blob: 356803ad7caf6c41bda4bcad7af46acbc249263d [file] [log] [blame]
Chris Lattner80f43d32010-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
14#include "InstCombine.h"
Eli Friedman74703252011-07-20 21:57:23 +000015#include "llvm/Analysis/ConstantFolding.h"
Chandler Carruth0b8c9a82013-01-02 11:36:10 +000016#include "llvm/IR/DataLayout.h"
Stephen Hines36b56882014-04-23 16:57:46 -070017#include "llvm/IR/PatternMatch.h"
Chandler Carruthd04a8d42012-12-03 16:50:05 +000018#include "llvm/Target/TargetLibraryInfo.h"
Chris Lattner80f43d32010-01-04 07:53:58 +000019using namespace llvm;
20using namespace PatternMatch;
21
Stephen Hinesdce4a402014-05-29 02:49:00 -070022#define DEBUG_TYPE "instcombine"
23
Chris Lattnerf3d1b5d2010-01-04 07:59:07 +000024/// DecomposeSimpleLinearExpr - Analyze 'Val', seeing if it is a simple linear
25/// expression. If so, decompose it, returning some value X, such that Val is
26/// X*Scale+Offset.
27///
28static Value *DecomposeSimpleLinearExpr(Value *Val, unsigned &Scale,
Dan Gohman28d2e0a2010-05-28 04:33:04 +000029 uint64_t &Offset) {
Chris Lattnerf3d1b5d2010-01-04 07:59:07 +000030 if (ConstantInt *CI = dyn_cast<ConstantInt>(Val)) {
31 Offset = CI->getZExtValue();
32 Scale = 0;
Dan Gohman28d2e0a2010-05-28 04:33:04 +000033 return ConstantInt::get(Val->getType(), 0);
Chris Lattnerf86d7992010-01-05 20:57:30 +000034 }
Craig Topperb57c2922013-01-24 05:22:40 +000035
Chris Lattnerf86d7992010-01-05 20:57:30 +000036 if (BinaryOperator *I = dyn_cast<BinaryOperator>(Val)) {
Bob Wilsone2e86f62011-07-08 22:09:33 +000037 // Cannot look past anything that might overflow.
38 OverflowingBinaryOperator *OBI = dyn_cast<OverflowingBinaryOperator>(Val);
Stepan Dyatkovskiy3f71cf12012-05-05 07:09:40 +000039 if (OBI && !OBI->hasNoUnsignedWrap() && !OBI->hasNoSignedWrap()) {
Bob Wilsone2e86f62011-07-08 22:09:33 +000040 Scale = 1;
41 Offset = 0;
42 return Val;
43 }
44
Chris Lattnerf3d1b5d2010-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 Gohman28d2e0a2010-05-28 04:33:04 +000048 Scale = UINT64_C(1) << RHS->getZExtValue();
Chris Lattnerf3d1b5d2010-01-04 07:59:07 +000049 Offset = 0;
50 return I->getOperand(0);
Chris Lattnerf86d7992010-01-05 20:57:30 +000051 }
Craig Topperb57c2922013-01-24 05:22:40 +000052
Chris Lattnerf86d7992010-01-05 20:57:30 +000053 if (I->getOpcode() == Instruction::Mul) {
Chris Lattnerf3d1b5d2010-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 Lattnerf86d7992010-01-05 20:57:30 +000058 }
Craig Topperb57c2922013-01-24 05:22:40 +000059
Chris Lattnerf86d7992010-01-05 20:57:30 +000060 if (I->getOpcode() == Instruction::Add) {
Craig Topperb57c2922013-01-24 05:22:40 +000061 // We have X+C. Check to see if we really have (X*C2)+C1,
Chris Lattnerf3d1b5d2010-01-04 07:59:07 +000062 // where C1 is divisible by C2.
63 unsigned SubScale;
Craig Topperb57c2922013-01-24 05:22:40 +000064 Value *SubVal =
Chris Lattnerf3d1b5d2010-01-04 07:59:07 +000065 DecomposeSimpleLinearExpr(I->getOperand(0), SubScale, Offset);
66 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
79/// PromoteCastOfAllocation - If we find a cast of an allocation instruction,
80/// try to eliminate the cast by moving the type information into the alloc.
81Instruction *InstCombiner::PromoteCastOfAllocation(BitCastInst &CI,
82 AllocaInst &AI) {
Micah Villmow3574eca2012-10-08 16:38:25 +000083 // This requires DataLayout to get the alloca alignment and size information.
Stephen Hinesdce4a402014-05-29 02:49:00 -070084 if (!DL) return nullptr;
Chris Lattnerf3d1b5d2010-01-04 07:59:07 +000085
Chris Lattnerdb125cf2011-07-18 04:54:35 +000086 PointerType *PTy = cast<PointerType>(CI.getType());
Craig Topperb57c2922013-01-24 05:22:40 +000087
Chris Lattnerf3d1b5d2010-01-04 07:59:07 +000088 BuilderTy AllocaBuilder(*Builder);
89 AllocaBuilder.SetInsertPoint(AI.getParent(), &AI);
90
91 // Get the type really allocated and the type casted to.
Chris Lattnerdb125cf2011-07-18 04:54:35 +000092 Type *AllocElTy = AI.getAllocatedType();
93 Type *CastElTy = PTy->getElementType();
Stephen Hinesdce4a402014-05-29 02:49:00 -070094 if (!AllocElTy->isSized() || !CastElTy->isSized()) return nullptr;
Chris Lattnerf3d1b5d2010-01-04 07:59:07 +000095
Stephen Hines36b56882014-04-23 16:57:46 -070096 unsigned AllocElTyAlign = DL->getABITypeAlignment(AllocElTy);
97 unsigned CastElTyAlign = DL->getABITypeAlignment(CastElTy);
Stephen Hinesdce4a402014-05-29 02:49:00 -070098 if (CastElTyAlign < AllocElTyAlign) return nullptr;
Chris Lattnerf3d1b5d2010-01-04 07:59:07 +000099
100 // If the allocation has multiple uses, only promote it if we are strictly
101 // increasing the alignment of the resultant allocation. If we keep it the
Devang Patel5aa3fa62011-03-08 22:12:11 +0000102 // same, we open the door to infinite loops of various kinds.
Stephen Hinesdce4a402014-05-29 02:49:00 -0700103 if (!AI.hasOneUse() && CastElTyAlign == AllocElTyAlign) return nullptr;
Chris Lattnerf3d1b5d2010-01-04 07:59:07 +0000104
Stephen Hines36b56882014-04-23 16:57:46 -0700105 uint64_t AllocElTySize = DL->getTypeAllocSize(AllocElTy);
106 uint64_t CastElTySize = DL->getTypeAllocSize(CastElTy);
Stephen Hinesdce4a402014-05-29 02:49:00 -0700107 if (CastElTySize == 0 || AllocElTySize == 0) return nullptr;
Chris Lattnerf3d1b5d2010-01-04 07:59:07 +0000108
Jim Grosbach186d8a32013-03-06 05:44:53 +0000109 // If the allocation has multiple uses, only promote it if we're not
110 // shrinking the amount of memory being allocated.
Stephen Hines36b56882014-04-23 16:57:46 -0700111 uint64_t AllocElTyStoreSize = DL->getTypeStoreSize(AllocElTy);
112 uint64_t CastElTyStoreSize = DL->getTypeStoreSize(CastElTy);
Stephen Hinesdce4a402014-05-29 02:49:00 -0700113 if (!AI.hasOneUse() && CastElTyStoreSize < AllocElTyStoreSize) return nullptr;
Jim Grosbach186d8a32013-03-06 05:44:53 +0000114
Chris Lattnerf3d1b5d2010-01-04 07:59:07 +0000115 // See if we can satisfy the modulus by pulling a scale out of the array
116 // size argument.
117 unsigned ArraySizeScale;
Dan Gohman28d2e0a2010-05-28 04:33:04 +0000118 uint64_t ArrayOffset;
Chris Lattnerf3d1b5d2010-01-04 07:59:07 +0000119 Value *NumElements = // See if the array size is a decomposable linear expr.
120 DecomposeSimpleLinearExpr(AI.getOperand(0), ArraySizeScale, ArrayOffset);
Craig Topperb57c2922013-01-24 05:22:40 +0000121
Chris Lattnerf3d1b5d2010-01-04 07:59:07 +0000122 // If we can now satisfy the modulus, by using a non-1 scale, we really can
123 // do the xform.
124 if ((AllocElTySize*ArraySizeScale) % CastElTySize != 0 ||
Stephen Hinesdce4a402014-05-29 02:49:00 -0700125 (AllocElTySize*ArrayOffset ) % CastElTySize != 0) return nullptr;
Chris Lattnerf3d1b5d2010-01-04 07:59:07 +0000126
127 unsigned Scale = (AllocElTySize*ArraySizeScale)/CastElTySize;
Stephen Hinesdce4a402014-05-29 02:49:00 -0700128 Value *Amt = nullptr;
Chris Lattnerf3d1b5d2010-01-04 07:59:07 +0000129 if (Scale == 1) {
130 Amt = NumElements;
131 } else {
Dan Gohman28d2e0a2010-05-28 04:33:04 +0000132 Amt = ConstantInt::get(AI.getArraySize()->getType(), Scale);
Chris Lattnerf3d1b5d2010-01-04 07:59:07 +0000133 // Insert before the alloca, not before the cast.
Benjamin Kramera9390a42011-09-27 20:39:19 +0000134 Amt = AllocaBuilder.CreateMul(Amt, NumElements);
Chris Lattnerf3d1b5d2010-01-04 07:59:07 +0000135 }
Craig Topperb57c2922013-01-24 05:22:40 +0000136
Dan Gohman28d2e0a2010-05-28 04:33:04 +0000137 if (uint64_t Offset = (AllocElTySize*ArrayOffset)/CastElTySize) {
138 Value *Off = ConstantInt::get(AI.getArraySize()->getType(),
Chris Lattnerf3d1b5d2010-01-04 07:59:07 +0000139 Offset, true);
Benjamin Kramera9390a42011-09-27 20:39:19 +0000140 Amt = AllocaBuilder.CreateAdd(Amt, Off);
Chris Lattnerf3d1b5d2010-01-04 07:59:07 +0000141 }
Craig Topperb57c2922013-01-24 05:22:40 +0000142
Chris Lattnerf3d1b5d2010-01-04 07:59:07 +0000143 AllocaInst *New = AllocaBuilder.CreateAlloca(CastElTy, Amt);
144 New->setAlignment(AI.getAlignment());
145 New->takeName(&AI);
Stephen Hinesdce4a402014-05-29 02:49:00 -0700146 New->setUsedWithInAlloca(AI.isUsedWithInAlloca());
Craig Topperb57c2922013-01-24 05:22:40 +0000147
Chris Lattnerf3d1b5d2010-01-04 07:59:07 +0000148 // If the allocation has multiple real uses, insert a cast and change all
149 // things that used it to use the new cast. This will also hack on CI, but it
150 // will die soon.
Devang Patel5aa3fa62011-03-08 22:12:11 +0000151 if (!AI.hasOneUse()) {
Chris Lattnerf3d1b5d2010-01-04 07:59:07 +0000152 // New is the allocation instruction, pointer typed. AI is the original
153 // allocation instruction, also pointer typed. Thus, cast to use is BitCast.
154 Value *NewCast = AllocaBuilder.CreateBitCast(New, AI.getType(), "tmpcast");
Eli Friedman3e22cb92011-05-18 00:32:01 +0000155 ReplaceInstUsesWith(AI, NewCast);
Chris Lattnerf3d1b5d2010-01-04 07:59:07 +0000156 }
157 return ReplaceInstUsesWith(CI, New);
158}
159
Craig Topperb57c2922013-01-24 05:22:40 +0000160/// EvaluateInDifferentType - Given an expression that
Chris Lattner14bf8f02010-01-08 19:19:23 +0000161/// CanEvaluateTruncated or CanEvaluateSExtd returns true for, actually
Chris Lattnere0e4cc72010-01-06 01:56:21 +0000162/// insert the code to evaluate the expression.
Craig Topperb57c2922013-01-24 05:22:40 +0000163Value *InstCombiner::EvaluateInDifferentType(Value *V, Type *Ty,
Chris Lattner5f0290e2010-01-04 07:54:59 +0000164 bool isSigned) {
Chris Lattnerc8b3fce2010-01-08 19:28:47 +0000165 if (Constant *C = dyn_cast<Constant>(V)) {
166 C = ConstantExpr::getIntegerCast(C, Ty, isSigned /*Sext or ZExt*/);
Stephen Hines36b56882014-04-23 16:57:46 -0700167 // If we got a constantexpr back, try to simplify it with DL info.
Chris Lattnerc8b3fce2010-01-08 19:28:47 +0000168 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(C))
Stephen Hines36b56882014-04-23 16:57:46 -0700169 C = ConstantFoldConstantExpression(CE, DL, TLI);
Chris Lattnerc8b3fce2010-01-08 19:28:47 +0000170 return C;
171 }
Chris Lattner5f0290e2010-01-04 07:54:59 +0000172
173 // Otherwise, it must be an instruction.
174 Instruction *I = cast<Instruction>(V);
Stephen Hinesdce4a402014-05-29 02:49:00 -0700175 Instruction *Res = nullptr;
Chris Lattner5f0290e2010-01-04 07:54:59 +0000176 unsigned Opc = I->getOpcode();
177 switch (Opc) {
178 case Instruction::Add:
179 case Instruction::Sub:
180 case Instruction::Mul:
181 case Instruction::And:
182 case Instruction::Or:
183 case Instruction::Xor:
184 case Instruction::AShr:
185 case Instruction::LShr:
186 case Instruction::Shl:
187 case Instruction::UDiv:
188 case Instruction::URem: {
189 Value *LHS = EvaluateInDifferentType(I->getOperand(0), Ty, isSigned);
190 Value *RHS = EvaluateInDifferentType(I->getOperand(1), Ty, isSigned);
191 Res = BinaryOperator::Create((Instruction::BinaryOps)Opc, LHS, RHS);
192 break;
Craig Topperb57c2922013-01-24 05:22:40 +0000193 }
Chris Lattner5f0290e2010-01-04 07:54:59 +0000194 case Instruction::Trunc:
195 case Instruction::ZExt:
196 case Instruction::SExt:
197 // If the source type of the cast is the type we're trying for then we can
198 // just return the source. There's no need to insert it because it is not
199 // new.
200 if (I->getOperand(0)->getType() == Ty)
201 return I->getOperand(0);
Craig Topperb57c2922013-01-24 05:22:40 +0000202
Chris Lattner5f0290e2010-01-04 07:54:59 +0000203 // Otherwise, must be the same type of cast, so just reinsert a new one.
Chris Lattner9ee947c2010-01-10 20:25:54 +0000204 // This also handles the case of zext(trunc(x)) -> zext(x).
205 Res = CastInst::CreateIntegerCast(I->getOperand(0), Ty,
206 Opc == Instruction::SExt);
Chris Lattner5f0290e2010-01-04 07:54:59 +0000207 break;
208 case Instruction::Select: {
209 Value *True = EvaluateInDifferentType(I->getOperand(1), Ty, isSigned);
210 Value *False = EvaluateInDifferentType(I->getOperand(2), Ty, isSigned);
211 Res = SelectInst::Create(I->getOperand(0), True, False);
212 break;
213 }
214 case Instruction::PHI: {
215 PHINode *OPN = cast<PHINode>(I);
Jay Foad3ecfc862011-03-30 11:28:46 +0000216 PHINode *NPN = PHINode::Create(Ty, OPN->getNumIncomingValues());
Chris Lattner5f0290e2010-01-04 07:54:59 +0000217 for (unsigned i = 0, e = OPN->getNumIncomingValues(); i != e; ++i) {
218 Value *V =EvaluateInDifferentType(OPN->getIncomingValue(i), Ty, isSigned);
219 NPN->addIncoming(V, OPN->getIncomingBlock(i));
220 }
221 Res = NPN;
222 break;
223 }
Craig Topperb57c2922013-01-24 05:22:40 +0000224 default:
Chris Lattner5f0290e2010-01-04 07:54:59 +0000225 // TODO: Can handle more cases here.
226 llvm_unreachable("Unreachable!");
Chris Lattner5f0290e2010-01-04 07:54:59 +0000227 }
Craig Topperb57c2922013-01-24 05:22:40 +0000228
Chris Lattner5f0290e2010-01-04 07:54:59 +0000229 Res->takeName(I);
Eli Friedmana311c342011-05-27 00:19:40 +0000230 return InsertNewInstWith(Res, *I);
Chris Lattner5f0290e2010-01-04 07:54:59 +0000231}
Chris Lattner80f43d32010-01-04 07:53:58 +0000232
233
234/// This function is a wrapper around CastInst::isEliminableCastPair. It
235/// simply extracts arguments and returns what that function returns.
Craig Topperb57c2922013-01-24 05:22:40 +0000236static Instruction::CastOps
Chris Lattner80f43d32010-01-04 07:53:58 +0000237isEliminableCastPair(
238 const CastInst *CI, ///< The first cast instruction
239 unsigned opcode, ///< The opcode of the second cast instruction
Chris Lattnerdb125cf2011-07-18 04:54:35 +0000240 Type *DstTy, ///< The target type for the second cast instruction
Stephen Hines36b56882014-04-23 16:57:46 -0700241 const DataLayout *DL ///< The target data for pointer size
Chris Lattner80f43d32010-01-04 07:53:58 +0000242) {
243
Chris Lattnerdb125cf2011-07-18 04:54:35 +0000244 Type *SrcTy = CI->getOperand(0)->getType(); // A from above
245 Type *MidTy = CI->getType(); // B from above
Chris Lattner80f43d32010-01-04 07:53:58 +0000246
247 // Get the opcodes of the two Cast instructions
248 Instruction::CastOps firstOp = Instruction::CastOps(CI->getOpcode());
249 Instruction::CastOps secondOp = Instruction::CastOps(opcode);
Stephen Hines36b56882014-04-23 16:57:46 -0700250 Type *SrcIntPtrTy = DL && SrcTy->isPtrOrPtrVectorTy() ?
Stephen Hinesdce4a402014-05-29 02:49:00 -0700251 DL->getIntPtrType(SrcTy) : nullptr;
Stephen Hines36b56882014-04-23 16:57:46 -0700252 Type *MidIntPtrTy = DL && MidTy->isPtrOrPtrVectorTy() ?
Stephen Hinesdce4a402014-05-29 02:49:00 -0700253 DL->getIntPtrType(MidTy) : nullptr;
Stephen Hines36b56882014-04-23 16:57:46 -0700254 Type *DstIntPtrTy = DL && DstTy->isPtrOrPtrVectorTy() ?
Stephen Hinesdce4a402014-05-29 02:49:00 -0700255 DL->getIntPtrType(DstTy) : nullptr;
Chris Lattner80f43d32010-01-04 07:53:58 +0000256 unsigned Res = CastInst::isEliminableCastPair(firstOp, secondOp, SrcTy, MidTy,
Duncan Sands446cf942012-10-30 16:03:32 +0000257 DstTy, SrcIntPtrTy, MidIntPtrTy,
258 DstIntPtrTy);
Micah Villmowaa76e9e2012-10-24 15:52:52 +0000259
Chris Lattner80f43d32010-01-04 07:53:58 +0000260 // We don't want to form an inttoptr or ptrtoint that converts to an integer
261 // type that differs from the pointer size.
Duncan Sands446cf942012-10-30 16:03:32 +0000262 if ((Res == Instruction::IntToPtr && SrcTy != DstIntPtrTy) ||
263 (Res == Instruction::PtrToInt && DstTy != SrcIntPtrTy))
Chris Lattner80f43d32010-01-04 07:53:58 +0000264 Res = 0;
Craig Topperb57c2922013-01-24 05:22:40 +0000265
Chris Lattner80f43d32010-01-04 07:53:58 +0000266 return Instruction::CastOps(Res);
267}
268
Chris Lattner8c5ad3a2010-02-11 06:26:33 +0000269/// ShouldOptimizeCast - Return true if the cast from "V to Ty" actually
270/// results in any code being generated and is interesting to optimize out. If
271/// the cast can be eliminated by some other simple transformation, we prefer
272/// to do the simplification first.
273bool InstCombiner::ShouldOptimizeCast(Instruction::CastOps opc, const Value *V,
Chris Lattnerdb125cf2011-07-18 04:54:35 +0000274 Type *Ty) {
Chris Lattner8c5ad3a2010-02-11 06:26:33 +0000275 // Noop casts and casts of constants should be eliminated trivially.
Chris Lattner80f43d32010-01-04 07:53:58 +0000276 if (V->getType() == Ty || isa<Constant>(V)) return false;
Craig Topperb57c2922013-01-24 05:22:40 +0000277
Chris Lattner8c5ad3a2010-02-11 06:26:33 +0000278 // If this is another cast that can be eliminated, we prefer to have it
279 // eliminated.
Chris Lattner80f43d32010-01-04 07:53:58 +0000280 if (const CastInst *CI = dyn_cast<CastInst>(V))
Stephen Hines36b56882014-04-23 16:57:46 -0700281 if (isEliminableCastPair(CI, opc, Ty, DL))
Chris Lattner80f43d32010-01-04 07:53:58 +0000282 return false;
Craig Topperb57c2922013-01-24 05:22:40 +0000283
Chris Lattner8c5ad3a2010-02-11 06:26:33 +0000284 // If this is a vector sext from a compare, then we don't want to break the
285 // idiom where each element of the extended vector is either zero or all ones.
Duncan Sands1df98592010-02-16 11:11:14 +0000286 if (opc == Instruction::SExt && isa<CmpInst>(V) && Ty->isVectorTy())
Chris Lattner8c5ad3a2010-02-11 06:26:33 +0000287 return false;
Craig Topperb57c2922013-01-24 05:22:40 +0000288
Chris Lattner80f43d32010-01-04 07:53:58 +0000289 return true;
290}
291
292
293/// @brief Implement the transforms common to all CastInst visitors.
294Instruction *InstCombiner::commonCastTransforms(CastInst &CI) {
295 Value *Src = CI.getOperand(0);
296
297 // Many cases of "cast of a cast" are eliminable. If it's eliminable we just
298 // eliminate it now.
299 if (CastInst *CSrc = dyn_cast<CastInst>(Src)) { // A->B->C cast
Craig Topperb57c2922013-01-24 05:22:40 +0000300 if (Instruction::CastOps opc =
Stephen Hines36b56882014-04-23 16:57:46 -0700301 isEliminableCastPair(CSrc, CI.getOpcode(), CI.getType(), DL)) {
Chris Lattner80f43d32010-01-04 07:53:58 +0000302 // The first cast (CSrc) is eliminable so we need to fix up or replace
303 // the second cast (CI). CSrc will then have a good chance of being dead.
304 return CastInst::Create(opc, CSrc->getOperand(0), CI.getType());
305 }
306 }
307
308 // If we are casting a select then fold the cast into the select
309 if (SelectInst *SI = dyn_cast<SelectInst>(Src))
310 if (Instruction *NV = FoldOpIntoSelect(CI, SI))
311 return NV;
312
313 // If we are casting a PHI then fold the cast into the PHI
314 if (isa<PHINode>(Src)) {
315 // We don't do this if this would create a PHI node with an illegal type if
316 // it is currently legal.
Duncan Sands1df98592010-02-16 11:11:14 +0000317 if (!Src->getType()->isIntegerTy() ||
318 !CI.getType()->isIntegerTy() ||
Chris Lattner80f43d32010-01-04 07:53:58 +0000319 ShouldChangeType(CI.getType(), Src->getType()))
320 if (Instruction *NV = FoldOpIntoPhi(CI))
321 return NV;
322 }
Craig Topperb57c2922013-01-24 05:22:40 +0000323
Stephen Hinesdce4a402014-05-29 02:49:00 -0700324 return nullptr;
Chris Lattner80f43d32010-01-04 07:53:58 +0000325}
326
Chris Lattner75215c92010-01-10 00:58:42 +0000327/// CanEvaluateTruncated - Return true if we can evaluate the specified
328/// expression tree as type Ty instead of its larger type, and arrive with the
329/// same value. This is used by code that tries to eliminate truncates.
330///
331/// Ty will always be a type smaller than V. We should return true if trunc(V)
332/// can be computed by computing V in the smaller type. If V is an instruction,
333/// then trunc(inst(x,y)) can be computed as inst(trunc(x),trunc(y)), which only
334/// makes sense if x and y can be efficiently truncated.
335///
Chris Lattner8cf4f6f2010-01-11 02:43:35 +0000336/// This function works on both vectors and scalars.
337///
Chris Lattnerdb125cf2011-07-18 04:54:35 +0000338static bool CanEvaluateTruncated(Value *V, Type *Ty) {
Chris Lattner75215c92010-01-10 00:58:42 +0000339 // We can always evaluate constants in another type.
340 if (isa<Constant>(V))
341 return true;
Craig Topperb57c2922013-01-24 05:22:40 +0000342
Chris Lattner75215c92010-01-10 00:58:42 +0000343 Instruction *I = dyn_cast<Instruction>(V);
344 if (!I) return false;
Craig Topperb57c2922013-01-24 05:22:40 +0000345
Chris Lattnerdb125cf2011-07-18 04:54:35 +0000346 Type *OrigTy = V->getType();
Craig Topperb57c2922013-01-24 05:22:40 +0000347
Chris Lattnera958cbf2010-01-11 22:45:25 +0000348 // If this is an extension from the dest type, we can eliminate it, even if it
349 // has multiple uses.
Craig Topperb57c2922013-01-24 05:22:40 +0000350 if ((isa<ZExtInst>(I) || isa<SExtInst>(I)) &&
Chris Lattner75215c92010-01-10 00:58:42 +0000351 I->getOperand(0)->getType() == Ty)
352 return true;
353
354 // We can't extend or shrink something that has multiple uses: doing so would
355 // require duplicating the instruction in general, which isn't profitable.
356 if (!I->hasOneUse()) return false;
357
358 unsigned Opc = I->getOpcode();
359 switch (Opc) {
360 case Instruction::Add:
361 case Instruction::Sub:
362 case Instruction::Mul:
363 case Instruction::And:
364 case Instruction::Or:
365 case Instruction::Xor:
366 // These operators can all arbitrarily be extended or truncated.
367 return CanEvaluateTruncated(I->getOperand(0), Ty) &&
368 CanEvaluateTruncated(I->getOperand(1), Ty);
369
370 case Instruction::UDiv:
371 case Instruction::URem: {
372 // UDiv and URem can be truncated if all the truncated bits are zero.
373 uint32_t OrigBitWidth = OrigTy->getScalarSizeInBits();
374 uint32_t BitWidth = Ty->getScalarSizeInBits();
375 if (BitWidth < OrigBitWidth) {
376 APInt Mask = APInt::getHighBitsSet(OrigBitWidth, OrigBitWidth-BitWidth);
377 if (MaskedValueIsZero(I->getOperand(0), Mask) &&
378 MaskedValueIsZero(I->getOperand(1), Mask)) {
379 return CanEvaluateTruncated(I->getOperand(0), Ty) &&
380 CanEvaluateTruncated(I->getOperand(1), Ty);
381 }
382 }
383 break;
384 }
385 case Instruction::Shl:
386 // If we are truncating the result of this SHL, and if it's a shift of a
387 // constant amount, we can always perform a SHL in a smaller type.
388 if (ConstantInt *CI = dyn_cast<ConstantInt>(I->getOperand(1))) {
389 uint32_t BitWidth = Ty->getScalarSizeInBits();
390 if (CI->getLimitedValue(BitWidth) < BitWidth)
391 return CanEvaluateTruncated(I->getOperand(0), Ty);
392 }
393 break;
394 case Instruction::LShr:
395 // If this is a truncate of a logical shr, we can truncate it to a smaller
Sylvestre Ledru94c22712012-09-27 10:14:43 +0000396 // lshr iff we know that the bits we would otherwise be shifting in are
Chris Lattner75215c92010-01-10 00:58:42 +0000397 // already zeros.
398 if (ConstantInt *CI = dyn_cast<ConstantInt>(I->getOperand(1))) {
399 uint32_t OrigBitWidth = OrigTy->getScalarSizeInBits();
400 uint32_t BitWidth = Ty->getScalarSizeInBits();
401 if (MaskedValueIsZero(I->getOperand(0),
402 APInt::getHighBitsSet(OrigBitWidth, OrigBitWidth-BitWidth)) &&
403 CI->getLimitedValue(BitWidth) < BitWidth) {
404 return CanEvaluateTruncated(I->getOperand(0), Ty);
405 }
406 }
407 break;
408 case Instruction::Trunc:
409 // trunc(trunc(x)) -> trunc(x)
410 return true;
Chris Lattnerf9d05ab2010-08-27 20:32:06 +0000411 case Instruction::ZExt:
412 case Instruction::SExt:
413 // trunc(ext(x)) -> ext(x) if the source type is smaller than the new dest
414 // trunc(ext(x)) -> trunc(x) if the source type is larger than the new dest
415 return true;
Chris Lattner75215c92010-01-10 00:58:42 +0000416 case Instruction::Select: {
417 SelectInst *SI = cast<SelectInst>(I);
418 return CanEvaluateTruncated(SI->getTrueValue(), Ty) &&
419 CanEvaluateTruncated(SI->getFalseValue(), Ty);
420 }
421 case Instruction::PHI: {
422 // We can change a phi if we can change all operands. Note that we never
423 // get into trouble with cyclic PHIs here because we only consider
424 // instructions with a single use.
425 PHINode *PN = cast<PHINode>(I);
426 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i)
427 if (!CanEvaluateTruncated(PN->getIncomingValue(i), Ty))
428 return false;
429 return true;
430 }
431 default:
432 // TODO: Can handle more cases here.
433 break;
434 }
Craig Topperb57c2922013-01-24 05:22:40 +0000435
Chris Lattner75215c92010-01-10 00:58:42 +0000436 return false;
437}
438
439Instruction *InstCombiner::visitTrunc(TruncInst &CI) {
Chris Lattnerd84dfa42010-01-10 01:00:46 +0000440 if (Instruction *Result = commonCastTransforms(CI))
Chris Lattner75215c92010-01-10 00:58:42 +0000441 return Result;
Craig Topperb57c2922013-01-24 05:22:40 +0000442
443 // See if we can simplify any instructions used by the input whose sole
Chris Lattnerd84dfa42010-01-10 01:00:46 +0000444 // purpose is to compute bits we don't care about.
445 if (SimplifyDemandedInstructionBits(CI))
446 return &CI;
Craig Topperb57c2922013-01-24 05:22:40 +0000447
Chris Lattner75215c92010-01-10 00:58:42 +0000448 Value *Src = CI.getOperand(0);
Chris Lattnerdb125cf2011-07-18 04:54:35 +0000449 Type *DestTy = CI.getType(), *SrcTy = Src->getType();
Craig Topperb57c2922013-01-24 05:22:40 +0000450
Chris Lattner75215c92010-01-10 00:58:42 +0000451 // Attempt to truncate the entire input expression tree to the destination
452 // type. Only do this if the dest type is a simple type, don't convert the
Chris Lattner80f43d32010-01-04 07:53:58 +0000453 // expression tree to something weird like i93 unless the source is also
454 // strange.
Duncan Sands1df98592010-02-16 11:11:14 +0000455 if ((DestTy->isVectorTy() || ShouldChangeType(SrcTy, DestTy)) &&
Chris Lattner75215c92010-01-10 00:58:42 +0000456 CanEvaluateTruncated(Src, DestTy)) {
Craig Topperb57c2922013-01-24 05:22:40 +0000457
Chris Lattner80f43d32010-01-04 07:53:58 +0000458 // If this cast is a truncate, evaluting in a different type always
Chris Lattner68c6e892010-01-05 23:00:30 +0000459 // eliminates the cast, so it is always a win.
Chris Lattner075f6922010-01-07 23:41:00 +0000460 DEBUG(dbgs() << "ICE: EvaluateInDifferentType converting expression type"
Dan Gohman5b71dce2010-05-25 21:50:35 +0000461 " to avoid cast: " << CI << '\n');
Chris Lattner075f6922010-01-07 23:41:00 +0000462 Value *Res = EvaluateInDifferentType(Src, DestTy, false);
463 assert(Res->getType() == DestTy);
464 return ReplaceInstUsesWith(CI, Res);
465 }
Chris Lattner80f43d32010-01-04 07:53:58 +0000466
Chris Lattner7a34d6c2010-01-05 22:21:18 +0000467 // Canonicalize trunc x to i1 -> (icmp ne (and x, 1), 0), likewise for vector.
468 if (DestTy->getScalarSizeInBits() == 1) {
Chris Lattner80f43d32010-01-04 07:53:58 +0000469 Constant *One = ConstantInt::get(Src->getType(), 1);
Benjamin Kramera9390a42011-09-27 20:39:19 +0000470 Src = Builder->CreateAnd(Src, One);
Chris Lattner80f43d32010-01-04 07:53:58 +0000471 Value *Zero = Constant::getNullValue(Src->getType());
472 return new ICmpInst(ICmpInst::ICMP_NE, Src, Zero);
473 }
Craig Topperb57c2922013-01-24 05:22:40 +0000474
Chris Lattner784f3332010-08-27 18:31:05 +0000475 // Transform trunc(lshr (zext A), Cst) to eliminate one type conversion.
Stephen Hinesdce4a402014-05-29 02:49:00 -0700476 Value *A = nullptr; ConstantInt *Cst = nullptr;
Chris Lattner62fe4062011-01-15 06:32:33 +0000477 if (Src->hasOneUse() &&
478 match(Src, m_LShr(m_ZExt(m_Value(A)), m_ConstantInt(Cst)))) {
Chris Lattner784f3332010-08-27 18:31:05 +0000479 // We have three types to worry about here, the type of A, the source of
480 // the truncate (MidSize), and the destination of the truncate. We know that
481 // ASize < MidSize and MidSize > ResultSize, but don't know the relation
482 // between ASize and ResultSize.
483 unsigned ASize = A->getType()->getPrimitiveSizeInBits();
Craig Topperb57c2922013-01-24 05:22:40 +0000484
Chris Lattner784f3332010-08-27 18:31:05 +0000485 // If the shift amount is larger than the size of A, then the result is
486 // known to be zero because all the input bits got shifted out.
487 if (Cst->getZExtValue() >= ASize)
488 return ReplaceInstUsesWith(CI, Constant::getNullValue(CI.getType()));
489
490 // Since we're doing an lshr and a zero extend, and know that the shift
491 // amount is smaller than ASize, it is always safe to do the shift in A's
492 // type, then zero extend or truncate to the result.
493 Value *Shift = Builder->CreateLShr(A, Cst->getZExtValue());
494 Shift->takeName(Src);
495 return CastInst::CreateIntegerCast(Shift, CI.getType(), false);
496 }
Craig Topperb57c2922013-01-24 05:22:40 +0000497
Chris Lattner62fe4062011-01-15 06:32:33 +0000498 // Transform "trunc (and X, cst)" -> "and (trunc X), cst" so long as the dest
499 // type isn't non-native.
500 if (Src->hasOneUse() && isa<IntegerType>(Src->getType()) &&
501 ShouldChangeType(Src->getType(), CI.getType()) &&
502 match(Src, m_And(m_Value(A), m_ConstantInt(Cst)))) {
503 Value *NewTrunc = Builder->CreateTrunc(A, CI.getType(), A->getName()+".tr");
504 return BinaryOperator::CreateAnd(NewTrunc,
505 ConstantExpr::getTrunc(Cst, CI.getType()));
506 }
Chris Lattner80f43d32010-01-04 07:53:58 +0000507
Stephen Hinesdce4a402014-05-29 02:49:00 -0700508 return nullptr;
Chris Lattner80f43d32010-01-04 07:53:58 +0000509}
510
511/// transformZExtICmp - Transform (zext icmp) to bitwise / integer operations
512/// in order to eliminate the icmp.
513Instruction *InstCombiner::transformZExtICmp(ICmpInst *ICI, Instruction &CI,
514 bool DoXform) {
515 // If we are just checking for a icmp eq of a single bit and zext'ing it
516 // to an integer, then shift the bit to the appropriate place and then
517 // cast to integer to avoid the comparison.
518 if (ConstantInt *Op1C = dyn_cast<ConstantInt>(ICI->getOperand(1))) {
519 const APInt &Op1CV = Op1C->getValue();
Craig Topperb57c2922013-01-24 05:22:40 +0000520
Chris Lattner80f43d32010-01-04 07:53:58 +0000521 // zext (x <s 0) to i32 --> x>>u31 true if signbit set.
522 // zext (x >s -1) to i32 --> (x>>u31)^1 true if signbit clear.
523 if ((ICI->getPredicate() == ICmpInst::ICMP_SLT && Op1CV == 0) ||
524 (ICI->getPredicate() == ICmpInst::ICMP_SGT &&Op1CV.isAllOnesValue())) {
525 if (!DoXform) return ICI;
526
527 Value *In = ICI->getOperand(0);
528 Value *Sh = ConstantInt::get(In->getType(),
529 In->getType()->getScalarSizeInBits()-1);
530 In = Builder->CreateLShr(In, Sh, In->getName()+".lobit");
531 if (In->getType() != CI.getType())
Benjamin Kramera9390a42011-09-27 20:39:19 +0000532 In = Builder->CreateIntCast(In, CI.getType(), false/*ZExt*/);
Chris Lattner80f43d32010-01-04 07:53:58 +0000533
534 if (ICI->getPredicate() == ICmpInst::ICMP_SGT) {
535 Constant *One = ConstantInt::get(In->getType(), 1);
536 In = Builder->CreateXor(In, One, In->getName()+".not");
537 }
538
539 return ReplaceInstUsesWith(CI, In);
540 }
Chad Rosiercaebb1e2011-11-30 01:59:59 +0000541
Sylvestre Ledru94c22712012-09-27 10:14:43 +0000542 // zext (X == 0) to i32 --> X^1 iff X has only the low bit set.
543 // zext (X == 0) to i32 --> (X>>1)^1 iff X has only the 2nd bit set.
544 // zext (X == 1) to i32 --> X iff X has only the low bit set.
545 // zext (X == 2) to i32 --> X>>1 iff X has only the 2nd bit set.
546 // zext (X != 0) to i32 --> X iff X has only the low bit set.
547 // zext (X != 0) to i32 --> X>>1 iff X has only the 2nd bit set.
548 // zext (X != 1) to i32 --> X^1 iff X has only the low bit set.
549 // zext (X != 2) to i32 --> (X>>1)^1 iff X has only the 2nd bit set.
Craig Topperb57c2922013-01-24 05:22:40 +0000550 if ((Op1CV == 0 || Op1CV.isPowerOf2()) &&
Chris Lattner80f43d32010-01-04 07:53:58 +0000551 // This only works for EQ and NE
552 ICI->isEquality()) {
553 // If Op1C some other power of two, convert:
554 uint32_t BitWidth = Op1C->getType()->getBitWidth();
555 APInt KnownZero(BitWidth, 0), KnownOne(BitWidth, 0);
Stephen Hinesdce4a402014-05-29 02:49:00 -0700556 computeKnownBits(ICI->getOperand(0), KnownZero, KnownOne);
Craig Topperb57c2922013-01-24 05:22:40 +0000557
Chris Lattner80f43d32010-01-04 07:53:58 +0000558 APInt KnownZeroMask(~KnownZero);
559 if (KnownZeroMask.isPowerOf2()) { // Exactly 1 possible 1?
560 if (!DoXform) return ICI;
561
562 bool isNE = ICI->getPredicate() == ICmpInst::ICMP_NE;
563 if (Op1CV != 0 && (Op1CV != KnownZeroMask)) {
564 // (X&4) == 2 --> false
565 // (X&4) != 2 --> true
566 Constant *Res = ConstantInt::get(Type::getInt1Ty(CI.getContext()),
567 isNE);
568 Res = ConstantExpr::getZExt(Res, CI.getType());
569 return ReplaceInstUsesWith(CI, Res);
570 }
Craig Topperb57c2922013-01-24 05:22:40 +0000571
Chris Lattner80f43d32010-01-04 07:53:58 +0000572 uint32_t ShiftAmt = KnownZeroMask.logBase2();
573 Value *In = ICI->getOperand(0);
574 if (ShiftAmt) {
575 // Perform a logical shr by shiftamt.
576 // Insert the shift to put the result in the low bit.
577 In = Builder->CreateLShr(In, ConstantInt::get(In->getType(),ShiftAmt),
578 In->getName()+".lobit");
579 }
Craig Topperb57c2922013-01-24 05:22:40 +0000580
Chris Lattner80f43d32010-01-04 07:53:58 +0000581 if ((Op1CV != 0) == isNE) { // Toggle the low bit.
582 Constant *One = ConstantInt::get(In->getType(), 1);
Benjamin Kramera9390a42011-09-27 20:39:19 +0000583 In = Builder->CreateXor(In, One);
Chris Lattner80f43d32010-01-04 07:53:58 +0000584 }
Craig Topperb57c2922013-01-24 05:22:40 +0000585
Chris Lattner80f43d32010-01-04 07:53:58 +0000586 if (CI.getType() == In->getType())
587 return ReplaceInstUsesWith(CI, In);
Chris Lattner29cc0b32010-08-27 22:24:38 +0000588 return CastInst::CreateIntegerCast(In, CI.getType(), false/*ZExt*/);
Chris Lattner80f43d32010-01-04 07:53:58 +0000589 }
590 }
591 }
592
593 // icmp ne A, B is equal to xor A, B when A and B only really have one bit.
594 // It is also profitable to transform icmp eq into not(xor(A, B)) because that
595 // may lead to additional simplifications.
596 if (ICI->isEquality() && CI.getType() == ICI->getOperand(0)->getType()) {
Chris Lattnerdb125cf2011-07-18 04:54:35 +0000597 if (IntegerType *ITy = dyn_cast<IntegerType>(CI.getType())) {
Chris Lattner80f43d32010-01-04 07:53:58 +0000598 uint32_t BitWidth = ITy->getBitWidth();
599 Value *LHS = ICI->getOperand(0);
600 Value *RHS = ICI->getOperand(1);
601
602 APInt KnownZeroLHS(BitWidth, 0), KnownOneLHS(BitWidth, 0);
603 APInt KnownZeroRHS(BitWidth, 0), KnownOneRHS(BitWidth, 0);
Stephen Hinesdce4a402014-05-29 02:49:00 -0700604 computeKnownBits(LHS, KnownZeroLHS, KnownOneLHS);
605 computeKnownBits(RHS, KnownZeroRHS, KnownOneRHS);
Chris Lattner80f43d32010-01-04 07:53:58 +0000606
607 if (KnownZeroLHS == KnownZeroRHS && KnownOneLHS == KnownOneRHS) {
608 APInt KnownBits = KnownZeroLHS | KnownOneLHS;
609 APInt UnknownBit = ~KnownBits;
610 if (UnknownBit.countPopulation() == 1) {
611 if (!DoXform) return ICI;
612
613 Value *Result = Builder->CreateXor(LHS, RHS);
614
615 // Mask off any bits that are set and won't be shifted away.
616 if (KnownOneLHS.uge(UnknownBit))
617 Result = Builder->CreateAnd(Result,
618 ConstantInt::get(ITy, UnknownBit));
619
620 // Shift the bit we're testing down to the lsb.
621 Result = Builder->CreateLShr(
622 Result, ConstantInt::get(ITy, UnknownBit.countTrailingZeros()));
623
624 if (ICI->getPredicate() == ICmpInst::ICMP_EQ)
625 Result = Builder->CreateXor(Result, ConstantInt::get(ITy, 1));
626 Result->takeName(ICI);
627 return ReplaceInstUsesWith(CI, Result);
628 }
629 }
630 }
631 }
632
Stephen Hinesdce4a402014-05-29 02:49:00 -0700633 return nullptr;
Chris Lattner80f43d32010-01-04 07:53:58 +0000634}
635
Chris Lattner75215c92010-01-10 00:58:42 +0000636/// CanEvaluateZExtd - Determine if the specified value can be computed in the
Chris Lattner8cf4f6f2010-01-11 02:43:35 +0000637/// specified wider type and produce the same low bits. If not, return false.
638///
Chris Lattner789162a2010-01-11 03:32:00 +0000639/// If this function returns true, it can also return a non-zero number of bits
640/// (in BitsToClear) which indicates that the value it computes is correct for
641/// the zero extend, but that the additional BitsToClear bits need to be zero'd
642/// out. For example, to promote something like:
643///
644/// %B = trunc i64 %A to i32
645/// %C = lshr i32 %B, 8
646/// %E = zext i32 %C to i64
647///
648/// CanEvaluateZExtd for the 'lshr' will return true, and BitsToClear will be
649/// set to 8 to indicate that the promoted value needs to have bits 24-31
650/// cleared in addition to bits 32-63. Since an 'and' will be generated to
651/// clear the top bits anyway, doing this has no extra cost.
652///
Chris Lattner8cf4f6f2010-01-11 02:43:35 +0000653/// This function works on both vectors and scalars.
Chris Lattnerdb125cf2011-07-18 04:54:35 +0000654static bool CanEvaluateZExtd(Value *V, Type *Ty, unsigned &BitsToClear) {
Chris Lattner789162a2010-01-11 03:32:00 +0000655 BitsToClear = 0;
Chris Lattner9e390dd2010-01-10 02:50:04 +0000656 if (isa<Constant>(V))
657 return true;
Craig Topperb57c2922013-01-24 05:22:40 +0000658
Chris Lattner75215c92010-01-10 00:58:42 +0000659 Instruction *I = dyn_cast<Instruction>(V);
Chris Lattner9e390dd2010-01-10 02:50:04 +0000660 if (!I) return false;
Craig Topperb57c2922013-01-24 05:22:40 +0000661
Chris Lattner75215c92010-01-10 00:58:42 +0000662 // If the input is a truncate from the destination type, we can trivially
Jakob Stoklund Olesen7ee3ca12012-06-22 16:36:43 +0000663 // eliminate it.
664 if (isa<TruncInst>(I) && I->getOperand(0)->getType() == Ty)
Chris Lattner9e390dd2010-01-10 02:50:04 +0000665 return true;
Craig Topperb57c2922013-01-24 05:22:40 +0000666
Chris Lattner75215c92010-01-10 00:58:42 +0000667 // We can't extend or shrink something that has multiple uses: doing so would
668 // require duplicating the instruction in general, which isn't profitable.
Chris Lattner9e390dd2010-01-10 02:50:04 +0000669 if (!I->hasOneUse()) return false;
Craig Topperb57c2922013-01-24 05:22:40 +0000670
Chris Lattner789162a2010-01-11 03:32:00 +0000671 unsigned Opc = I->getOpcode(), Tmp;
Chris Lattner75215c92010-01-10 00:58:42 +0000672 switch (Opc) {
Chris Lattner9ee947c2010-01-10 20:25:54 +0000673 case Instruction::ZExt: // zext(zext(x)) -> zext(x).
674 case Instruction::SExt: // zext(sext(x)) -> sext(x).
675 case Instruction::Trunc: // zext(trunc(x)) -> trunc(x) or zext(x)
676 return true;
Chris Lattner75215c92010-01-10 00:58:42 +0000677 case Instruction::And:
Chris Lattner75215c92010-01-10 00:58:42 +0000678 case Instruction::Or:
679 case Instruction::Xor:
Chris Lattner75215c92010-01-10 00:58:42 +0000680 case Instruction::Add:
681 case Instruction::Sub:
682 case Instruction::Mul:
Chris Lattner789162a2010-01-11 03:32:00 +0000683 if (!CanEvaluateZExtd(I->getOperand(0), Ty, BitsToClear) ||
684 !CanEvaluateZExtd(I->getOperand(1), Ty, Tmp))
685 return false;
686 // These can all be promoted if neither operand has 'bits to clear'.
687 if (BitsToClear == 0 && Tmp == 0)
688 return true;
Craig Topperb57c2922013-01-24 05:22:40 +0000689
Chris Lattner7acc4b12010-01-11 04:05:13 +0000690 // If the operation is an AND/OR/XOR and the bits to clear are zero in the
691 // other side, BitsToClear is ok.
692 if (Tmp == 0 &&
693 (Opc == Instruction::And || Opc == Instruction::Or ||
694 Opc == Instruction::Xor)) {
695 // We use MaskedValueIsZero here for generality, but the case we care
696 // about the most is constant RHS.
697 unsigned VSize = V->getType()->getScalarSizeInBits();
698 if (MaskedValueIsZero(I->getOperand(1),
699 APInt::getHighBitsSet(VSize, BitsToClear)))
700 return true;
701 }
Craig Topperb57c2922013-01-24 05:22:40 +0000702
Chris Lattner7acc4b12010-01-11 04:05:13 +0000703 // Otherwise, we don't know how to analyze this BitsToClear case yet.
Chris Lattner789162a2010-01-11 03:32:00 +0000704 return false;
Craig Topperb57c2922013-01-24 05:22:40 +0000705
Benjamin Kramer7159a302013-05-10 16:26:37 +0000706 case Instruction::Shl:
707 // We can promote shl(x, cst) if we can promote x. Since shl overwrites the
708 // upper bits we can reduce BitsToClear by the shift amount.
709 if (ConstantInt *Amt = dyn_cast<ConstantInt>(I->getOperand(1))) {
710 if (!CanEvaluateZExtd(I->getOperand(0), Ty, BitsToClear))
711 return false;
712 uint64_t ShiftAmt = Amt->getZExtValue();
713 BitsToClear = ShiftAmt < BitsToClear ? BitsToClear - ShiftAmt : 0;
714 return true;
715 }
716 return false;
Chris Lattner789162a2010-01-11 03:32:00 +0000717 case Instruction::LShr:
718 // We can promote lshr(x, cst) if we can promote x. This requires the
719 // ultimate 'and' to clear out the high zero bits we're clearing out though.
720 if (ConstantInt *Amt = dyn_cast<ConstantInt>(I->getOperand(1))) {
721 if (!CanEvaluateZExtd(I->getOperand(0), Ty, BitsToClear))
722 return false;
723 BitsToClear += Amt->getZExtValue();
724 if (BitsToClear > V->getType()->getScalarSizeInBits())
725 BitsToClear = V->getType()->getScalarSizeInBits();
726 return true;
727 }
728 // Cannot promote variable LSHR.
729 return false;
Chris Lattner75215c92010-01-10 00:58:42 +0000730 case Instruction::Select:
Chris Lattner789162a2010-01-11 03:32:00 +0000731 if (!CanEvaluateZExtd(I->getOperand(1), Ty, Tmp) ||
732 !CanEvaluateZExtd(I->getOperand(2), Ty, BitsToClear) ||
Chris Lattner7acc4b12010-01-11 04:05:13 +0000733 // TODO: If important, we could handle the case when the BitsToClear are
734 // known zero in the disagreeing side.
Chris Lattner789162a2010-01-11 03:32:00 +0000735 Tmp != BitsToClear)
736 return false;
737 return true;
Craig Topperb57c2922013-01-24 05:22:40 +0000738
Chris Lattner75215c92010-01-10 00:58:42 +0000739 case Instruction::PHI: {
740 // We can change a phi if we can change all operands. Note that we never
741 // get into trouble with cyclic PHIs here because we only consider
742 // instructions with a single use.
743 PHINode *PN = cast<PHINode>(I);
Chris Lattner789162a2010-01-11 03:32:00 +0000744 if (!CanEvaluateZExtd(PN->getIncomingValue(0), Ty, BitsToClear))
745 return false;
Chris Lattner9e390dd2010-01-10 02:50:04 +0000746 for (unsigned i = 1, e = PN->getNumIncomingValues(); i != e; ++i)
Chris Lattner789162a2010-01-11 03:32:00 +0000747 if (!CanEvaluateZExtd(PN->getIncomingValue(i), Ty, Tmp) ||
Chris Lattner7acc4b12010-01-11 04:05:13 +0000748 // TODO: If important, we could handle the case when the BitsToClear
749 // are known zero in the disagreeing input.
Chris Lattner789162a2010-01-11 03:32:00 +0000750 Tmp != BitsToClear)
751 return false;
Chris Lattner9e390dd2010-01-10 02:50:04 +0000752 return true;
Chris Lattner75215c92010-01-10 00:58:42 +0000753 }
754 default:
755 // TODO: Can handle more cases here.
Chris Lattner9e390dd2010-01-10 02:50:04 +0000756 return false;
Chris Lattner75215c92010-01-10 00:58:42 +0000757 }
758}
759
Chris Lattner80f43d32010-01-04 07:53:58 +0000760Instruction *InstCombiner::visitZExt(ZExtInst &CI) {
Nick Lewyckyeb3ac452013-01-14 20:56:10 +0000761 // If this zero extend is only used by a truncate, let the truncate be
Chris Lattner5324d802010-01-10 02:39:31 +0000762 // eliminated before we try to optimize this zext.
Stephen Hines36b56882014-04-23 16:57:46 -0700763 if (CI.hasOneUse() && isa<TruncInst>(CI.user_back()))
Stephen Hinesdce4a402014-05-29 02:49:00 -0700764 return nullptr;
Craig Topperb57c2922013-01-24 05:22:40 +0000765
Chris Lattner80f43d32010-01-04 07:53:58 +0000766 // If one of the common conversion will work, do it.
Chris Lattnerd84dfa42010-01-10 01:00:46 +0000767 if (Instruction *Result = commonCastTransforms(CI))
Chris Lattner80f43d32010-01-04 07:53:58 +0000768 return Result;
769
Craig Topperb57c2922013-01-24 05:22:40 +0000770 // See if we can simplify any instructions used by the input whose sole
Chris Lattnerd84dfa42010-01-10 01:00:46 +0000771 // purpose is to compute bits we don't care about.
772 if (SimplifyDemandedInstructionBits(CI))
773 return &CI;
Craig Topperb57c2922013-01-24 05:22:40 +0000774
Chris Lattnerd84dfa42010-01-10 01:00:46 +0000775 Value *Src = CI.getOperand(0);
Chris Lattnerdb125cf2011-07-18 04:54:35 +0000776 Type *SrcTy = Src->getType(), *DestTy = CI.getType();
Craig Topperb57c2922013-01-24 05:22:40 +0000777
Chris Lattner75215c92010-01-10 00:58:42 +0000778 // Attempt to extend the entire input expression tree to the destination
779 // type. Only do this if the dest type is a simple type, don't convert the
780 // expression tree to something weird like i93 unless the source is also
781 // strange.
Chris Lattner789162a2010-01-11 03:32:00 +0000782 unsigned BitsToClear;
Duncan Sands1df98592010-02-16 11:11:14 +0000783 if ((DestTy->isVectorTy() || ShouldChangeType(SrcTy, DestTy)) &&
Craig Topperb57c2922013-01-24 05:22:40 +0000784 CanEvaluateZExtd(Src, DestTy, BitsToClear)) {
Chris Lattner789162a2010-01-11 03:32:00 +0000785 assert(BitsToClear < SrcTy->getScalarSizeInBits() &&
786 "Unreasonable BitsToClear");
Craig Topperb57c2922013-01-24 05:22:40 +0000787
Chris Lattner5324d802010-01-10 02:39:31 +0000788 // Okay, we can transform this! Insert the new expression now.
789 DEBUG(dbgs() << "ICE: EvaluateInDifferentType converting expression type"
790 " to avoid zero extend: " << CI);
791 Value *Res = EvaluateInDifferentType(Src, DestTy, false);
792 assert(Res->getType() == DestTy);
Craig Topperb57c2922013-01-24 05:22:40 +0000793
Chris Lattner789162a2010-01-11 03:32:00 +0000794 uint32_t SrcBitsKept = SrcTy->getScalarSizeInBits()-BitsToClear;
795 uint32_t DestBitSize = DestTy->getScalarSizeInBits();
Craig Topperb57c2922013-01-24 05:22:40 +0000796
Chris Lattner5324d802010-01-10 02:39:31 +0000797 // If the high bits are already filled with zeros, just replace this
798 // cast with the result.
Chris Lattner9e390dd2010-01-10 02:50:04 +0000799 if (MaskedValueIsZero(Res, APInt::getHighBitsSet(DestBitSize,
Chris Lattner789162a2010-01-11 03:32:00 +0000800 DestBitSize-SrcBitsKept)))
Chris Lattner5324d802010-01-10 02:39:31 +0000801 return ReplaceInstUsesWith(CI, Res);
Craig Topperb57c2922013-01-24 05:22:40 +0000802
Chris Lattner5324d802010-01-10 02:39:31 +0000803 // We need to emit an AND to clear the high bits.
Chris Lattner9ee947c2010-01-10 20:25:54 +0000804 Constant *C = ConstantInt::get(Res->getType(),
Chris Lattner789162a2010-01-11 03:32:00 +0000805 APInt::getLowBitsSet(DestBitSize, SrcBitsKept));
Chris Lattner5324d802010-01-10 02:39:31 +0000806 return BinaryOperator::CreateAnd(Res, C);
Chris Lattner75215c92010-01-10 00:58:42 +0000807 }
Chris Lattner80f43d32010-01-04 07:53:58 +0000808
809 // If this is a TRUNC followed by a ZEXT then we are dealing with integral
810 // types and if the sizes are just right we can convert this into a logical
811 // 'and' which will be much cheaper than the pair of casts.
812 if (TruncInst *CSrc = dyn_cast<TruncInst>(Src)) { // A->B->C cast
Chris Lattnerf4fb9112010-01-10 07:08:30 +0000813 // TODO: Subsume this into EvaluateInDifferentType.
Craig Topperb57c2922013-01-24 05:22:40 +0000814
Chris Lattner80f43d32010-01-04 07:53:58 +0000815 // Get the sizes of the types involved. We know that the intermediate type
816 // will be smaller than A or C, but don't know the relation between A and C.
817 Value *A = CSrc->getOperand(0);
818 unsigned SrcSize = A->getType()->getScalarSizeInBits();
819 unsigned MidSize = CSrc->getType()->getScalarSizeInBits();
820 unsigned DstSize = CI.getType()->getScalarSizeInBits();
821 // If we're actually extending zero bits, then if
822 // SrcSize < DstSize: zext(a & mask)
823 // SrcSize == DstSize: a & mask
824 // SrcSize > DstSize: trunc(a) & mask
825 if (SrcSize < DstSize) {
826 APInt AndValue(APInt::getLowBitsSet(SrcSize, MidSize));
827 Constant *AndConst = ConstantInt::get(A->getType(), AndValue);
828 Value *And = Builder->CreateAnd(A, AndConst, CSrc->getName()+".mask");
829 return new ZExtInst(And, CI.getType());
830 }
Craig Topperb57c2922013-01-24 05:22:40 +0000831
Chris Lattner80f43d32010-01-04 07:53:58 +0000832 if (SrcSize == DstSize) {
833 APInt AndValue(APInt::getLowBitsSet(SrcSize, MidSize));
834 return BinaryOperator::CreateAnd(A, ConstantInt::get(A->getType(),
835 AndValue));
836 }
837 if (SrcSize > DstSize) {
Benjamin Kramera9390a42011-09-27 20:39:19 +0000838 Value *Trunc = Builder->CreateTrunc(A, CI.getType());
Chris Lattner80f43d32010-01-04 07:53:58 +0000839 APInt AndValue(APInt::getLowBitsSet(DstSize, MidSize));
Craig Topperb57c2922013-01-24 05:22:40 +0000840 return BinaryOperator::CreateAnd(Trunc,
Chris Lattner80f43d32010-01-04 07:53:58 +0000841 ConstantInt::get(Trunc->getType(),
Chris Lattnerf4fb9112010-01-10 07:08:30 +0000842 AndValue));
Chris Lattner80f43d32010-01-04 07:53:58 +0000843 }
844 }
845
846 if (ICmpInst *ICI = dyn_cast<ICmpInst>(Src))
847 return transformZExtICmp(ICI, CI);
848
849 BinaryOperator *SrcI = dyn_cast<BinaryOperator>(Src);
850 if (SrcI && SrcI->getOpcode() == Instruction::Or) {
851 // zext (or icmp, icmp) --> or (zext icmp), (zext icmp) if at least one
852 // of the (zext icmp) will be transformed.
853 ICmpInst *LHS = dyn_cast<ICmpInst>(SrcI->getOperand(0));
854 ICmpInst *RHS = dyn_cast<ICmpInst>(SrcI->getOperand(1));
855 if (LHS && RHS && LHS->hasOneUse() && RHS->hasOneUse() &&
856 (transformZExtICmp(LHS, CI, false) ||
857 transformZExtICmp(RHS, CI, false))) {
858 Value *LCast = Builder->CreateZExt(LHS, CI.getType(), LHS->getName());
859 Value *RCast = Builder->CreateZExt(RHS, CI.getType(), RHS->getName());
860 return BinaryOperator::Create(Instruction::Or, LCast, RCast);
861 }
862 }
863
Stephen Hines36b56882014-04-23 16:57:46 -0700864 // zext(trunc(X) & C) -> (X & zext(C)).
865 Constant *C;
866 Value *X;
867 if (SrcI &&
868 match(SrcI, m_OneUse(m_And(m_Trunc(m_Value(X)), m_Constant(C)))) &&
869 X->getType() == CI.getType())
870 return BinaryOperator::CreateAnd(X, ConstantExpr::getZExt(C, CI.getType()));
Chris Lattner80f43d32010-01-04 07:53:58 +0000871
Stephen Hines36b56882014-04-23 16:57:46 -0700872 // zext((trunc(X) & C) ^ C) -> ((X & zext(C)) ^ zext(C)).
873 Value *And;
874 if (SrcI && match(SrcI, m_OneUse(m_Xor(m_Value(And), m_Constant(C)))) &&
875 match(And, m_OneUse(m_And(m_Trunc(m_Value(X)), m_Specific(C)))) &&
876 X->getType() == CI.getType()) {
877 Constant *ZC = ConstantExpr::getZExt(C, CI.getType());
878 return BinaryOperator::CreateXor(Builder->CreateAnd(X, ZC), ZC);
879 }
Chris Lattner80f43d32010-01-04 07:53:58 +0000880
Chris Lattner718bf3f2010-01-05 21:04:47 +0000881 // zext (xor i1 X, true) to i32 --> xor (zext i1 X to i32), 1
Stephen Hines36b56882014-04-23 16:57:46 -0700882 if (SrcI && SrcI->hasOneUse() &&
883 SrcI->getType()->getScalarType()->isIntegerTy(1) &&
884 match(SrcI, m_Not(m_Value(X))) && (!X->hasOneUse() || !isa<CmpInst>(X))) {
Chris Lattner718bf3f2010-01-05 21:04:47 +0000885 Value *New = Builder->CreateZExt(X, CI.getType());
886 return BinaryOperator::CreateXor(New, ConstantInt::get(CI.getType(), 1));
887 }
Craig Topperb57c2922013-01-24 05:22:40 +0000888
Stephen Hinesdce4a402014-05-29 02:49:00 -0700889 return nullptr;
Chris Lattner80f43d32010-01-04 07:53:58 +0000890}
891
Benjamin Kramer0a30c422011-04-01 20:09:03 +0000892/// transformSExtICmp - Transform (sext icmp) to bitwise / integer operations
893/// in order to eliminate the icmp.
894Instruction *InstCombiner::transformSExtICmp(ICmpInst *ICI, Instruction &CI) {
895 Value *Op0 = ICI->getOperand(0), *Op1 = ICI->getOperand(1);
896 ICmpInst::Predicate Pred = ICI->getPredicate();
897
Stephen Hines36b56882014-04-23 16:57:46 -0700898 if (Constant *Op1C = dyn_cast<Constant>(Op1)) {
Benjamin Kramer406a6502011-04-01 22:29:18 +0000899 // (x <s 0) ? -1 : 0 -> ashr x, 31 -> all ones if negative
900 // (x >s -1) ? -1 : 0 -> not (ashr x, 31) -> all ones if positive
Stephen Hines36b56882014-04-23 16:57:46 -0700901 if ((Pred == ICmpInst::ICMP_SLT && Op1C->isNullValue()) ||
Benjamin Kramer0a30c422011-04-01 20:09:03 +0000902 (Pred == ICmpInst::ICMP_SGT && Op1C->isAllOnesValue())) {
903
904 Value *Sh = ConstantInt::get(Op0->getType(),
905 Op0->getType()->getScalarSizeInBits()-1);
906 Value *In = Builder->CreateAShr(Op0, Sh, Op0->getName()+".lobit");
907 if (In->getType() != CI.getType())
Benjamin Kramera9390a42011-09-27 20:39:19 +0000908 In = Builder->CreateIntCast(In, CI.getType(), true/*SExt*/);
Benjamin Kramer0a30c422011-04-01 20:09:03 +0000909
910 if (Pred == ICmpInst::ICMP_SGT)
911 In = Builder->CreateNot(In, In->getName()+".not");
912 return ReplaceInstUsesWith(CI, In);
913 }
Stephen Hines36b56882014-04-23 16:57:46 -0700914 }
Benjamin Kramer0baa94a2011-04-01 20:09:10 +0000915
Stephen Hines36b56882014-04-23 16:57:46 -0700916 if (ConstantInt *Op1C = dyn_cast<ConstantInt>(Op1)) {
Benjamin Kramer0baa94a2011-04-01 20:09:10 +0000917 // If we know that only one bit of the LHS of the icmp can be set and we
918 // have an equality comparison with zero or a power of 2, we can transform
919 // the icmp and sext into bitwise/integer operations.
Benjamin Kramer5337fab2011-04-01 22:22:11 +0000920 if (ICI->hasOneUse() &&
921 ICI->isEquality() && (Op1C->isZero() || Op1C->getValue().isPowerOf2())){
Benjamin Kramer0baa94a2011-04-01 20:09:10 +0000922 unsigned BitWidth = Op1C->getType()->getBitWidth();
923 APInt KnownZero(BitWidth, 0), KnownOne(BitWidth, 0);
Stephen Hinesdce4a402014-05-29 02:49:00 -0700924 computeKnownBits(Op0, KnownZero, KnownOne);
Benjamin Kramer0baa94a2011-04-01 20:09:10 +0000925
Benjamin Kramerce1498b2011-04-01 20:15:16 +0000926 APInt KnownZeroMask(~KnownZero);
927 if (KnownZeroMask.isPowerOf2()) {
Benjamin Kramer0baa94a2011-04-01 20:09:10 +0000928 Value *In = ICI->getOperand(0);
929
Benjamin Kramerf5b75932011-04-02 18:50:58 +0000930 // If the icmp tests for a known zero bit we can constant fold it.
931 if (!Op1C->isZero() && Op1C->getValue() != KnownZeroMask) {
932 Value *V = Pred == ICmpInst::ICMP_NE ?
933 ConstantInt::getAllOnesValue(CI.getType()) :
934 ConstantInt::getNullValue(CI.getType());
935 return ReplaceInstUsesWith(CI, V);
936 }
Benjamin Kramer5337fab2011-04-01 22:22:11 +0000937
Benjamin Kramer0baa94a2011-04-01 20:09:10 +0000938 if (!Op1C->isZero() == (Pred == ICmpInst::ICMP_NE)) {
939 // sext ((x & 2^n) == 0) -> (x >> n) - 1
940 // sext ((x & 2^n) != 2^n) -> (x >> n) - 1
941 unsigned ShiftAmt = KnownZeroMask.countTrailingZeros();
942 // Perform a right shift to place the desired bit in the LSB.
943 if (ShiftAmt)
944 In = Builder->CreateLShr(In,
945 ConstantInt::get(In->getType(), ShiftAmt));
946
947 // At this point "In" is either 1 or 0. Subtract 1 to turn
948 // {1, 0} -> {0, -1}.
949 In = Builder->CreateAdd(In,
950 ConstantInt::getAllOnesValue(In->getType()),
951 "sext");
952 } else {
953 // sext ((x & 2^n) != 0) -> (x << bitwidth-n) a>> bitwidth-1
Benjamin Kramer5337fab2011-04-01 22:22:11 +0000954 // sext ((x & 2^n) == 2^n) -> (x << bitwidth-n) a>> bitwidth-1
Benjamin Kramer0baa94a2011-04-01 20:09:10 +0000955 unsigned ShiftAmt = KnownZeroMask.countLeadingZeros();
956 // Perform a left shift to place the desired bit in the MSB.
957 if (ShiftAmt)
958 In = Builder->CreateShl(In,
959 ConstantInt::get(In->getType(), ShiftAmt));
960
961 // Distribute the bit over the whole bit width.
962 In = Builder->CreateAShr(In, ConstantInt::get(In->getType(),
963 BitWidth - 1), "sext");
964 }
965
966 if (CI.getType() == In->getType())
967 return ReplaceInstUsesWith(CI, In);
968 return CastInst::CreateIntegerCast(In, CI.getType(), true/*SExt*/);
969 }
970 }
Benjamin Kramer0a30c422011-04-01 20:09:03 +0000971 }
972
Stephen Hinesdce4a402014-05-29 02:49:00 -0700973 return nullptr;
Benjamin Kramer0a30c422011-04-01 20:09:03 +0000974}
975
Chris Lattner75215c92010-01-10 00:58:42 +0000976/// CanEvaluateSExtd - Return true if we can take the specified value
977/// and return it as type Ty without inserting any new casts and without
978/// changing the value of the common low bits. This is used by code that tries
979/// to promote integer operations to a wider types will allow us to eliminate
980/// the extension.
981///
Chris Lattneraa9c8942010-01-10 07:57:20 +0000982/// This function works on both vectors and scalars.
Chris Lattner75215c92010-01-10 00:58:42 +0000983///
Chris Lattnerdb125cf2011-07-18 04:54:35 +0000984static bool CanEvaluateSExtd(Value *V, Type *Ty) {
Chris Lattner75215c92010-01-10 00:58:42 +0000985 assert(V->getType()->getScalarSizeInBits() < Ty->getScalarSizeInBits() &&
986 "Can't sign extend type to a smaller type");
Chris Lattneraa9c8942010-01-10 07:57:20 +0000987 // If this is a constant, it can be trivially promoted.
988 if (isa<Constant>(V))
989 return true;
Craig Topperb57c2922013-01-24 05:22:40 +0000990
Chris Lattner75215c92010-01-10 00:58:42 +0000991 Instruction *I = dyn_cast<Instruction>(V);
Chris Lattneraa9c8942010-01-10 07:57:20 +0000992 if (!I) return false;
Craig Topperb57c2922013-01-24 05:22:40 +0000993
Jakob Stoklund Olesen7ee3ca12012-06-22 16:36:43 +0000994 // If this is a truncate from the dest type, we can trivially eliminate it.
995 if (isa<TruncInst>(I) && I->getOperand(0)->getType() == Ty)
Chris Lattneraa9c8942010-01-10 07:57:20 +0000996 return true;
Craig Topperb57c2922013-01-24 05:22:40 +0000997
Chris Lattner75215c92010-01-10 00:58:42 +0000998 // We can't extend or shrink something that has multiple uses: doing so would
999 // require duplicating the instruction in general, which isn't profitable.
Chris Lattneraa9c8942010-01-10 07:57:20 +00001000 if (!I->hasOneUse()) return false;
Chris Lattner75215c92010-01-10 00:58:42 +00001001
Chris Lattneraa9c8942010-01-10 07:57:20 +00001002 switch (I->getOpcode()) {
Chris Lattner11ea8122010-01-10 20:30:41 +00001003 case Instruction::SExt: // sext(sext(x)) -> sext(x)
1004 case Instruction::ZExt: // sext(zext(x)) -> zext(x)
1005 case Instruction::Trunc: // sext(trunc(x)) -> trunc(x) or sext(x)
1006 return true;
Chris Lattner75215c92010-01-10 00:58:42 +00001007 case Instruction::And:
1008 case Instruction::Or:
1009 case Instruction::Xor:
Chris Lattner75215c92010-01-10 00:58:42 +00001010 case Instruction::Add:
1011 case Instruction::Sub:
Chris Lattner75215c92010-01-10 00:58:42 +00001012 case Instruction::Mul:
Chris Lattneraa9c8942010-01-10 07:57:20 +00001013 // These operators can all arbitrarily be extended if their inputs can.
Chris Lattner8cf4f6f2010-01-11 02:43:35 +00001014 return CanEvaluateSExtd(I->getOperand(0), Ty) &&
1015 CanEvaluateSExtd(I->getOperand(1), Ty);
Craig Topperb57c2922013-01-24 05:22:40 +00001016
Chris Lattner75215c92010-01-10 00:58:42 +00001017 //case Instruction::Shl: TODO
1018 //case Instruction::LShr: TODO
Craig Topperb57c2922013-01-24 05:22:40 +00001019
Chris Lattneraa9c8942010-01-10 07:57:20 +00001020 case Instruction::Select:
Chris Lattner8cf4f6f2010-01-11 02:43:35 +00001021 return CanEvaluateSExtd(I->getOperand(1), Ty) &&
1022 CanEvaluateSExtd(I->getOperand(2), Ty);
Craig Topperb57c2922013-01-24 05:22:40 +00001023
Chris Lattner75215c92010-01-10 00:58:42 +00001024 case Instruction::PHI: {
1025 // We can change a phi if we can change all operands. Note that we never
1026 // get into trouble with cyclic PHIs here because we only consider
1027 // instructions with a single use.
1028 PHINode *PN = cast<PHINode>(I);
Chris Lattner9ee947c2010-01-10 20:25:54 +00001029 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i)
Chris Lattner8cf4f6f2010-01-11 02:43:35 +00001030 if (!CanEvaluateSExtd(PN->getIncomingValue(i), Ty)) return false;
Chris Lattneraa9c8942010-01-10 07:57:20 +00001031 return true;
Chris Lattner75215c92010-01-10 00:58:42 +00001032 }
1033 default:
1034 // TODO: Can handle more cases here.
1035 break;
1036 }
Craig Topperb57c2922013-01-24 05:22:40 +00001037
Chris Lattneraa9c8942010-01-10 07:57:20 +00001038 return false;
Chris Lattner75215c92010-01-10 00:58:42 +00001039}
1040
Chris Lattner80f43d32010-01-04 07:53:58 +00001041Instruction *InstCombiner::visitSExt(SExtInst &CI) {
Arnaud A. de Grandmaison66bff1e2013-02-13 00:19:19 +00001042 // If this sign extend is only used by a truncate, let the truncate be
1043 // eliminated before we try to optimize this sext.
Stephen Hines36b56882014-04-23 16:57:46 -07001044 if (CI.hasOneUse() && isa<TruncInst>(CI.user_back()))
Stephen Hinesdce4a402014-05-29 02:49:00 -07001045 return nullptr;
Craig Topperb57c2922013-01-24 05:22:40 +00001046
Chris Lattnerd84dfa42010-01-10 01:00:46 +00001047 if (Instruction *I = commonCastTransforms(CI))
Chris Lattner80f43d32010-01-04 07:53:58 +00001048 return I;
Craig Topperb57c2922013-01-24 05:22:40 +00001049
1050 // See if we can simplify any instructions used by the input whose sole
Chris Lattnerd84dfa42010-01-10 01:00:46 +00001051 // purpose is to compute bits we don't care about.
1052 if (SimplifyDemandedInstructionBits(CI))
1053 return &CI;
Craig Topperb57c2922013-01-24 05:22:40 +00001054
Chris Lattner80f43d32010-01-04 07:53:58 +00001055 Value *Src = CI.getOperand(0);
Chris Lattnerdb125cf2011-07-18 04:54:35 +00001056 Type *SrcTy = Src->getType(), *DestTy = CI.getType();
Chris Lattner75215c92010-01-10 00:58:42 +00001057
Chris Lattner75215c92010-01-10 00:58:42 +00001058 // Attempt to extend the entire input expression tree to the destination
1059 // type. Only do this if the dest type is a simple type, don't convert the
1060 // expression tree to something weird like i93 unless the source is also
1061 // strange.
Duncan Sands1df98592010-02-16 11:11:14 +00001062 if ((DestTy->isVectorTy() || ShouldChangeType(SrcTy, DestTy)) &&
Chris Lattner8cf4f6f2010-01-11 02:43:35 +00001063 CanEvaluateSExtd(Src, DestTy)) {
Chris Lattnerdde5ee52010-01-10 07:40:50 +00001064 // Okay, we can transform this! Insert the new expression now.
1065 DEBUG(dbgs() << "ICE: EvaluateInDifferentType converting expression type"
1066 " to avoid sign extend: " << CI);
1067 Value *Res = EvaluateInDifferentType(Src, DestTy, true);
1068 assert(Res->getType() == DestTy);
1069
Chris Lattner75215c92010-01-10 00:58:42 +00001070 uint32_t SrcBitSize = SrcTy->getScalarSizeInBits();
1071 uint32_t DestBitSize = DestTy->getScalarSizeInBits();
Chris Lattnerdde5ee52010-01-10 07:40:50 +00001072
1073 // If the high bits are already filled with sign bit, just replace this
1074 // cast with the result.
Chris Lattneraa9c8942010-01-10 07:57:20 +00001075 if (ComputeNumSignBits(Res) > DestBitSize - SrcBitSize)
Chris Lattnerdde5ee52010-01-10 07:40:50 +00001076 return ReplaceInstUsesWith(CI, Res);
Craig Topperb57c2922013-01-24 05:22:40 +00001077
Chris Lattnerdde5ee52010-01-10 07:40:50 +00001078 // We need to emit a shl + ashr to do the sign extend.
1079 Value *ShAmt = ConstantInt::get(DestTy, DestBitSize-SrcBitSize);
1080 return BinaryOperator::CreateAShr(Builder->CreateShl(Res, ShAmt, "sext"),
1081 ShAmt);
Chris Lattner75215c92010-01-10 00:58:42 +00001082 }
Chris Lattner80f43d32010-01-04 07:53:58 +00001083
Chris Lattnercd5adbb2010-01-18 22:19:16 +00001084 // If this input is a trunc from our destination, then turn sext(trunc(x))
1085 // into shifts.
1086 if (TruncInst *TI = dyn_cast<TruncInst>(Src))
1087 if (TI->hasOneUse() && TI->getOperand(0)->getType() == DestTy) {
1088 uint32_t SrcBitSize = SrcTy->getScalarSizeInBits();
1089 uint32_t DestBitSize = DestTy->getScalarSizeInBits();
Craig Topperb57c2922013-01-24 05:22:40 +00001090
Chris Lattnercd5adbb2010-01-18 22:19:16 +00001091 // We need to emit a shl + ashr to do the sign extend.
1092 Value *ShAmt = ConstantInt::get(DestTy, DestBitSize-SrcBitSize);
1093 Value *Res = Builder->CreateShl(TI->getOperand(0), ShAmt, "sext");
1094 return BinaryOperator::CreateAShr(Res, ShAmt);
1095 }
Nate Begeman9a3dc552010-12-17 23:12:19 +00001096
Benjamin Kramer0a30c422011-04-01 20:09:03 +00001097 if (ICmpInst *ICI = dyn_cast<ICmpInst>(Src))
1098 return transformSExtICmp(ICI, CI);
Bill Wendling2d0537c2010-12-17 23:27:41 +00001099
Chris Lattner80f43d32010-01-04 07:53:58 +00001100 // If the input is a shl/ashr pair of a same constant, then this is a sign
1101 // extension from a smaller value. If we could trust arbitrary bitwidth
1102 // integers, we could turn this into a truncate to the smaller bit and then
1103 // use a sext for the whole extension. Since we don't, look deeper and check
1104 // for a truncate. If the source and dest are the same type, eliminate the
1105 // trunc and extend and just do shifts. For example, turn:
1106 // %a = trunc i32 %i to i8
1107 // %b = shl i8 %a, 6
1108 // %c = ashr i8 %b, 6
1109 // %d = sext i8 %c to i32
1110 // into:
1111 // %a = shl i32 %i, 30
1112 // %d = ashr i32 %a, 30
Stephen Hinesdce4a402014-05-29 02:49:00 -07001113 Value *A = nullptr;
Chris Lattner4f379782010-01-10 01:04:31 +00001114 // TODO: Eventually this could be subsumed by EvaluateInDifferentType.
Stephen Hinesdce4a402014-05-29 02:49:00 -07001115 ConstantInt *BA = nullptr, *CA = nullptr;
Chris Lattner4f379782010-01-10 01:04:31 +00001116 if (match(Src, m_AShr(m_Shl(m_Trunc(m_Value(A)), m_ConstantInt(BA)),
Chris Lattner80f43d32010-01-04 07:53:58 +00001117 m_ConstantInt(CA))) &&
Chris Lattner4f379782010-01-10 01:04:31 +00001118 BA == CA && A->getType() == CI.getType()) {
1119 unsigned MidSize = Src->getType()->getScalarSizeInBits();
1120 unsigned SrcDstSize = CI.getType()->getScalarSizeInBits();
1121 unsigned ShAmt = CA->getZExtValue()+SrcDstSize-MidSize;
1122 Constant *ShAmtV = ConstantInt::get(CI.getType(), ShAmt);
1123 A = Builder->CreateShl(A, ShAmtV, CI.getName());
1124 return BinaryOperator::CreateAShr(A, ShAmtV);
Chris Lattner80f43d32010-01-04 07:53:58 +00001125 }
Craig Topperb57c2922013-01-24 05:22:40 +00001126
Stephen Hinesdce4a402014-05-29 02:49:00 -07001127 return nullptr;
Chris Lattner80f43d32010-01-04 07:53:58 +00001128}
1129
1130
1131/// FitsInFPType - Return a Constant* for the specified FP constant if it fits
1132/// in the specified FP type without changing its value.
1133static Constant *FitsInFPType(ConstantFP *CFP, const fltSemantics &Sem) {
1134 bool losesInfo;
1135 APFloat F = CFP->getValueAPF();
1136 (void)F.convert(Sem, APFloat::rmNearestTiesToEven, &losesInfo);
1137 if (!losesInfo)
1138 return ConstantFP::get(CFP->getContext(), F);
Stephen Hinesdce4a402014-05-29 02:49:00 -07001139 return nullptr;
Chris Lattner80f43d32010-01-04 07:53:58 +00001140}
1141
1142/// LookThroughFPExtensions - If this is an fp extension instruction, look
1143/// through it until we get the source value.
1144static Value *LookThroughFPExtensions(Value *V) {
1145 if (Instruction *I = dyn_cast<Instruction>(V))
1146 if (I->getOpcode() == Instruction::FPExt)
1147 return LookThroughFPExtensions(I->getOperand(0));
Craig Topperb57c2922013-01-24 05:22:40 +00001148
Chris Lattner80f43d32010-01-04 07:53:58 +00001149 // If this value is a constant, return the constant in the smallest FP type
1150 // that can accurately represent it. This allows us to turn
1151 // (float)((double)X+2.0) into x+2.0f.
1152 if (ConstantFP *CFP = dyn_cast<ConstantFP>(V)) {
1153 if (CFP->getType() == Type::getPPC_FP128Ty(V->getContext()))
1154 return V; // No constant folding of this.
Dan Gohmance163392011-12-17 00:04:22 +00001155 // See if the value can be truncated to half and then reextended.
1156 if (Value *V = FitsInFPType(CFP, APFloat::IEEEhalf))
1157 return V;
Chris Lattner80f43d32010-01-04 07:53:58 +00001158 // See if the value can be truncated to float and then reextended.
1159 if (Value *V = FitsInFPType(CFP, APFloat::IEEEsingle))
1160 return V;
Benjamin Kramerf0127052010-01-05 13:12:22 +00001161 if (CFP->getType()->isDoubleTy())
Chris Lattner80f43d32010-01-04 07:53:58 +00001162 return V; // Won't shrink.
1163 if (Value *V = FitsInFPType(CFP, APFloat::IEEEdouble))
1164 return V;
1165 // Don't try to shrink to various long double types.
1166 }
Craig Topperb57c2922013-01-24 05:22:40 +00001167
Chris Lattner80f43d32010-01-04 07:53:58 +00001168 return V;
1169}
1170
1171Instruction *InstCombiner::visitFPTrunc(FPTruncInst &CI) {
1172 if (Instruction *I = commonCastTransforms(CI))
1173 return I;
Stephen Hines36b56882014-04-23 16:57:46 -07001174 // If we have fptrunc(OpI (fpextend x), (fpextend y)), we would like to
1175 // simpilify this expression to avoid one or more of the trunc/extend
1176 // operations if we can do so without changing the numerical results.
1177 //
1178 // The exact manner in which the widths of the operands interact to limit
1179 // what we can and cannot do safely varies from operation to operation, and
1180 // is explained below in the various case statements.
Chris Lattner80f43d32010-01-04 07:53:58 +00001181 BinaryOperator *OpI = dyn_cast<BinaryOperator>(CI.getOperand(0));
1182 if (OpI && OpI->hasOneUse()) {
Stephen Hines36b56882014-04-23 16:57:46 -07001183 Value *LHSOrig = LookThroughFPExtensions(OpI->getOperand(0));
1184 Value *RHSOrig = LookThroughFPExtensions(OpI->getOperand(1));
1185 unsigned OpWidth = OpI->getType()->getFPMantissaWidth();
1186 unsigned LHSWidth = LHSOrig->getType()->getFPMantissaWidth();
1187 unsigned RHSWidth = RHSOrig->getType()->getFPMantissaWidth();
1188 unsigned SrcWidth = std::max(LHSWidth, RHSWidth);
1189 unsigned DstWidth = CI.getType()->getFPMantissaWidth();
Chris Lattner80f43d32010-01-04 07:53:58 +00001190 switch (OpI->getOpcode()) {
Stephen Hines36b56882014-04-23 16:57:46 -07001191 default: break;
1192 case Instruction::FAdd:
1193 case Instruction::FSub:
1194 // For addition and subtraction, the infinitely precise result can
1195 // essentially be arbitrarily wide; proving that double rounding
1196 // will not occur because the result of OpI is exact (as we will for
1197 // FMul, for example) is hopeless. However, we *can* nonetheless
1198 // frequently know that double rounding cannot occur (or that it is
1199 // innocuous) by taking advantage of the specific structure of
1200 // infinitely-precise results that admit double rounding.
1201 //
1202 // Specifically, if OpWidth >= 2*DstWdith+1 and DstWidth is sufficient
1203 // to represent both sources, we can guarantee that the double
1204 // rounding is innocuous (See p50 of Figueroa's 2000 PhD thesis,
1205 // "A Rigorous Framework for Fully Supporting the IEEE Standard ..."
1206 // for proof of this fact).
1207 //
1208 // Note: Figueroa does not consider the case where DstFormat !=
1209 // SrcFormat. It's possible (likely even!) that this analysis
1210 // could be tightened for those cases, but they are rare (the main
1211 // case of interest here is (float)((double)float + float)).
1212 if (OpWidth >= 2*DstWidth+1 && DstWidth >= SrcWidth) {
1213 if (LHSOrig->getType() != CI.getType())
1214 LHSOrig = Builder->CreateFPExt(LHSOrig, CI.getType());
1215 if (RHSOrig->getType() != CI.getType())
1216 RHSOrig = Builder->CreateFPExt(RHSOrig, CI.getType());
1217 Instruction *RI =
1218 BinaryOperator::Create(OpI->getOpcode(), LHSOrig, RHSOrig);
1219 RI->copyFastMathFlags(OpI);
1220 return RI;
Chris Lattner80f43d32010-01-04 07:53:58 +00001221 }
Stephen Hines36b56882014-04-23 16:57:46 -07001222 break;
1223 case Instruction::FMul:
1224 // For multiplication, the infinitely precise result has at most
1225 // LHSWidth + RHSWidth significant bits; if OpWidth is sufficient
1226 // that such a value can be exactly represented, then no double
1227 // rounding can possibly occur; we can safely perform the operation
1228 // in the destination format if it can represent both sources.
1229 if (OpWidth >= LHSWidth + RHSWidth && DstWidth >= SrcWidth) {
1230 if (LHSOrig->getType() != CI.getType())
1231 LHSOrig = Builder->CreateFPExt(LHSOrig, CI.getType());
1232 if (RHSOrig->getType() != CI.getType())
1233 RHSOrig = Builder->CreateFPExt(RHSOrig, CI.getType());
1234 Instruction *RI =
1235 BinaryOperator::CreateFMul(LHSOrig, RHSOrig);
1236 RI->copyFastMathFlags(OpI);
1237 return RI;
1238 }
1239 break;
1240 case Instruction::FDiv:
1241 // For division, we use again use the bound from Figueroa's
1242 // dissertation. I am entirely certain that this bound can be
1243 // tightened in the unbalanced operand case by an analysis based on
1244 // the diophantine rational approximation bound, but the well-known
1245 // condition used here is a good conservative first pass.
1246 // TODO: Tighten bound via rigorous analysis of the unbalanced case.
1247 if (OpWidth >= 2*DstWidth && DstWidth >= SrcWidth) {
1248 if (LHSOrig->getType() != CI.getType())
1249 LHSOrig = Builder->CreateFPExt(LHSOrig, CI.getType());
1250 if (RHSOrig->getType() != CI.getType())
1251 RHSOrig = Builder->CreateFPExt(RHSOrig, CI.getType());
1252 Instruction *RI =
1253 BinaryOperator::CreateFDiv(LHSOrig, RHSOrig);
1254 RI->copyFastMathFlags(OpI);
1255 return RI;
1256 }
1257 break;
1258 case Instruction::FRem:
1259 // Remainder is straightforward. Remainder is always exact, so the
1260 // type of OpI doesn't enter into things at all. We simply evaluate
1261 // in whichever source type is larger, then convert to the
1262 // destination type.
1263 if (LHSWidth < SrcWidth)
1264 LHSOrig = Builder->CreateFPExt(LHSOrig, RHSOrig->getType());
1265 else if (RHSWidth <= SrcWidth)
1266 RHSOrig = Builder->CreateFPExt(RHSOrig, LHSOrig->getType());
1267 Value *ExactResult = Builder->CreateFRem(LHSOrig, RHSOrig);
1268 if (Instruction *RI = dyn_cast<Instruction>(ExactResult))
1269 RI->copyFastMathFlags(OpI);
1270 return CastInst::CreateFPCast(ExactResult, CI.getType());
Chris Lattner80f43d32010-01-04 07:53:58 +00001271 }
Owen Andersone9d4eba2013-01-10 22:06:52 +00001272
1273 // (fptrunc (fneg x)) -> (fneg (fptrunc x))
1274 if (BinaryOperator::isFNeg(OpI)) {
1275 Value *InnerTrunc = Builder->CreateFPTrunc(OpI->getOperand(1),
1276 CI.getType());
Stephen Hines36b56882014-04-23 16:57:46 -07001277 Instruction *RI = BinaryOperator::CreateFNeg(InnerTrunc);
1278 RI->copyFastMathFlags(OpI);
1279 return RI;
Owen Andersone9d4eba2013-01-10 22:06:52 +00001280 }
Chris Lattner80f43d32010-01-04 07:53:58 +00001281 }
Owen Andersone9d4eba2013-01-10 22:06:52 +00001282
Owen Anderson03e84c92013-10-03 21:08:05 +00001283 // (fptrunc (select cond, R1, Cst)) -->
1284 // (select cond, (fptrunc R1), (fptrunc Cst))
1285 SelectInst *SI = dyn_cast<SelectInst>(CI.getOperand(0));
1286 if (SI &&
1287 (isa<ConstantFP>(SI->getOperand(1)) ||
1288 isa<ConstantFP>(SI->getOperand(2)))) {
1289 Value *LHSTrunc = Builder->CreateFPTrunc(SI->getOperand(1),
1290 CI.getType());
1291 Value *RHSTrunc = Builder->CreateFPTrunc(SI->getOperand(2),
1292 CI.getType());
1293 return SelectInst::Create(SI->getOperand(0), LHSTrunc, RHSTrunc);
1294 }
1295
Owen Andersone9d4eba2013-01-10 22:06:52 +00001296 IntrinsicInst *II = dyn_cast<IntrinsicInst>(CI.getOperand(0));
1297 if (II) {
1298 switch (II->getIntrinsicID()) {
1299 default: break;
1300 case Intrinsic::fabs: {
1301 // (fptrunc (fabs x)) -> (fabs (fptrunc x))
1302 Value *InnerTrunc = Builder->CreateFPTrunc(II->getArgOperand(0),
1303 CI.getType());
1304 Type *IntrinsicType[] = { CI.getType() };
1305 Function *Overload =
1306 Intrinsic::getDeclaration(CI.getParent()->getParent()->getParent(),
1307 II->getIntrinsicID(), IntrinsicType);
1308
1309 Value *Args[] = { InnerTrunc };
1310 return CallInst::Create(Overload, Args, II->getName());
1311 }
1312 }
1313 }
1314
Owen Andersond9029012010-07-19 08:09:34 +00001315 // Fold (fptrunc (sqrt (fpext x))) -> (sqrtf x)
Hal Finkel64fa5012013-11-16 21:29:08 +00001316 // Note that we restrict this transformation based on
1317 // TLI->has(LibFunc::sqrtf), even for the sqrt intrinsic, because
1318 // TLI->has(LibFunc::sqrtf) is sufficient to guarantee that the
1319 // single-precision intrinsic can be expanded in the backend.
Owen Andersond9029012010-07-19 08:09:34 +00001320 CallInst *Call = dyn_cast<CallInst>(CI.getOperand(0));
Chad Rosier00737bd2011-12-01 21:29:16 +00001321 if (Call && Call->getCalledFunction() && TLI->has(LibFunc::sqrtf) &&
Hal Finkel64fa5012013-11-16 21:29:08 +00001322 (Call->getCalledFunction()->getName() == TLI->getName(LibFunc::sqrt) ||
1323 Call->getCalledFunction()->getIntrinsicID() == Intrinsic::sqrt) &&
Evan Cheng93a635c2011-07-13 19:08:16 +00001324 Call->getNumArgOperands() == 1 &&
1325 Call->hasOneUse()) {
Owen Andersond9029012010-07-19 08:09:34 +00001326 CastInst *Arg = dyn_cast<CastInst>(Call->getArgOperand(0));
1327 if (Arg && Arg->getOpcode() == Instruction::FPExt &&
Owen Anderson5f23a932010-07-19 19:23:32 +00001328 CI.getType()->isFloatTy() &&
1329 Call->getType()->isDoubleTy() &&
1330 Arg->getType()->isDoubleTy() &&
1331 Arg->getOperand(0)->getType()->isFloatTy()) {
1332 Function *Callee = Call->getCalledFunction();
1333 Module *M = CI.getParent()->getParent()->getParent();
Hal Finkel64fa5012013-11-16 21:29:08 +00001334 Constant *SqrtfFunc = (Callee->getIntrinsicID() == Intrinsic::sqrt) ?
1335 Intrinsic::getDeclaration(M, Intrinsic::sqrt, Builder->getFloatTy()) :
1336 M->getOrInsertFunction("sqrtf", Callee->getAttributes(),
1337 Builder->getFloatTy(), Builder->getFloatTy(),
1338 NULL);
Owen Andersond9029012010-07-19 08:09:34 +00001339 CallInst *ret = CallInst::Create(SqrtfFunc, Arg->getOperand(0),
1340 "sqrtfcall");
Owen Anderson5f23a932010-07-19 19:23:32 +00001341 ret->setAttributes(Callee->getAttributes());
Craig Topperb57c2922013-01-24 05:22:40 +00001342
1343
Chris Lattner979ed442010-09-07 20:01:38 +00001344 // Remove the old Call. With -fmath-errno, it won't get marked readnone.
Eli Friedman3e22cb92011-05-18 00:32:01 +00001345 ReplaceInstUsesWith(*Call, UndefValue::get(Call->getType()));
Chris Lattner979ed442010-09-07 20:01:38 +00001346 EraseInstFromFunction(*Call);
Owen Andersond9029012010-07-19 08:09:34 +00001347 return ret;
1348 }
1349 }
Craig Topperb57c2922013-01-24 05:22:40 +00001350
Stephen Hinesdce4a402014-05-29 02:49:00 -07001351 return nullptr;
Chris Lattner80f43d32010-01-04 07:53:58 +00001352}
1353
1354Instruction *InstCombiner::visitFPExt(CastInst &CI) {
1355 return commonCastTransforms(CI);
1356}
1357
1358Instruction *InstCombiner::visitFPToUI(FPToUIInst &FI) {
1359 Instruction *OpI = dyn_cast<Instruction>(FI.getOperand(0));
Stephen Hinesdce4a402014-05-29 02:49:00 -07001360 if (!OpI)
Chris Lattner80f43d32010-01-04 07:53:58 +00001361 return commonCastTransforms(FI);
1362
1363 // fptoui(uitofp(X)) --> X
1364 // fptoui(sitofp(X)) --> X
1365 // This is safe if the intermediate type has enough bits in its mantissa to
1366 // accurately represent all values of X. For example, do not do this with
1367 // i64->float->i64. This is also safe for sitofp case, because any negative
Craig Topperb57c2922013-01-24 05:22:40 +00001368 // 'X' value would cause an undefined result for the fptoui.
Chris Lattner80f43d32010-01-04 07:53:58 +00001369 if ((isa<UIToFPInst>(OpI) || isa<SIToFPInst>(OpI)) &&
1370 OpI->getOperand(0)->getType() == FI.getType() &&
1371 (int)FI.getType()->getScalarSizeInBits() < /*extra bit for sign */
1372 OpI->getType()->getFPMantissaWidth())
1373 return ReplaceInstUsesWith(FI, OpI->getOperand(0));
1374
1375 return commonCastTransforms(FI);
1376}
1377
1378Instruction *InstCombiner::visitFPToSI(FPToSIInst &FI) {
1379 Instruction *OpI = dyn_cast<Instruction>(FI.getOperand(0));
Stephen Hinesdce4a402014-05-29 02:49:00 -07001380 if (!OpI)
Chris Lattner80f43d32010-01-04 07:53:58 +00001381 return commonCastTransforms(FI);
Craig Topperb57c2922013-01-24 05:22:40 +00001382
Chris Lattner80f43d32010-01-04 07:53:58 +00001383 // fptosi(sitofp(X)) --> X
1384 // fptosi(uitofp(X)) --> X
1385 // This is safe if the intermediate type has enough bits in its mantissa to
1386 // accurately represent all values of X. For example, do not do this with
1387 // i64->float->i64. This is also safe for sitofp case, because any negative
Craig Topperb57c2922013-01-24 05:22:40 +00001388 // 'X' value would cause an undefined result for the fptoui.
Chris Lattner80f43d32010-01-04 07:53:58 +00001389 if ((isa<UIToFPInst>(OpI) || isa<SIToFPInst>(OpI)) &&
1390 OpI->getOperand(0)->getType() == FI.getType() &&
1391 (int)FI.getType()->getScalarSizeInBits() <=
1392 OpI->getType()->getFPMantissaWidth())
1393 return ReplaceInstUsesWith(FI, OpI->getOperand(0));
Craig Topperb57c2922013-01-24 05:22:40 +00001394
Chris Lattner80f43d32010-01-04 07:53:58 +00001395 return commonCastTransforms(FI);
1396}
1397
1398Instruction *InstCombiner::visitUIToFP(CastInst &CI) {
1399 return commonCastTransforms(CI);
1400}
1401
1402Instruction *InstCombiner::visitSIToFP(CastInst &CI) {
1403 return commonCastTransforms(CI);
1404}
1405
Chris Lattner80f43d32010-01-04 07:53:58 +00001406Instruction *InstCombiner::visitIntToPtr(IntToPtrInst &CI) {
Dan Gohman3b5487e2010-02-02 01:44:02 +00001407 // If the source integer type is not the intptr_t type for this target, do a
1408 // trunc or zext to the intptr_t type, then inttoptr of it. This allows the
1409 // cast to be exposed to other transforms.
Benjamin Kramer39b5f122013-02-05 20:22:40 +00001410
Stephen Hines36b56882014-04-23 16:57:46 -07001411 if (DL) {
Matt Arsenault52c7d8e2013-08-21 19:53:10 +00001412 unsigned AS = CI.getAddressSpace();
1413 if (CI.getOperand(0)->getType()->getScalarSizeInBits() !=
Stephen Hines36b56882014-04-23 16:57:46 -07001414 DL->getPointerSizeInBits(AS)) {
1415 Type *Ty = DL->getIntPtrType(CI.getContext(), AS);
Matt Arsenault52c7d8e2013-08-21 19:53:10 +00001416 if (CI.getType()->isVectorTy()) // Handle vectors of pointers.
1417 Ty = VectorType::get(Ty, CI.getType()->getVectorNumElements());
1418
1419 Value *P = Builder->CreateZExtOrTrunc(CI.getOperand(0), Ty);
1420 return new IntToPtrInst(P, CI.getType());
1421 }
Chris Lattner80f43d32010-01-04 07:53:58 +00001422 }
Craig Topperb57c2922013-01-24 05:22:40 +00001423
Chris Lattner80f43d32010-01-04 07:53:58 +00001424 if (Instruction *I = commonCastTransforms(CI))
1425 return I;
1426
Stephen Hinesdce4a402014-05-29 02:49:00 -07001427 return nullptr;
Chris Lattner80f43d32010-01-04 07:53:58 +00001428}
1429
Chris Lattner7a34d6c2010-01-05 22:21:18 +00001430/// @brief Implement the transforms for cast of pointer (bitcast/ptrtoint)
1431Instruction *InstCombiner::commonPointerCastTransforms(CastInst &CI) {
1432 Value *Src = CI.getOperand(0);
Craig Topperb57c2922013-01-24 05:22:40 +00001433
Chris Lattner7a34d6c2010-01-05 22:21:18 +00001434 if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(Src)) {
1435 // If casting the result of a getelementptr instruction with no offset, turn
1436 // this into a cast of the original pointer!
1437 if (GEP->hasAllZeroIndices()) {
1438 // Changing the cast operand is usually not a good idea but it is safe
Craig Topperb57c2922013-01-24 05:22:40 +00001439 // here because the pointer operand is being replaced with another
Chris Lattner7a34d6c2010-01-05 22:21:18 +00001440 // pointer operand so the opcode doesn't need to change.
1441 Worklist.Add(GEP);
1442 CI.setOperand(0, GEP->getOperand(0));
1443 return &CI;
1444 }
Craig Topperb57c2922013-01-24 05:22:40 +00001445
Stephen Hines36b56882014-04-23 16:57:46 -07001446 if (!DL)
Matt Arsenault5c40cc22013-08-19 22:17:18 +00001447 return commonCastTransforms(CI);
1448
Chris Lattner7a34d6c2010-01-05 22:21:18 +00001449 // If the GEP has a single use, and the base pointer is a bitcast, and the
1450 // GEP computes a constant offset, see if we can convert these three
1451 // instructions into fewer. This typically happens with unions and other
1452 // non-type-safe code.
Matt Arsenault52c7d8e2013-08-21 19:53:10 +00001453 unsigned AS = GEP->getPointerAddressSpace();
Stephen Hines36b56882014-04-23 16:57:46 -07001454 unsigned OffsetBits = DL->getPointerSizeInBits(AS);
Matt Arsenault5c40cc22013-08-19 22:17:18 +00001455 APInt Offset(OffsetBits, 0);
1456 BitCastInst *BCI = dyn_cast<BitCastInst>(GEP->getOperand(0));
1457 if (GEP->hasOneUse() &&
1458 BCI &&
Stephen Hines36b56882014-04-23 16:57:46 -07001459 GEP->accumulateConstantOffset(*DL, Offset)) {
Chris Lattner7a34d6c2010-01-05 22:21:18 +00001460 // Get the base pointer input of the bitcast, and the type it points to.
Matt Arsenault5c40cc22013-08-19 22:17:18 +00001461 Value *OrigBase = BCI->getOperand(0);
Chris Lattner7a34d6c2010-01-05 22:21:18 +00001462 SmallVector<Value*, 8> NewIndices;
Matt Arsenault8e3367e2013-08-19 22:17:40 +00001463 if (FindElementAtOffset(OrigBase->getType(),
1464 Offset.getSExtValue(),
1465 NewIndices)) {
Chris Lattner7a34d6c2010-01-05 22:21:18 +00001466 // If we were able to index down into an element, create the GEP
1467 // and bitcast the result. This eliminates one bitcast, potentially
1468 // two.
1469 Value *NGEP = cast<GEPOperator>(GEP)->isInBounds() ?
Matt Arsenault5c40cc22013-08-19 22:17:18 +00001470 Builder->CreateInBoundsGEP(OrigBase, NewIndices) :
1471 Builder->CreateGEP(OrigBase, NewIndices);
Chris Lattner7a34d6c2010-01-05 22:21:18 +00001472 NGEP->takeName(GEP);
Craig Topperb57c2922013-01-24 05:22:40 +00001473
Chris Lattner7a34d6c2010-01-05 22:21:18 +00001474 if (isa<BitCastInst>(CI))
1475 return new BitCastInst(NGEP, CI.getType());
1476 assert(isa<PtrToIntInst>(CI));
1477 return new PtrToIntInst(NGEP, CI.getType());
Craig Topperb57c2922013-01-24 05:22:40 +00001478 }
Chris Lattner7a34d6c2010-01-05 22:21:18 +00001479 }
1480 }
Craig Topperb57c2922013-01-24 05:22:40 +00001481
Chris Lattner7a34d6c2010-01-05 22:21:18 +00001482 return commonCastTransforms(CI);
1483}
1484
1485Instruction *InstCombiner::visitPtrToInt(PtrToIntInst &CI) {
Dan Gohman3b5487e2010-02-02 01:44:02 +00001486 // If the destination integer type is not the intptr_t type for this target,
1487 // do a ptrtoint to intptr_t then do a trunc or zext. This allows the cast
1488 // to be exposed to other transforms.
Benjamin Kramer1018fa22013-02-05 19:21:56 +00001489
Stephen Hines36b56882014-04-23 16:57:46 -07001490 if (!DL)
Matt Arsenault52c7d8e2013-08-21 19:53:10 +00001491 return commonPointerCastTransforms(CI);
Craig Topperb57c2922013-01-24 05:22:40 +00001492
Matt Arsenault52c7d8e2013-08-21 19:53:10 +00001493 Type *Ty = CI.getType();
1494 unsigned AS = CI.getPointerAddressSpace();
1495
Stephen Hines36b56882014-04-23 16:57:46 -07001496 if (Ty->getScalarSizeInBits() == DL->getPointerSizeInBits(AS))
Matt Arsenault52c7d8e2013-08-21 19:53:10 +00001497 return commonPointerCastTransforms(CI);
1498
Stephen Hines36b56882014-04-23 16:57:46 -07001499 Type *PtrTy = DL->getIntPtrType(CI.getContext(), AS);
Matt Arsenault52c7d8e2013-08-21 19:53:10 +00001500 if (Ty->isVectorTy()) // Handle vectors of pointers.
1501 PtrTy = VectorType::get(PtrTy, Ty->getVectorNumElements());
1502
1503 Value *P = Builder->CreatePtrToInt(CI.getOperand(0), PtrTy);
1504 return CastInst::CreateIntegerCast(P, Ty, /*isSigned=*/false);
Chris Lattner7a34d6c2010-01-05 22:21:18 +00001505}
1506
Chris Lattner67451912010-05-08 21:50:26 +00001507/// OptimizeVectorResize - This input value (which is known to have vector type)
1508/// is being zero extended or truncated to the specified vector type. Try to
1509/// replace it with a shuffle (and vector/vector bitcast) if possible.
1510///
1511/// The source and destination vector types may have different element types.
Chris Lattnerdb125cf2011-07-18 04:54:35 +00001512static Instruction *OptimizeVectorResize(Value *InVal, VectorType *DestTy,
Chris Lattner67451912010-05-08 21:50:26 +00001513 InstCombiner &IC) {
1514 // We can only do this optimization if the output is a multiple of the input
1515 // element size, or the input is a multiple of the output element size.
1516 // Convert the input type to have the same element type as the output.
Chris Lattnerdb125cf2011-07-18 04:54:35 +00001517 VectorType *SrcTy = cast<VectorType>(InVal->getType());
Craig Topperb57c2922013-01-24 05:22:40 +00001518
Chris Lattner67451912010-05-08 21:50:26 +00001519 if (SrcTy->getElementType() != DestTy->getElementType()) {
1520 // The input types don't need to be identical, but for now they must be the
1521 // same size. There is no specific reason we couldn't handle things like
1522 // <4 x i16> -> <4 x i32> by bitcasting to <2 x i32> but haven't gotten
Craig Topperb57c2922013-01-24 05:22:40 +00001523 // there yet.
Chris Lattner67451912010-05-08 21:50:26 +00001524 if (SrcTy->getElementType()->getPrimitiveSizeInBits() !=
1525 DestTy->getElementType()->getPrimitiveSizeInBits())
Stephen Hinesdce4a402014-05-29 02:49:00 -07001526 return nullptr;
Craig Topperb57c2922013-01-24 05:22:40 +00001527
Chris Lattner67451912010-05-08 21:50:26 +00001528 SrcTy = VectorType::get(DestTy->getElementType(), SrcTy->getNumElements());
1529 InVal = IC.Builder->CreateBitCast(InVal, SrcTy);
1530 }
Craig Topperb57c2922013-01-24 05:22:40 +00001531
Chris Lattner67451912010-05-08 21:50:26 +00001532 // Now that the element types match, get the shuffle mask and RHS of the
1533 // shuffle to use, which depends on whether we're increasing or decreasing the
1534 // size of the input.
Chris Lattner7302d802012-02-06 21:56:39 +00001535 SmallVector<uint32_t, 16> ShuffleMask;
Chris Lattner67451912010-05-08 21:50:26 +00001536 Value *V2;
Craig Topperb57c2922013-01-24 05:22:40 +00001537
Chris Lattner67451912010-05-08 21:50:26 +00001538 if (SrcTy->getNumElements() > DestTy->getNumElements()) {
1539 // If we're shrinking the number of elements, just shuffle in the low
1540 // elements from the input and use undef as the second shuffle input.
1541 V2 = UndefValue::get(SrcTy);
1542 for (unsigned i = 0, e = DestTy->getNumElements(); i != e; ++i)
Chris Lattner7302d802012-02-06 21:56:39 +00001543 ShuffleMask.push_back(i);
Craig Topperb57c2922013-01-24 05:22:40 +00001544
Chris Lattner67451912010-05-08 21:50:26 +00001545 } else {
1546 // If we're increasing the number of elements, shuffle in all of the
1547 // elements from InVal and fill the rest of the result elements with zeros
1548 // from a constant zero.
1549 V2 = Constant::getNullValue(SrcTy);
1550 unsigned SrcElts = SrcTy->getNumElements();
1551 for (unsigned i = 0, e = SrcElts; i != e; ++i)
Chris Lattner7302d802012-02-06 21:56:39 +00001552 ShuffleMask.push_back(i);
Chris Lattner67451912010-05-08 21:50:26 +00001553
1554 // The excess elements reference the first element of the zero input.
Chris Lattner7302d802012-02-06 21:56:39 +00001555 for (unsigned i = 0, e = DestTy->getNumElements()-SrcElts; i != e; ++i)
1556 ShuffleMask.push_back(SrcElts);
Chris Lattner67451912010-05-08 21:50:26 +00001557 }
Craig Topperb57c2922013-01-24 05:22:40 +00001558
Chris Lattner7302d802012-02-06 21:56:39 +00001559 return new ShuffleVectorInst(InVal, V2,
1560 ConstantDataVector::get(V2->getContext(),
1561 ShuffleMask));
Chris Lattner67451912010-05-08 21:50:26 +00001562}
1563
Chris Lattnerdb125cf2011-07-18 04:54:35 +00001564static bool isMultipleOfTypeSize(unsigned Value, Type *Ty) {
Chris Lattner3dd08732010-08-28 01:20:38 +00001565 return Value % Ty->getPrimitiveSizeInBits() == 0;
1566}
1567
Chris Lattnerdb125cf2011-07-18 04:54:35 +00001568static unsigned getTypeSizeIndex(unsigned Value, Type *Ty) {
Chris Lattner3dd08732010-08-28 01:20:38 +00001569 return Value / Ty->getPrimitiveSizeInBits();
1570}
1571
1572/// CollectInsertionElements - V is a value which is inserted into a vector of
1573/// VecEltTy. Look through the value to see if we can decompose it into
1574/// insertions into the vector. See the example in the comment for
1575/// OptimizeIntegerToVectorInsertions for the pattern this handles.
1576/// The type of V is always a non-zero multiple of VecEltTy's size.
Richard Sandiford23331c32013-08-12 07:26:09 +00001577/// Shift is the number of bits between the lsb of V and the lsb of
1578/// the vector.
Chris Lattner3dd08732010-08-28 01:20:38 +00001579///
1580/// This returns false if the pattern can't be matched or true if it can,
1581/// filling in Elements with the elements found here.
Richard Sandiford23331c32013-08-12 07:26:09 +00001582static bool CollectInsertionElements(Value *V, unsigned Shift,
Chris Lattner3dd08732010-08-28 01:20:38 +00001583 SmallVectorImpl<Value*> &Elements,
Richard Sandiford23331c32013-08-12 07:26:09 +00001584 Type *VecEltTy, InstCombiner &IC) {
1585 assert(isMultipleOfTypeSize(Shift, VecEltTy) &&
1586 "Shift should be a multiple of the element type size");
1587
Chris Lattner157d4ea2010-08-28 03:36:51 +00001588 // Undef values never contribute useful bits to the result.
1589 if (isa<UndefValue>(V)) return true;
Craig Topperb57c2922013-01-24 05:22:40 +00001590
Chris Lattner3dd08732010-08-28 01:20:38 +00001591 // If we got down to a value of the right type, we win, try inserting into the
1592 // right element.
1593 if (V->getType() == VecEltTy) {
Chris Lattner79007792010-08-28 01:50:57 +00001594 // Inserting null doesn't actually insert any elements.
1595 if (Constant *C = dyn_cast<Constant>(V))
1596 if (C->isNullValue())
1597 return true;
Craig Topperb57c2922013-01-24 05:22:40 +00001598
Richard Sandiford23331c32013-08-12 07:26:09 +00001599 unsigned ElementIndex = getTypeSizeIndex(Shift, VecEltTy);
1600 if (IC.getDataLayout()->isBigEndian())
1601 ElementIndex = Elements.size() - ElementIndex - 1;
1602
Chris Lattner3dd08732010-08-28 01:20:38 +00001603 // Fail if multiple elements are inserted into this slot.
Stephen Hinesdce4a402014-05-29 02:49:00 -07001604 if (Elements[ElementIndex])
Chris Lattner3dd08732010-08-28 01:20:38 +00001605 return false;
Craig Topperb57c2922013-01-24 05:22:40 +00001606
Chris Lattner3dd08732010-08-28 01:20:38 +00001607 Elements[ElementIndex] = V;
1608 return true;
1609 }
Craig Topperb57c2922013-01-24 05:22:40 +00001610
Chris Lattner79007792010-08-28 01:50:57 +00001611 if (Constant *C = dyn_cast<Constant>(V)) {
Chris Lattner3dd08732010-08-28 01:20:38 +00001612 // Figure out the # elements this provides, and bitcast it or slice it up
1613 // as required.
Chris Lattner79007792010-08-28 01:50:57 +00001614 unsigned NumElts = getTypeSizeIndex(C->getType()->getPrimitiveSizeInBits(),
1615 VecEltTy);
1616 // If the constant is the size of a vector element, we just need to bitcast
1617 // it to the right type so it gets properly inserted.
1618 if (NumElts == 1)
1619 return CollectInsertionElements(ConstantExpr::getBitCast(C, VecEltTy),
Richard Sandiford23331c32013-08-12 07:26:09 +00001620 Shift, Elements, VecEltTy, IC);
Craig Topperb57c2922013-01-24 05:22:40 +00001621
Chris Lattner79007792010-08-28 01:50:57 +00001622 // Okay, this is a constant that covers multiple elements. Slice it up into
1623 // pieces and insert each element-sized piece into the vector.
1624 if (!isa<IntegerType>(C->getType()))
1625 C = ConstantExpr::getBitCast(C, IntegerType::get(V->getContext(),
1626 C->getType()->getPrimitiveSizeInBits()));
1627 unsigned ElementSize = VecEltTy->getPrimitiveSizeInBits();
Chris Lattnerdb125cf2011-07-18 04:54:35 +00001628 Type *ElementIntTy = IntegerType::get(C->getContext(), ElementSize);
Craig Topperb57c2922013-01-24 05:22:40 +00001629
Chris Lattner79007792010-08-28 01:50:57 +00001630 for (unsigned i = 0; i != NumElts; ++i) {
Richard Sandiford23331c32013-08-12 07:26:09 +00001631 unsigned ShiftI = Shift+i*ElementSize;
Chris Lattner79007792010-08-28 01:50:57 +00001632 Constant *Piece = ConstantExpr::getLShr(C, ConstantInt::get(C->getType(),
Richard Sandiford23331c32013-08-12 07:26:09 +00001633 ShiftI));
Chris Lattner79007792010-08-28 01:50:57 +00001634 Piece = ConstantExpr::getTrunc(Piece, ElementIntTy);
Richard Sandiford23331c32013-08-12 07:26:09 +00001635 if (!CollectInsertionElements(Piece, ShiftI, Elements, VecEltTy, IC))
Chris Lattner79007792010-08-28 01:50:57 +00001636 return false;
1637 }
1638 return true;
1639 }
Craig Topperb57c2922013-01-24 05:22:40 +00001640
Chris Lattner3dd08732010-08-28 01:20:38 +00001641 if (!V->hasOneUse()) return false;
Craig Topperb57c2922013-01-24 05:22:40 +00001642
Chris Lattner3dd08732010-08-28 01:20:38 +00001643 Instruction *I = dyn_cast<Instruction>(V);
Stephen Hinesdce4a402014-05-29 02:49:00 -07001644 if (!I) return false;
Chris Lattner3dd08732010-08-28 01:20:38 +00001645 switch (I->getOpcode()) {
1646 default: return false; // Unhandled case.
1647 case Instruction::BitCast:
Richard Sandiford23331c32013-08-12 07:26:09 +00001648 return CollectInsertionElements(I->getOperand(0), Shift,
1649 Elements, VecEltTy, IC);
Chris Lattner3dd08732010-08-28 01:20:38 +00001650 case Instruction::ZExt:
1651 if (!isMultipleOfTypeSize(
1652 I->getOperand(0)->getType()->getPrimitiveSizeInBits(),
1653 VecEltTy))
1654 return false;
Richard Sandiford23331c32013-08-12 07:26:09 +00001655 return CollectInsertionElements(I->getOperand(0), Shift,
1656 Elements, VecEltTy, IC);
Chris Lattner3dd08732010-08-28 01:20:38 +00001657 case Instruction::Or:
Richard Sandiford23331c32013-08-12 07:26:09 +00001658 return CollectInsertionElements(I->getOperand(0), Shift,
1659 Elements, VecEltTy, IC) &&
1660 CollectInsertionElements(I->getOperand(1), Shift,
1661 Elements, VecEltTy, IC);
Chris Lattner3dd08732010-08-28 01:20:38 +00001662 case Instruction::Shl: {
1663 // Must be shifting by a constant that is a multiple of the element size.
1664 ConstantInt *CI = dyn_cast<ConstantInt>(I->getOperand(1));
Stephen Hinesdce4a402014-05-29 02:49:00 -07001665 if (!CI) return false;
Richard Sandiford23331c32013-08-12 07:26:09 +00001666 Shift += CI->getZExtValue();
1667 if (!isMultipleOfTypeSize(Shift, VecEltTy)) return false;
1668 return CollectInsertionElements(I->getOperand(0), Shift,
1669 Elements, VecEltTy, IC);
Chris Lattner3dd08732010-08-28 01:20:38 +00001670 }
Craig Topperb57c2922013-01-24 05:22:40 +00001671
Chris Lattner3dd08732010-08-28 01:20:38 +00001672 }
1673}
1674
1675
1676/// OptimizeIntegerToVectorInsertions - If the input is an 'or' instruction, we
1677/// may be doing shifts and ors to assemble the elements of the vector manually.
1678/// Try to rip the code out and replace it with insertelements. This is to
1679/// optimize code like this:
1680///
1681/// %tmp37 = bitcast float %inc to i32
1682/// %tmp38 = zext i32 %tmp37 to i64
1683/// %tmp31 = bitcast float %inc5 to i32
1684/// %tmp32 = zext i32 %tmp31 to i64
1685/// %tmp33 = shl i64 %tmp32, 32
1686/// %ins35 = or i64 %tmp33, %tmp38
1687/// %tmp43 = bitcast i64 %ins35 to <2 x float>
1688///
1689/// Into two insertelements that do "buildvector{%inc, %inc5}".
1690static Value *OptimizeIntegerToVectorInsertions(BitCastInst &CI,
1691 InstCombiner &IC) {
Richard Sandiford23331c32013-08-12 07:26:09 +00001692 // We need to know the target byte order to perform this optimization.
Stephen Hinesdce4a402014-05-29 02:49:00 -07001693 if (!IC.getDataLayout()) return nullptr;
Richard Sandiford23331c32013-08-12 07:26:09 +00001694
Chris Lattnerdb125cf2011-07-18 04:54:35 +00001695 VectorType *DestVecTy = cast<VectorType>(CI.getType());
Chris Lattner3dd08732010-08-28 01:20:38 +00001696 Value *IntInput = CI.getOperand(0);
1697
1698 SmallVector<Value*, 8> Elements(DestVecTy->getNumElements());
1699 if (!CollectInsertionElements(IntInput, 0, Elements,
Richard Sandiford23331c32013-08-12 07:26:09 +00001700 DestVecTy->getElementType(), IC))
Stephen Hinesdce4a402014-05-29 02:49:00 -07001701 return nullptr;
Chris Lattner3dd08732010-08-28 01:20:38 +00001702
1703 // If we succeeded, we know that all of the element are specified by Elements
1704 // or are zero if Elements has a null entry. Recast this as a set of
1705 // insertions.
1706 Value *Result = Constant::getNullValue(CI.getType());
1707 for (unsigned i = 0, e = Elements.size(); i != e; ++i) {
Stephen Hinesdce4a402014-05-29 02:49:00 -07001708 if (!Elements[i]) continue; // Unset element.
Craig Topperb57c2922013-01-24 05:22:40 +00001709
Chris Lattner3dd08732010-08-28 01:20:38 +00001710 Result = IC.Builder->CreateInsertElement(Result, Elements[i],
1711 IC.Builder->getInt32(i));
1712 }
Craig Topperb57c2922013-01-24 05:22:40 +00001713
Chris Lattner3dd08732010-08-28 01:20:38 +00001714 return Result;
1715}
1716
1717
Chris Lattnere5a14262010-08-26 21:55:42 +00001718/// OptimizeIntToFloatBitCast - See if we can optimize an integer->float/double
1719/// bitcast. The various long double bitcasts can't get in here.
Chris Lattner26dbe7e2010-08-26 22:14:59 +00001720static Instruction *OptimizeIntToFloatBitCast(BitCastInst &CI,InstCombiner &IC){
Ulrich Weigandfdc61772013-03-26 15:36:14 +00001721 // We need to know the target byte order to perform this optimization.
Stephen Hinesdce4a402014-05-29 02:49:00 -07001722 if (!IC.getDataLayout()) return nullptr;
Ulrich Weigandfdc61772013-03-26 15:36:14 +00001723
Chris Lattnere5a14262010-08-26 21:55:42 +00001724 Value *Src = CI.getOperand(0);
Chris Lattnerdb125cf2011-07-18 04:54:35 +00001725 Type *DestTy = CI.getType();
Chris Lattnere5a14262010-08-26 21:55:42 +00001726
1727 // If this is a bitcast from int to float, check to see if the int is an
1728 // extraction from a vector.
Stephen Hinesdce4a402014-05-29 02:49:00 -07001729 Value *VecInput = nullptr;
Chris Lattner26dbe7e2010-08-26 22:14:59 +00001730 // bitcast(trunc(bitcast(somevector)))
Chris Lattnere5a14262010-08-26 21:55:42 +00001731 if (match(Src, m_Trunc(m_BitCast(m_Value(VecInput)))) &&
1732 isa<VectorType>(VecInput->getType())) {
Chris Lattnerdb125cf2011-07-18 04:54:35 +00001733 VectorType *VecTy = cast<VectorType>(VecInput->getType());
Chris Lattner26dbe7e2010-08-26 22:14:59 +00001734 unsigned DestWidth = DestTy->getPrimitiveSizeInBits();
1735
1736 if (VecTy->getPrimitiveSizeInBits() % DestWidth == 0) {
1737 // If the element type of the vector doesn't match the result type,
1738 // bitcast it to be a vector type we can extract from.
1739 if (VecTy->getElementType() != DestTy) {
1740 VecTy = VectorType::get(DestTy,
1741 VecTy->getPrimitiveSizeInBits() / DestWidth);
1742 VecInput = IC.Builder->CreateBitCast(VecInput, VecTy);
1743 }
Craig Topperb57c2922013-01-24 05:22:40 +00001744
Ulrich Weigandfdc61772013-03-26 15:36:14 +00001745 unsigned Elt = 0;
1746 if (IC.getDataLayout()->isBigEndian())
1747 Elt = VecTy->getPrimitiveSizeInBits() / DestWidth - 1;
1748 return ExtractElementInst::Create(VecInput, IC.Builder->getInt32(Elt));
Chris Lattner26dbe7e2010-08-26 22:14:59 +00001749 }
Chris Lattnere5a14262010-08-26 21:55:42 +00001750 }
Craig Topperb57c2922013-01-24 05:22:40 +00001751
Chris Lattner26dbe7e2010-08-26 22:14:59 +00001752 // bitcast(trunc(lshr(bitcast(somevector), cst))
Stephen Hinesdce4a402014-05-29 02:49:00 -07001753 ConstantInt *ShAmt = nullptr;
Chris Lattner26dbe7e2010-08-26 22:14:59 +00001754 if (match(Src, m_Trunc(m_LShr(m_BitCast(m_Value(VecInput)),
1755 m_ConstantInt(ShAmt)))) &&
1756 isa<VectorType>(VecInput->getType())) {
Chris Lattnerdb125cf2011-07-18 04:54:35 +00001757 VectorType *VecTy = cast<VectorType>(VecInput->getType());
Chris Lattner26dbe7e2010-08-26 22:14:59 +00001758 unsigned DestWidth = DestTy->getPrimitiveSizeInBits();
1759 if (VecTy->getPrimitiveSizeInBits() % DestWidth == 0 &&
1760 ShAmt->getZExtValue() % DestWidth == 0) {
1761 // If the element type of the vector doesn't match the result type,
1762 // bitcast it to be a vector type we can extract from.
1763 if (VecTy->getElementType() != DestTy) {
1764 VecTy = VectorType::get(DestTy,
1765 VecTy->getPrimitiveSizeInBits() / DestWidth);
1766 VecInput = IC.Builder->CreateBitCast(VecInput, VecTy);
1767 }
Craig Topperb57c2922013-01-24 05:22:40 +00001768
Chris Lattner26dbe7e2010-08-26 22:14:59 +00001769 unsigned Elt = ShAmt->getZExtValue() / DestWidth;
Ulrich Weigandfdc61772013-03-26 15:36:14 +00001770 if (IC.getDataLayout()->isBigEndian())
1771 Elt = VecTy->getPrimitiveSizeInBits() / DestWidth - 1 - Elt;
Chris Lattner26dbe7e2010-08-26 22:14:59 +00001772 return ExtractElementInst::Create(VecInput, IC.Builder->getInt32(Elt));
1773 }
1774 }
Stephen Hinesdce4a402014-05-29 02:49:00 -07001775 return nullptr;
Chris Lattnere5a14262010-08-26 21:55:42 +00001776}
Chris Lattner67451912010-05-08 21:50:26 +00001777
Chris Lattner80f43d32010-01-04 07:53:58 +00001778Instruction *InstCombiner::visitBitCast(BitCastInst &CI) {
1779 // If the operands are integer typed then apply the integer transforms,
1780 // otherwise just apply the common ones.
1781 Value *Src = CI.getOperand(0);
Chris Lattnerdb125cf2011-07-18 04:54:35 +00001782 Type *SrcTy = Src->getType();
1783 Type *DestTy = CI.getType();
Chris Lattner80f43d32010-01-04 07:53:58 +00001784
Chris Lattner80f43d32010-01-04 07:53:58 +00001785 // Get rid of casts from one type to the same type. These are useless and can
1786 // be replaced by the operand.
1787 if (DestTy == Src->getType())
1788 return ReplaceInstUsesWith(CI, Src);
1789
Chris Lattnerdb125cf2011-07-18 04:54:35 +00001790 if (PointerType *DstPTy = dyn_cast<PointerType>(DestTy)) {
1791 PointerType *SrcPTy = cast<PointerType>(SrcTy);
1792 Type *DstElTy = DstPTy->getElementType();
1793 Type *SrcElTy = SrcPTy->getElementType();
Craig Topperb57c2922013-01-24 05:22:40 +00001794
Chris Lattner80f43d32010-01-04 07:53:58 +00001795 // If we are casting a alloca to a pointer to a type of the same
1796 // size, rewrite the allocation instruction to allocate the "right" type.
1797 // There is no need to modify malloc calls because it is their bitcast that
1798 // needs to be cleaned up.
1799 if (AllocaInst *AI = dyn_cast<AllocaInst>(Src))
1800 if (Instruction *V = PromoteCastOfAllocation(CI, *AI))
1801 return V;
Craig Topperb57c2922013-01-24 05:22:40 +00001802
Chris Lattner80f43d32010-01-04 07:53:58 +00001803 // If the source and destination are pointers, and this cast is equivalent
1804 // to a getelementptr X, 0, 0, 0... turn it into the appropriate gep.
1805 // This can enhance SROA and other transforms that want type-safe pointers.
1806 Constant *ZeroUInt =
1807 Constant::getNullValue(Type::getInt32Ty(CI.getContext()));
1808 unsigned NumZeros = 0;
Craig Topperb57c2922013-01-24 05:22:40 +00001809 while (SrcElTy != DstElTy &&
Duncan Sands1df98592010-02-16 11:11:14 +00001810 isa<CompositeType>(SrcElTy) && !SrcElTy->isPointerTy() &&
Chris Lattner80f43d32010-01-04 07:53:58 +00001811 SrcElTy->getNumContainedTypes() /* not "{}" */) {
1812 SrcElTy = cast<CompositeType>(SrcElTy)->getTypeAtIndex(ZeroUInt);
1813 ++NumZeros;
1814 }
1815
1816 // If we found a path from the src to dest, create the getelementptr now.
1817 if (SrcElTy == DstElTy) {
1818 SmallVector<Value*, 8> Idxs(NumZeros+1, ZeroUInt);
Jay Foada9203102011-07-25 09:48:08 +00001819 return GetElementPtrInst::CreateInBounds(Src, Idxs);
Chris Lattner80f43d32010-01-04 07:53:58 +00001820 }
1821 }
Craig Topperb57c2922013-01-24 05:22:40 +00001822
Chris Lattnere5a14262010-08-26 21:55:42 +00001823 // Try to optimize int -> float bitcasts.
1824 if ((DestTy->isFloatTy() || DestTy->isDoubleTy()) && isa<IntegerType>(SrcTy))
1825 if (Instruction *I = OptimizeIntToFloatBitCast(CI, *this))
1826 return I;
Chris Lattner80f43d32010-01-04 07:53:58 +00001827
Chris Lattnerdb125cf2011-07-18 04:54:35 +00001828 if (VectorType *DestVTy = dyn_cast<VectorType>(DestTy)) {
Duncan Sands1df98592010-02-16 11:11:14 +00001829 if (DestVTy->getNumElements() == 1 && !SrcTy->isVectorTy()) {
Chris Lattner7a34d6c2010-01-05 22:21:18 +00001830 Value *Elem = Builder->CreateBitCast(Src, DestVTy->getElementType());
1831 return InsertElementInst::Create(UndefValue::get(DestTy), Elem,
Chris Lattner80f43d32010-01-04 07:53:58 +00001832 Constant::getNullValue(Type::getInt32Ty(CI.getContext())));
Chris Lattner80f43d32010-01-04 07:53:58 +00001833 // FIXME: Canonicalize bitcast(insertelement) -> insertelement(bitcast)
1834 }
Craig Topperb57c2922013-01-24 05:22:40 +00001835
Chris Lattner3dd08732010-08-28 01:20:38 +00001836 if (isa<IntegerType>(SrcTy)) {
1837 // If this is a cast from an integer to vector, check to see if the input
1838 // is a trunc or zext of a bitcast from vector. If so, we can replace all
1839 // the casts with a shuffle and (potentially) a bitcast.
1840 if (isa<TruncInst>(Src) || isa<ZExtInst>(Src)) {
1841 CastInst *SrcCast = cast<CastInst>(Src);
1842 if (BitCastInst *BCIn = dyn_cast<BitCastInst>(SrcCast->getOperand(0)))
1843 if (isa<VectorType>(BCIn->getOperand(0)->getType()))
1844 if (Instruction *I = OptimizeVectorResize(BCIn->getOperand(0),
Chris Lattner67451912010-05-08 21:50:26 +00001845 cast<VectorType>(DestTy), *this))
Chris Lattner3dd08732010-08-28 01:20:38 +00001846 return I;
1847 }
Craig Topperb57c2922013-01-24 05:22:40 +00001848
Chris Lattner3dd08732010-08-28 01:20:38 +00001849 // If the input is an 'or' instruction, we may be doing shifts and ors to
1850 // assemble the elements of the vector manually. Try to rip the code out
1851 // and replace it with insertelements.
1852 if (Value *V = OptimizeIntegerToVectorInsertions(CI, *this))
1853 return ReplaceInstUsesWith(CI, V);
Chris Lattner67451912010-05-08 21:50:26 +00001854 }
Chris Lattner80f43d32010-01-04 07:53:58 +00001855 }
1856
Chris Lattnerdb125cf2011-07-18 04:54:35 +00001857 if (VectorType *SrcVTy = dyn_cast<VectorType>(SrcTy)) {
Michael Ilseman9c213cc2013-02-11 21:41:44 +00001858 if (SrcVTy->getNumElements() == 1) {
1859 // If our destination is not a vector, then make this a straight
1860 // scalar-scalar cast.
1861 if (!DestTy->isVectorTy()) {
1862 Value *Elem =
1863 Builder->CreateExtractElement(Src,
1864 Constant::getNullValue(Type::getInt32Ty(CI.getContext())));
1865 return CastInst::Create(Instruction::BitCast, Elem, DestTy);
1866 }
1867
1868 // Otherwise, see if our source is an insert. If so, then use the scalar
1869 // component directly.
1870 if (InsertElementInst *IEI =
1871 dyn_cast<InsertElementInst>(CI.getOperand(0)))
1872 return CastInst::Create(Instruction::BitCast, IEI->getOperand(1),
1873 DestTy);
Chris Lattner80f43d32010-01-04 07:53:58 +00001874 }
1875 }
1876
1877 if (ShuffleVectorInst *SVI = dyn_cast<ShuffleVectorInst>(Src)) {
Chris Lattner7a34d6c2010-01-05 22:21:18 +00001878 // Okay, we have (bitcast (shuffle ..)). Check to see if this is
Dan Gohmana5ced592010-04-07 23:22:42 +00001879 // a bitcast to a vector with the same # elts.
Craig Topperb57c2922013-01-24 05:22:40 +00001880 if (SVI->hasOneUse() && DestTy->isVectorTy() &&
Matt Arsenault3ea117e2013-08-14 00:24:34 +00001881 DestTy->getVectorNumElements() == SVI->getType()->getNumElements() &&
Chris Lattner7a34d6c2010-01-05 22:21:18 +00001882 SVI->getType()->getNumElements() ==
Matt Arsenault3ea117e2013-08-14 00:24:34 +00001883 SVI->getOperand(0)->getType()->getVectorNumElements()) {
Chris Lattner7a34d6c2010-01-05 22:21:18 +00001884 BitCastInst *Tmp;
1885 // If either of the operands is a cast from CI.getType(), then
1886 // evaluating the shuffle in the casted destination's type will allow
1887 // us to eliminate at least one cast.
Craig Topperb57c2922013-01-24 05:22:40 +00001888 if (((Tmp = dyn_cast<BitCastInst>(SVI->getOperand(0))) &&
Chris Lattner7a34d6c2010-01-05 22:21:18 +00001889 Tmp->getOperand(0)->getType() == DestTy) ||
Craig Topperb57c2922013-01-24 05:22:40 +00001890 ((Tmp = dyn_cast<BitCastInst>(SVI->getOperand(1))) &&
Chris Lattner7a34d6c2010-01-05 22:21:18 +00001891 Tmp->getOperand(0)->getType() == DestTy)) {
1892 Value *LHS = Builder->CreateBitCast(SVI->getOperand(0), DestTy);
1893 Value *RHS = Builder->CreateBitCast(SVI->getOperand(1), DestTy);
1894 // Return a new shuffle vector. Use the same element ID's, as we
1895 // know the vector types match #elts.
1896 return new ShuffleVectorInst(LHS, RHS, SVI->getOperand(2));
Chris Lattner80f43d32010-01-04 07:53:58 +00001897 }
1898 }
1899 }
Craig Topperb57c2922013-01-24 05:22:40 +00001900
Duncan Sands1df98592010-02-16 11:11:14 +00001901 if (SrcTy->isPointerTy())
Chris Lattner7a34d6c2010-01-05 22:21:18 +00001902 return commonPointerCastTransforms(CI);
1903 return commonCastTransforms(CI);
Chris Lattner80f43d32010-01-04 07:53:58 +00001904}
Matt Arsenault6dd44d32013-11-15 05:45:08 +00001905
1906Instruction *InstCombiner::visitAddrSpaceCast(AddrSpaceCastInst &CI) {
Stephen Hines36b56882014-04-23 16:57:46 -07001907 return commonPointerCastTransforms(CI);
Matt Arsenault6dd44d32013-11-15 05:45:08 +00001908}