blob: 71ce74959c2d1e640456cc6e9691b11302bba052 [file] [log] [blame]
Chris Lattner2b295a02010-01-04 07:53:58 +00001//===- InstCombineCasts.cpp -----------------------------------------------===//
2//
3// The LLVM Compiler Infrastructure
4//
5// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
9//
10// This file implements the visit functions for cast operations.
11//
12//===----------------------------------------------------------------------===//
13
Chandler Carrutha9174582015-01-22 05:25:13 +000014#include "InstCombineInternal.h"
Eli Friedman911e12f2011-07-20 21:57:23 +000015#include "llvm/Analysis/ConstantFolding.h"
Chandler Carruth9fb823b2013-01-02 11:36:10 +000016#include "llvm/IR/DataLayout.h"
Chandler Carruth820a9082014-03-04 11:08:18 +000017#include "llvm/IR/PatternMatch.h"
Chandler Carruth62d42152015-01-15 02:16:27 +000018#include "llvm/Analysis/TargetLibraryInfo.h"
Chris Lattner2b295a02010-01-04 07:53:58 +000019using namespace llvm;
20using namespace PatternMatch;
21
Chandler Carruth964daaa2014-04-22 02:55:47 +000022#define DEBUG_TYPE "instcombine"
23
Chris Lattner59d95742010-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 Gohman05a65552010-05-28 04:33:04 +000029 uint64_t &Offset) {
Chris Lattner59d95742010-01-04 07:59:07 +000030 if (ConstantInt *CI = dyn_cast<ConstantInt>(Val)) {
31 Offset = CI->getZExtValue();
32 Scale = 0;
Dan Gohman05a65552010-05-28 04:33:04 +000033 return ConstantInt::get(Val->getType(), 0);
Chris Lattneraaccc8d2010-01-05 20:57:30 +000034 }
Craig Topper3529aa52013-01-24 05:22:40 +000035
Chris Lattneraaccc8d2010-01-05 20:57:30 +000036 if (BinaryOperator *I = dyn_cast<BinaryOperator>(Val)) {
Bob Wilson3c68b622011-07-08 22:09:33 +000037 // Cannot look past anything that might overflow.
38 OverflowingBinaryOperator *OBI = dyn_cast<OverflowingBinaryOperator>(Val);
Stepan Dyatkovskiycb2a1a32012-05-05 07:09:40 +000039 if (OBI && !OBI->hasNoUnsignedWrap() && !OBI->hasNoSignedWrap()) {
Bob Wilson3c68b622011-07-08 22:09:33 +000040 Scale = 1;
41 Offset = 0;
42 return Val;
43 }
44
Chris Lattner59d95742010-01-04 07:59:07 +000045 if (ConstantInt *RHS = dyn_cast<ConstantInt>(I->getOperand(1))) {
46 if (I->getOpcode() == Instruction::Shl) {
47 // This is a value scaled by '1 << the shift amt'.
Dan Gohman05a65552010-05-28 04:33:04 +000048 Scale = UINT64_C(1) << RHS->getZExtValue();
Chris Lattner59d95742010-01-04 07:59:07 +000049 Offset = 0;
50 return I->getOperand(0);
Chris Lattneraaccc8d2010-01-05 20:57:30 +000051 }
Craig Topper3529aa52013-01-24 05:22:40 +000052
Chris Lattneraaccc8d2010-01-05 20:57:30 +000053 if (I->getOpcode() == Instruction::Mul) {
Chris Lattner59d95742010-01-04 07:59:07 +000054 // This value is scaled by 'RHS'.
55 Scale = RHS->getZExtValue();
56 Offset = 0;
57 return I->getOperand(0);
Chris Lattneraaccc8d2010-01-05 20:57:30 +000058 }
Craig Topper3529aa52013-01-24 05:22:40 +000059
Chris Lattneraaccc8d2010-01-05 20:57:30 +000060 if (I->getOpcode() == Instruction::Add) {
Craig Topper3529aa52013-01-24 05:22:40 +000061 // We have X+C. Check to see if we really have (X*C2)+C1,
Chris Lattner59d95742010-01-04 07:59:07 +000062 // where C1 is divisible by C2.
63 unsigned SubScale;
Craig Topper3529aa52013-01-24 05:22:40 +000064 Value *SubVal =
Chris Lattner59d95742010-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) {
Chris Lattner229907c2011-07-18 04:54:35 +000083 PointerType *PTy = cast<PointerType>(CI.getType());
Craig Topper3529aa52013-01-24 05:22:40 +000084
Chris Lattner59d95742010-01-04 07:59:07 +000085 BuilderTy AllocaBuilder(*Builder);
86 AllocaBuilder.SetInsertPoint(AI.getParent(), &AI);
87
88 // Get the type really allocated and the type casted to.
Chris Lattner229907c2011-07-18 04:54:35 +000089 Type *AllocElTy = AI.getAllocatedType();
90 Type *CastElTy = PTy->getElementType();
Craig Topperf40110f2014-04-25 05:29:35 +000091 if (!AllocElTy->isSized() || !CastElTy->isSized()) return nullptr;
Chris Lattner59d95742010-01-04 07:59:07 +000092
Mehdi Aminia28d91d2015-03-10 02:37:25 +000093 unsigned AllocElTyAlign = DL.getABITypeAlignment(AllocElTy);
94 unsigned CastElTyAlign = DL.getABITypeAlignment(CastElTy);
Craig Topperf40110f2014-04-25 05:29:35 +000095 if (CastElTyAlign < AllocElTyAlign) return nullptr;
Chris Lattner59d95742010-01-04 07:59:07 +000096
97 // If the allocation has multiple uses, only promote it if we are strictly
98 // increasing the alignment of the resultant allocation. If we keep it the
Devang Patelfbb482b2011-03-08 22:12:11 +000099 // same, we open the door to infinite loops of various kinds.
Craig Topperf40110f2014-04-25 05:29:35 +0000100 if (!AI.hasOneUse() && CastElTyAlign == AllocElTyAlign) return nullptr;
Chris Lattner59d95742010-01-04 07:59:07 +0000101
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000102 uint64_t AllocElTySize = DL.getTypeAllocSize(AllocElTy);
103 uint64_t CastElTySize = DL.getTypeAllocSize(CastElTy);
Craig Topperf40110f2014-04-25 05:29:35 +0000104 if (CastElTySize == 0 || AllocElTySize == 0) return nullptr;
Chris Lattner59d95742010-01-04 07:59:07 +0000105
Jim Grosbach95d2eb92013-03-06 05:44:53 +0000106 // If the allocation has multiple uses, only promote it if we're not
107 // shrinking the amount of memory being allocated.
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000108 uint64_t AllocElTyStoreSize = DL.getTypeStoreSize(AllocElTy);
109 uint64_t CastElTyStoreSize = DL.getTypeStoreSize(CastElTy);
Craig Topperf40110f2014-04-25 05:29:35 +0000110 if (!AI.hasOneUse() && CastElTyStoreSize < AllocElTyStoreSize) return nullptr;
Jim Grosbach95d2eb92013-03-06 05:44:53 +0000111
Chris Lattner59d95742010-01-04 07:59:07 +0000112 // See if we can satisfy the modulus by pulling a scale out of the array
113 // size argument.
114 unsigned ArraySizeScale;
Dan Gohman05a65552010-05-28 04:33:04 +0000115 uint64_t ArrayOffset;
Chris Lattner59d95742010-01-04 07:59:07 +0000116 Value *NumElements = // See if the array size is a decomposable linear expr.
117 DecomposeSimpleLinearExpr(AI.getOperand(0), ArraySizeScale, ArrayOffset);
Craig Topper3529aa52013-01-24 05:22:40 +0000118
Chris Lattner59d95742010-01-04 07:59:07 +0000119 // If we can now satisfy the modulus, by using a non-1 scale, we really can
120 // do the xform.
121 if ((AllocElTySize*ArraySizeScale) % CastElTySize != 0 ||
Craig Topperf40110f2014-04-25 05:29:35 +0000122 (AllocElTySize*ArrayOffset ) % CastElTySize != 0) return nullptr;
Chris Lattner59d95742010-01-04 07:59:07 +0000123
124 unsigned Scale = (AllocElTySize*ArraySizeScale)/CastElTySize;
Craig Topperf40110f2014-04-25 05:29:35 +0000125 Value *Amt = nullptr;
Chris Lattner59d95742010-01-04 07:59:07 +0000126 if (Scale == 1) {
127 Amt = NumElements;
128 } else {
Dan Gohman05a65552010-05-28 04:33:04 +0000129 Amt = ConstantInt::get(AI.getArraySize()->getType(), Scale);
Chris Lattner59d95742010-01-04 07:59:07 +0000130 // Insert before the alloca, not before the cast.
Benjamin Kramer547b6c52011-09-27 20:39:19 +0000131 Amt = AllocaBuilder.CreateMul(Amt, NumElements);
Chris Lattner59d95742010-01-04 07:59:07 +0000132 }
Craig Topper3529aa52013-01-24 05:22:40 +0000133
Dan Gohman05a65552010-05-28 04:33:04 +0000134 if (uint64_t Offset = (AllocElTySize*ArrayOffset)/CastElTySize) {
135 Value *Off = ConstantInt::get(AI.getArraySize()->getType(),
Chris Lattner59d95742010-01-04 07:59:07 +0000136 Offset, true);
Benjamin Kramer547b6c52011-09-27 20:39:19 +0000137 Amt = AllocaBuilder.CreateAdd(Amt, Off);
Chris Lattner59d95742010-01-04 07:59:07 +0000138 }
Craig Topper3529aa52013-01-24 05:22:40 +0000139
Chris Lattner59d95742010-01-04 07:59:07 +0000140 AllocaInst *New = AllocaBuilder.CreateAlloca(CastElTy, Amt);
141 New->setAlignment(AI.getAlignment());
142 New->takeName(&AI);
Hans Wennborge36e1162014-04-28 17:40:03 +0000143 New->setUsedWithInAlloca(AI.isUsedWithInAlloca());
Craig Topper3529aa52013-01-24 05:22:40 +0000144
Chris Lattner59d95742010-01-04 07:59:07 +0000145 // If the allocation has multiple real uses, insert a cast and change all
146 // things that used it to use the new cast. This will also hack on CI, but it
147 // will die soon.
Devang Patelfbb482b2011-03-08 22:12:11 +0000148 if (!AI.hasOneUse()) {
Chris Lattner59d95742010-01-04 07:59:07 +0000149 // New is the allocation instruction, pointer typed. AI is the original
150 // allocation instruction, also pointer typed. Thus, cast to use is BitCast.
151 Value *NewCast = AllocaBuilder.CreateBitCast(New, AI.getType(), "tmpcast");
Eli Friedmanb9ed18f2011-05-18 00:32:01 +0000152 ReplaceInstUsesWith(AI, NewCast);
Chris Lattner59d95742010-01-04 07:59:07 +0000153 }
154 return ReplaceInstUsesWith(CI, New);
155}
156
Craig Topper3529aa52013-01-24 05:22:40 +0000157/// EvaluateInDifferentType - Given an expression that
Chris Lattner10840e92010-01-08 19:19:23 +0000158/// CanEvaluateTruncated or CanEvaluateSExtd returns true for, actually
Chris Lattner98748c02010-01-06 01:56:21 +0000159/// insert the code to evaluate the expression.
Craig Topper3529aa52013-01-24 05:22:40 +0000160Value *InstCombiner::EvaluateInDifferentType(Value *V, Type *Ty,
Chris Lattner92be2ad2010-01-04 07:54:59 +0000161 bool isSigned) {
Chris Lattner9242ae02010-01-08 19:28:47 +0000162 if (Constant *C = dyn_cast<Constant>(V)) {
163 C = ConstantExpr::getIntegerCast(C, Ty, isSigned /*Sext or ZExt*/);
Rafael Espindola37dc9e12014-02-21 00:06:31 +0000164 // If we got a constantexpr back, try to simplify it with DL info.
Chris Lattner9242ae02010-01-08 19:28:47 +0000165 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(C))
Rafael Espindola37dc9e12014-02-21 00:06:31 +0000166 C = ConstantFoldConstantExpression(CE, DL, TLI);
Chris Lattner9242ae02010-01-08 19:28:47 +0000167 return C;
168 }
Chris Lattner92be2ad2010-01-04 07:54:59 +0000169
170 // Otherwise, it must be an instruction.
171 Instruction *I = cast<Instruction>(V);
Craig Topperf40110f2014-04-25 05:29:35 +0000172 Instruction *Res = nullptr;
Chris Lattner92be2ad2010-01-04 07:54:59 +0000173 unsigned Opc = I->getOpcode();
174 switch (Opc) {
175 case Instruction::Add:
176 case Instruction::Sub:
177 case Instruction::Mul:
178 case Instruction::And:
179 case Instruction::Or:
180 case Instruction::Xor:
181 case Instruction::AShr:
182 case Instruction::LShr:
183 case Instruction::Shl:
184 case Instruction::UDiv:
185 case Instruction::URem: {
186 Value *LHS = EvaluateInDifferentType(I->getOperand(0), Ty, isSigned);
187 Value *RHS = EvaluateInDifferentType(I->getOperand(1), Ty, isSigned);
188 Res = BinaryOperator::Create((Instruction::BinaryOps)Opc, LHS, RHS);
189 break;
Craig Topper3529aa52013-01-24 05:22:40 +0000190 }
Chris Lattner92be2ad2010-01-04 07:54:59 +0000191 case Instruction::Trunc:
192 case Instruction::ZExt:
193 case Instruction::SExt:
194 // If the source type of the cast is the type we're trying for then we can
195 // just return the source. There's no need to insert it because it is not
196 // new.
197 if (I->getOperand(0)->getType() == Ty)
198 return I->getOperand(0);
Craig Topper3529aa52013-01-24 05:22:40 +0000199
Chris Lattner92be2ad2010-01-04 07:54:59 +0000200 // Otherwise, must be the same type of cast, so just reinsert a new one.
Chris Lattner39d2daa2010-01-10 20:25:54 +0000201 // This also handles the case of zext(trunc(x)) -> zext(x).
202 Res = CastInst::CreateIntegerCast(I->getOperand(0), Ty,
203 Opc == Instruction::SExt);
Chris Lattner92be2ad2010-01-04 07:54:59 +0000204 break;
205 case Instruction::Select: {
206 Value *True = EvaluateInDifferentType(I->getOperand(1), Ty, isSigned);
207 Value *False = EvaluateInDifferentType(I->getOperand(2), Ty, isSigned);
208 Res = SelectInst::Create(I->getOperand(0), True, False);
209 break;
210 }
211 case Instruction::PHI: {
212 PHINode *OPN = cast<PHINode>(I);
Jay Foad52131342011-03-30 11:28:46 +0000213 PHINode *NPN = PHINode::Create(Ty, OPN->getNumIncomingValues());
Chris Lattner92be2ad2010-01-04 07:54:59 +0000214 for (unsigned i = 0, e = OPN->getNumIncomingValues(); i != e; ++i) {
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000215 Value *V =
216 EvaluateInDifferentType(OPN->getIncomingValue(i), Ty, isSigned);
Chris Lattner92be2ad2010-01-04 07:54:59 +0000217 NPN->addIncoming(V, OPN->getIncomingBlock(i));
218 }
219 Res = NPN;
220 break;
221 }
Craig Topper3529aa52013-01-24 05:22:40 +0000222 default:
Chris Lattner92be2ad2010-01-04 07:54:59 +0000223 // TODO: Can handle more cases here.
224 llvm_unreachable("Unreachable!");
Chris Lattner92be2ad2010-01-04 07:54:59 +0000225 }
Craig Topper3529aa52013-01-24 05:22:40 +0000226
Chris Lattner92be2ad2010-01-04 07:54:59 +0000227 Res->takeName(I);
Eli Friedman35211c62011-05-27 00:19:40 +0000228 return InsertNewInstWith(Res, *I);
Chris Lattner92be2ad2010-01-04 07:54:59 +0000229}
Chris Lattner2b295a02010-01-04 07:53:58 +0000230
231
232/// This function is a wrapper around CastInst::isEliminableCastPair. It
233/// simply extracts arguments and returns what that function returns.
Craig Topper3529aa52013-01-24 05:22:40 +0000234static Instruction::CastOps
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000235isEliminableCastPair(const CastInst *CI, ///< First cast instruction
236 unsigned opcode, ///< Opcode for the second cast
237 Type *DstTy, ///< Target type for the second cast
238 const DataLayout &DL) {
Chris Lattner229907c2011-07-18 04:54:35 +0000239 Type *SrcTy = CI->getOperand(0)->getType(); // A from above
240 Type *MidTy = CI->getType(); // B from above
Chris Lattner2b295a02010-01-04 07:53:58 +0000241
242 // Get the opcodes of the two Cast instructions
243 Instruction::CastOps firstOp = Instruction::CastOps(CI->getOpcode());
244 Instruction::CastOps secondOp = Instruction::CastOps(opcode);
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000245 Type *SrcIntPtrTy =
246 SrcTy->isPtrOrPtrVectorTy() ? DL.getIntPtrType(SrcTy) : nullptr;
247 Type *MidIntPtrTy =
248 MidTy->isPtrOrPtrVectorTy() ? DL.getIntPtrType(MidTy) : nullptr;
249 Type *DstIntPtrTy =
250 DstTy->isPtrOrPtrVectorTy() ? DL.getIntPtrType(DstTy) : nullptr;
Chris Lattner2b295a02010-01-04 07:53:58 +0000251 unsigned Res = CastInst::isEliminableCastPair(firstOp, secondOp, SrcTy, MidTy,
Duncan Sandse2395dc2012-10-30 16:03:32 +0000252 DstTy, SrcIntPtrTy, MidIntPtrTy,
253 DstIntPtrTy);
Micah Villmow12d91272012-10-24 15:52:52 +0000254
Chris Lattner2b295a02010-01-04 07:53:58 +0000255 // We don't want to form an inttoptr or ptrtoint that converts to an integer
256 // type that differs from the pointer size.
Duncan Sandse2395dc2012-10-30 16:03:32 +0000257 if ((Res == Instruction::IntToPtr && SrcTy != DstIntPtrTy) ||
258 (Res == Instruction::PtrToInt && DstTy != SrcIntPtrTy))
Chris Lattner2b295a02010-01-04 07:53:58 +0000259 Res = 0;
Craig Topper3529aa52013-01-24 05:22:40 +0000260
Chris Lattner2b295a02010-01-04 07:53:58 +0000261 return Instruction::CastOps(Res);
262}
263
Chris Lattner4e8137d2010-02-11 06:26:33 +0000264/// ShouldOptimizeCast - Return true if the cast from "V to Ty" actually
265/// results in any code being generated and is interesting to optimize out. If
266/// the cast can be eliminated by some other simple transformation, we prefer
267/// to do the simplification first.
268bool InstCombiner::ShouldOptimizeCast(Instruction::CastOps opc, const Value *V,
Chris Lattner229907c2011-07-18 04:54:35 +0000269 Type *Ty) {
Chris Lattner4e8137d2010-02-11 06:26:33 +0000270 // Noop casts and casts of constants should be eliminated trivially.
Chris Lattner2b295a02010-01-04 07:53:58 +0000271 if (V->getType() == Ty || isa<Constant>(V)) return false;
Craig Topper3529aa52013-01-24 05:22:40 +0000272
Chris Lattner4e8137d2010-02-11 06:26:33 +0000273 // If this is another cast that can be eliminated, we prefer to have it
274 // eliminated.
Chris Lattner2b295a02010-01-04 07:53:58 +0000275 if (const CastInst *CI = dyn_cast<CastInst>(V))
Rafael Espindola37dc9e12014-02-21 00:06:31 +0000276 if (isEliminableCastPair(CI, opc, Ty, DL))
Chris Lattner2b295a02010-01-04 07:53:58 +0000277 return false;
Craig Topper3529aa52013-01-24 05:22:40 +0000278
Chris Lattner4e8137d2010-02-11 06:26:33 +0000279 // If this is a vector sext from a compare, then we don't want to break the
280 // idiom where each element of the extended vector is either zero or all ones.
Duncan Sands19d0b472010-02-16 11:11:14 +0000281 if (opc == Instruction::SExt && isa<CmpInst>(V) && Ty->isVectorTy())
Chris Lattner4e8137d2010-02-11 06:26:33 +0000282 return false;
Craig Topper3529aa52013-01-24 05:22:40 +0000283
Chris Lattner2b295a02010-01-04 07:53:58 +0000284 return true;
285}
286
287
288/// @brief Implement the transforms common to all CastInst visitors.
289Instruction *InstCombiner::commonCastTransforms(CastInst &CI) {
290 Value *Src = CI.getOperand(0);
291
292 // Many cases of "cast of a cast" are eliminable. If it's eliminable we just
293 // eliminate it now.
294 if (CastInst *CSrc = dyn_cast<CastInst>(Src)) { // A->B->C cast
Craig Topper3529aa52013-01-24 05:22:40 +0000295 if (Instruction::CastOps opc =
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000296 isEliminableCastPair(CSrc, CI.getOpcode(), CI.getType(), DL)) {
Chris Lattner2b295a02010-01-04 07:53:58 +0000297 // The first cast (CSrc) is eliminable so we need to fix up or replace
298 // the second cast (CI). CSrc will then have a good chance of being dead.
299 return CastInst::Create(opc, CSrc->getOperand(0), CI.getType());
300 }
301 }
302
303 // If we are casting a select then fold the cast into the select
304 if (SelectInst *SI = dyn_cast<SelectInst>(Src))
305 if (Instruction *NV = FoldOpIntoSelect(CI, SI))
306 return NV;
307
308 // If we are casting a PHI then fold the cast into the PHI
309 if (isa<PHINode>(Src)) {
310 // We don't do this if this would create a PHI node with an illegal type if
311 // it is currently legal.
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000312 if (!Src->getType()->isIntegerTy() || !CI.getType()->isIntegerTy() ||
Chris Lattner2b295a02010-01-04 07:53:58 +0000313 ShouldChangeType(CI.getType(), Src->getType()))
314 if (Instruction *NV = FoldOpIntoPhi(CI))
315 return NV;
316 }
Craig Topper3529aa52013-01-24 05:22:40 +0000317
Craig Topperf40110f2014-04-25 05:29:35 +0000318 return nullptr;
Chris Lattner2b295a02010-01-04 07:53:58 +0000319}
320
Chris Lattnerc3aca382010-01-10 00:58:42 +0000321/// CanEvaluateTruncated - Return true if we can evaluate the specified
322/// expression tree as type Ty instead of its larger type, and arrive with the
323/// same value. This is used by code that tries to eliminate truncates.
324///
325/// Ty will always be a type smaller than V. We should return true if trunc(V)
326/// can be computed by computing V in the smaller type. If V is an instruction,
327/// then trunc(inst(x,y)) can be computed as inst(trunc(x),trunc(y)), which only
328/// makes sense if x and y can be efficiently truncated.
329///
Chris Lattner172630a2010-01-11 02:43:35 +0000330/// This function works on both vectors and scalars.
331///
Hal Finkel60db0582014-09-07 18:57:58 +0000332static bool CanEvaluateTruncated(Value *V, Type *Ty, InstCombiner &IC,
333 Instruction *CxtI) {
Chris Lattnerc3aca382010-01-10 00:58:42 +0000334 // We can always evaluate constants in another type.
335 if (isa<Constant>(V))
336 return true;
Craig Topper3529aa52013-01-24 05:22:40 +0000337
Chris Lattnerc3aca382010-01-10 00:58:42 +0000338 Instruction *I = dyn_cast<Instruction>(V);
339 if (!I) return false;
Craig Topper3529aa52013-01-24 05:22:40 +0000340
Chris Lattner229907c2011-07-18 04:54:35 +0000341 Type *OrigTy = V->getType();
Craig Topper3529aa52013-01-24 05:22:40 +0000342
Chris Lattnera6b13562010-01-11 22:45:25 +0000343 // If this is an extension from the dest type, we can eliminate it, even if it
344 // has multiple uses.
Craig Topper3529aa52013-01-24 05:22:40 +0000345 if ((isa<ZExtInst>(I) || isa<SExtInst>(I)) &&
Chris Lattnerc3aca382010-01-10 00:58:42 +0000346 I->getOperand(0)->getType() == Ty)
347 return true;
348
349 // We can't extend or shrink something that has multiple uses: doing so would
350 // require duplicating the instruction in general, which isn't profitable.
351 if (!I->hasOneUse()) return false;
352
353 unsigned Opc = I->getOpcode();
354 switch (Opc) {
355 case Instruction::Add:
356 case Instruction::Sub:
357 case Instruction::Mul:
358 case Instruction::And:
359 case Instruction::Or:
360 case Instruction::Xor:
361 // These operators can all arbitrarily be extended or truncated.
Hal Finkel60db0582014-09-07 18:57:58 +0000362 return CanEvaluateTruncated(I->getOperand(0), Ty, IC, CxtI) &&
363 CanEvaluateTruncated(I->getOperand(1), Ty, IC, CxtI);
Chris Lattnerc3aca382010-01-10 00:58:42 +0000364
365 case Instruction::UDiv:
366 case Instruction::URem: {
367 // UDiv and URem can be truncated if all the truncated bits are zero.
368 uint32_t OrigBitWidth = OrigTy->getScalarSizeInBits();
369 uint32_t BitWidth = Ty->getScalarSizeInBits();
370 if (BitWidth < OrigBitWidth) {
371 APInt Mask = APInt::getHighBitsSet(OrigBitWidth, OrigBitWidth-BitWidth);
Hal Finkel60db0582014-09-07 18:57:58 +0000372 if (IC.MaskedValueIsZero(I->getOperand(0), Mask, 0, CxtI) &&
373 IC.MaskedValueIsZero(I->getOperand(1), Mask, 0, CxtI)) {
374 return CanEvaluateTruncated(I->getOperand(0), Ty, IC, CxtI) &&
375 CanEvaluateTruncated(I->getOperand(1), Ty, IC, CxtI);
Chris Lattnerc3aca382010-01-10 00:58:42 +0000376 }
377 }
378 break;
379 }
380 case Instruction::Shl:
381 // If we are truncating the result of this SHL, and if it's a shift of a
382 // constant amount, we can always perform a SHL in a smaller type.
383 if (ConstantInt *CI = dyn_cast<ConstantInt>(I->getOperand(1))) {
384 uint32_t BitWidth = Ty->getScalarSizeInBits();
385 if (CI->getLimitedValue(BitWidth) < BitWidth)
Hal Finkel60db0582014-09-07 18:57:58 +0000386 return CanEvaluateTruncated(I->getOperand(0), Ty, IC, CxtI);
Chris Lattnerc3aca382010-01-10 00:58:42 +0000387 }
388 break;
389 case Instruction::LShr:
390 // If this is a truncate of a logical shr, we can truncate it to a smaller
Sylvestre Ledru91ce36c2012-09-27 10:14:43 +0000391 // lshr iff we know that the bits we would otherwise be shifting in are
Chris Lattnerc3aca382010-01-10 00:58:42 +0000392 // already zeros.
393 if (ConstantInt *CI = dyn_cast<ConstantInt>(I->getOperand(1))) {
394 uint32_t OrigBitWidth = OrigTy->getScalarSizeInBits();
395 uint32_t BitWidth = Ty->getScalarSizeInBits();
Hal Finkel60db0582014-09-07 18:57:58 +0000396 if (IC.MaskedValueIsZero(I->getOperand(0),
397 APInt::getHighBitsSet(OrigBitWidth, OrigBitWidth-BitWidth), 0, CxtI) &&
Chris Lattnerc3aca382010-01-10 00:58:42 +0000398 CI->getLimitedValue(BitWidth) < BitWidth) {
Hal Finkel60db0582014-09-07 18:57:58 +0000399 return CanEvaluateTruncated(I->getOperand(0), Ty, IC, CxtI);
Chris Lattnerc3aca382010-01-10 00:58:42 +0000400 }
401 }
402 break;
403 case Instruction::Trunc:
404 // trunc(trunc(x)) -> trunc(x)
405 return true;
Chris Lattner73984342010-08-27 20:32:06 +0000406 case Instruction::ZExt:
407 case Instruction::SExt:
408 // trunc(ext(x)) -> ext(x) if the source type is smaller than the new dest
409 // trunc(ext(x)) -> trunc(x) if the source type is larger than the new dest
410 return true;
Chris Lattnerc3aca382010-01-10 00:58:42 +0000411 case Instruction::Select: {
412 SelectInst *SI = cast<SelectInst>(I);
Hal Finkel60db0582014-09-07 18:57:58 +0000413 return CanEvaluateTruncated(SI->getTrueValue(), Ty, IC, CxtI) &&
414 CanEvaluateTruncated(SI->getFalseValue(), Ty, IC, CxtI);
Chris Lattnerc3aca382010-01-10 00:58:42 +0000415 }
416 case Instruction::PHI: {
417 // We can change a phi if we can change all operands. Note that we never
418 // get into trouble with cyclic PHIs here because we only consider
419 // instructions with a single use.
420 PHINode *PN = cast<PHINode>(I);
Pete Cooper833f34d2015-05-12 20:05:31 +0000421 for (Value *IncValue : PN->incoming_values())
422 if (!CanEvaluateTruncated(IncValue, Ty, IC, CxtI))
Chris Lattnerc3aca382010-01-10 00:58:42 +0000423 return false;
424 return true;
425 }
426 default:
427 // TODO: Can handle more cases here.
428 break;
429 }
Craig Topper3529aa52013-01-24 05:22:40 +0000430
Chris Lattnerc3aca382010-01-10 00:58:42 +0000431 return false;
432}
433
434Instruction *InstCombiner::visitTrunc(TruncInst &CI) {
Chris Lattner883550a2010-01-10 01:00:46 +0000435 if (Instruction *Result = commonCastTransforms(CI))
Chris Lattnerc3aca382010-01-10 00:58:42 +0000436 return Result;
Craig Topper3529aa52013-01-24 05:22:40 +0000437
James Molloy2b21a7c2015-05-20 18:41:25 +0000438 // Test if the trunc is the user of a select which is part of a
439 // minimum or maximum operation. If so, don't do any more simplification.
440 // Even simplifying demanded bits can break the canonical form of a
441 // min/max.
442 Value *LHS, *RHS;
443 if (SelectInst *SI = dyn_cast<SelectInst>(CI.getOperand(0)))
James Molloy134bec22015-08-11 09:12:57 +0000444 if (matchSelectPattern(SI, LHS, RHS).Flavor != SPF_UNKNOWN)
James Molloy2b21a7c2015-05-20 18:41:25 +0000445 return nullptr;
446
Craig Topper3529aa52013-01-24 05:22:40 +0000447 // See if we can simplify any instructions used by the input whose sole
Chris Lattner883550a2010-01-10 01:00:46 +0000448 // purpose is to compute bits we don't care about.
449 if (SimplifyDemandedInstructionBits(CI))
450 return &CI;
Craig Topper3529aa52013-01-24 05:22:40 +0000451
Chris Lattnerc3aca382010-01-10 00:58:42 +0000452 Value *Src = CI.getOperand(0);
Chris Lattner229907c2011-07-18 04:54:35 +0000453 Type *DestTy = CI.getType(), *SrcTy = Src->getType();
Craig Topper3529aa52013-01-24 05:22:40 +0000454
Chris Lattnerc3aca382010-01-10 00:58:42 +0000455 // Attempt to truncate the entire input expression tree to the destination
456 // type. Only do this if the dest type is a simple type, don't convert the
Chris Lattner2b295a02010-01-04 07:53:58 +0000457 // expression tree to something weird like i93 unless the source is also
458 // strange.
Duncan Sands19d0b472010-02-16 11:11:14 +0000459 if ((DestTy->isVectorTy() || ShouldChangeType(SrcTy, DestTy)) &&
Hal Finkel60db0582014-09-07 18:57:58 +0000460 CanEvaluateTruncated(Src, DestTy, *this, &CI)) {
Craig Topper3529aa52013-01-24 05:22:40 +0000461
Chris Lattner2b295a02010-01-04 07:53:58 +0000462 // If this cast is a truncate, evaluting in a different type always
Chris Lattner8600dd32010-01-05 23:00:30 +0000463 // eliminates the cast, so it is always a win.
Chris Lattner3057c372010-01-07 23:41:00 +0000464 DEBUG(dbgs() << "ICE: EvaluateInDifferentType converting expression type"
Dan Gohmana4abd032010-05-25 21:50:35 +0000465 " to avoid cast: " << CI << '\n');
Chris Lattner3057c372010-01-07 23:41:00 +0000466 Value *Res = EvaluateInDifferentType(Src, DestTy, false);
467 assert(Res->getType() == DestTy);
468 return ReplaceInstUsesWith(CI, Res);
469 }
Chris Lattner2b295a02010-01-04 07:53:58 +0000470
Chris Lattnera93c63c2010-01-05 22:21:18 +0000471 // Canonicalize trunc x to i1 -> (icmp ne (and x, 1), 0), likewise for vector.
472 if (DestTy->getScalarSizeInBits() == 1) {
Chris Lattner2b295a02010-01-04 07:53:58 +0000473 Constant *One = ConstantInt::get(Src->getType(), 1);
Benjamin Kramer547b6c52011-09-27 20:39:19 +0000474 Src = Builder->CreateAnd(Src, One);
Chris Lattner2b295a02010-01-04 07:53:58 +0000475 Value *Zero = Constant::getNullValue(Src->getType());
476 return new ICmpInst(ICmpInst::ICMP_NE, Src, Zero);
477 }
Craig Topper3529aa52013-01-24 05:22:40 +0000478
Chris Lattner90cd7462010-08-27 18:31:05 +0000479 // Transform trunc(lshr (zext A), Cst) to eliminate one type conversion.
Craig Topperf40110f2014-04-25 05:29:35 +0000480 Value *A = nullptr; ConstantInt *Cst = nullptr;
Chris Lattner9c10d582011-01-15 06:32:33 +0000481 if (Src->hasOneUse() &&
482 match(Src, m_LShr(m_ZExt(m_Value(A)), m_ConstantInt(Cst)))) {
Chris Lattner90cd7462010-08-27 18:31:05 +0000483 // We have three types to worry about here, the type of A, the source of
484 // the truncate (MidSize), and the destination of the truncate. We know that
485 // ASize < MidSize and MidSize > ResultSize, but don't know the relation
486 // between ASize and ResultSize.
487 unsigned ASize = A->getType()->getPrimitiveSizeInBits();
Craig Topper3529aa52013-01-24 05:22:40 +0000488
Chris Lattner90cd7462010-08-27 18:31:05 +0000489 // If the shift amount is larger than the size of A, then the result is
490 // known to be zero because all the input bits got shifted out.
491 if (Cst->getZExtValue() >= ASize)
492 return ReplaceInstUsesWith(CI, Constant::getNullValue(CI.getType()));
493
494 // Since we're doing an lshr and a zero extend, and know that the shift
495 // amount is smaller than ASize, it is always safe to do the shift in A's
496 // type, then zero extend or truncate to the result.
497 Value *Shift = Builder->CreateLShr(A, Cst->getZExtValue());
498 Shift->takeName(Src);
499 return CastInst::CreateIntegerCast(Shift, CI.getType(), false);
500 }
Craig Topper3529aa52013-01-24 05:22:40 +0000501
Jakub Kuderski7cd48102015-09-08 10:03:17 +0000502 // Transform trunc(lshr (sext A), Cst) to ashr A, Cst to eliminate type
503 // conversion.
504 // It works because bits coming from sign extension have the same value as
505 // sign bit of the original value; performing ashr instead of lshr
506 // generates bits of the same value as the sign bit.
507 if (Src->hasOneUse() &&
508 match(Src, m_LShr(m_SExt(m_Value(A)), m_ConstantInt(Cst))) &&
509 cast<Instruction>(Src)->getOperand(0)->hasOneUse()) {
510 const unsigned ASize = A->getType()->getPrimitiveSizeInBits();
511 // This optimization can be only performed when zero bits generated by
512 // the original lshr aren't pulled into the value after truncation, so we
513 // can only shift by values smaller then the size of destination type (in
514 // bits).
515 if (Cst->getValue().ult(ASize)) {
516 Value *Shift = Builder->CreateAShr(A, Cst->getZExtValue());
517 Shift->takeName(Src);
518 return CastInst::CreateIntegerCast(Shift, CI.getType(), false);
519 }
520 }
521
Chris Lattner9c10d582011-01-15 06:32:33 +0000522 // Transform "trunc (and X, cst)" -> "and (trunc X), cst" so long as the dest
523 // type isn't non-native.
524 if (Src->hasOneUse() && isa<IntegerType>(Src->getType()) &&
525 ShouldChangeType(Src->getType(), CI.getType()) &&
526 match(Src, m_And(m_Value(A), m_ConstantInt(Cst)))) {
527 Value *NewTrunc = Builder->CreateTrunc(A, CI.getType(), A->getName()+".tr");
528 return BinaryOperator::CreateAnd(NewTrunc,
529 ConstantExpr::getTrunc(Cst, CI.getType()));
530 }
Chris Lattner2b295a02010-01-04 07:53:58 +0000531
Craig Topperf40110f2014-04-25 05:29:35 +0000532 return nullptr;
Chris Lattner2b295a02010-01-04 07:53:58 +0000533}
534
535/// transformZExtICmp - Transform (zext icmp) to bitwise / integer operations
536/// in order to eliminate the icmp.
537Instruction *InstCombiner::transformZExtICmp(ICmpInst *ICI, Instruction &CI,
538 bool DoXform) {
539 // If we are just checking for a icmp eq of a single bit and zext'ing it
540 // to an integer, then shift the bit to the appropriate place and then
541 // cast to integer to avoid the comparison.
542 if (ConstantInt *Op1C = dyn_cast<ConstantInt>(ICI->getOperand(1))) {
543 const APInt &Op1CV = Op1C->getValue();
Craig Topper3529aa52013-01-24 05:22:40 +0000544
Chris Lattner2b295a02010-01-04 07:53:58 +0000545 // zext (x <s 0) to i32 --> x>>u31 true if signbit set.
546 // zext (x >s -1) to i32 --> (x>>u31)^1 true if signbit clear.
547 if ((ICI->getPredicate() == ICmpInst::ICMP_SLT && Op1CV == 0) ||
548 (ICI->getPredicate() == ICmpInst::ICMP_SGT &&Op1CV.isAllOnesValue())) {
549 if (!DoXform) return ICI;
550
551 Value *In = ICI->getOperand(0);
552 Value *Sh = ConstantInt::get(In->getType(),
553 In->getType()->getScalarSizeInBits()-1);
554 In = Builder->CreateLShr(In, Sh, In->getName()+".lobit");
555 if (In->getType() != CI.getType())
Benjamin Kramer547b6c52011-09-27 20:39:19 +0000556 In = Builder->CreateIntCast(In, CI.getType(), false/*ZExt*/);
Chris Lattner2b295a02010-01-04 07:53:58 +0000557
558 if (ICI->getPredicate() == ICmpInst::ICMP_SGT) {
559 Constant *One = ConstantInt::get(In->getType(), 1);
560 In = Builder->CreateXor(In, One, In->getName()+".not");
561 }
562
563 return ReplaceInstUsesWith(CI, In);
564 }
Chad Rosier385d9f62011-11-30 01:59:59 +0000565
Sylvestre Ledru91ce36c2012-09-27 10:14:43 +0000566 // zext (X == 0) to i32 --> X^1 iff X has only the low bit set.
567 // zext (X == 0) to i32 --> (X>>1)^1 iff X has only the 2nd bit set.
568 // zext (X == 1) to i32 --> X iff X has only the low bit set.
569 // zext (X == 2) to i32 --> X>>1 iff X has only the 2nd bit set.
570 // zext (X != 0) to i32 --> X iff X has only the low bit set.
571 // zext (X != 0) to i32 --> X>>1 iff X has only the 2nd bit set.
572 // zext (X != 1) to i32 --> X^1 iff X has only the low bit set.
573 // zext (X != 2) to i32 --> (X>>1)^1 iff X has only the 2nd bit set.
Craig Topper3529aa52013-01-24 05:22:40 +0000574 if ((Op1CV == 0 || Op1CV.isPowerOf2()) &&
Chris Lattner2b295a02010-01-04 07:53:58 +0000575 // This only works for EQ and NE
576 ICI->isEquality()) {
577 // If Op1C some other power of two, convert:
578 uint32_t BitWidth = Op1C->getType()->getBitWidth();
579 APInt KnownZero(BitWidth, 0), KnownOne(BitWidth, 0);
Hal Finkel60db0582014-09-07 18:57:58 +0000580 computeKnownBits(ICI->getOperand(0), KnownZero, KnownOne, 0, &CI);
Craig Topper3529aa52013-01-24 05:22:40 +0000581
Chris Lattner2b295a02010-01-04 07:53:58 +0000582 APInt KnownZeroMask(~KnownZero);
583 if (KnownZeroMask.isPowerOf2()) { // Exactly 1 possible 1?
584 if (!DoXform) return ICI;
585
586 bool isNE = ICI->getPredicate() == ICmpInst::ICMP_NE;
587 if (Op1CV != 0 && (Op1CV != KnownZeroMask)) {
588 // (X&4) == 2 --> false
589 // (X&4) != 2 --> true
590 Constant *Res = ConstantInt::get(Type::getInt1Ty(CI.getContext()),
591 isNE);
592 Res = ConstantExpr::getZExt(Res, CI.getType());
593 return ReplaceInstUsesWith(CI, Res);
594 }
Craig Topper3529aa52013-01-24 05:22:40 +0000595
Chris Lattner2b295a02010-01-04 07:53:58 +0000596 uint32_t ShiftAmt = KnownZeroMask.logBase2();
597 Value *In = ICI->getOperand(0);
598 if (ShiftAmt) {
599 // Perform a logical shr by shiftamt.
600 // Insert the shift to put the result in the low bit.
601 In = Builder->CreateLShr(In, ConstantInt::get(In->getType(),ShiftAmt),
602 In->getName()+".lobit");
603 }
Craig Topper3529aa52013-01-24 05:22:40 +0000604
Chris Lattner2b295a02010-01-04 07:53:58 +0000605 if ((Op1CV != 0) == isNE) { // Toggle the low bit.
606 Constant *One = ConstantInt::get(In->getType(), 1);
Benjamin Kramer547b6c52011-09-27 20:39:19 +0000607 In = Builder->CreateXor(In, One);
Chris Lattner2b295a02010-01-04 07:53:58 +0000608 }
Craig Topper3529aa52013-01-24 05:22:40 +0000609
Chris Lattner2b295a02010-01-04 07:53:58 +0000610 if (CI.getType() == In->getType())
611 return ReplaceInstUsesWith(CI, In);
Chris Lattner18d7fc82010-08-27 22:24:38 +0000612 return CastInst::CreateIntegerCast(In, CI.getType(), false/*ZExt*/);
Chris Lattner2b295a02010-01-04 07:53:58 +0000613 }
614 }
615 }
616
617 // icmp ne A, B is equal to xor A, B when A and B only really have one bit.
618 // It is also profitable to transform icmp eq into not(xor(A, B)) because that
619 // may lead to additional simplifications.
620 if (ICI->isEquality() && CI.getType() == ICI->getOperand(0)->getType()) {
Chris Lattner229907c2011-07-18 04:54:35 +0000621 if (IntegerType *ITy = dyn_cast<IntegerType>(CI.getType())) {
Chris Lattner2b295a02010-01-04 07:53:58 +0000622 uint32_t BitWidth = ITy->getBitWidth();
623 Value *LHS = ICI->getOperand(0);
624 Value *RHS = ICI->getOperand(1);
625
626 APInt KnownZeroLHS(BitWidth, 0), KnownOneLHS(BitWidth, 0);
627 APInt KnownZeroRHS(BitWidth, 0), KnownOneRHS(BitWidth, 0);
Hal Finkel60db0582014-09-07 18:57:58 +0000628 computeKnownBits(LHS, KnownZeroLHS, KnownOneLHS, 0, &CI);
629 computeKnownBits(RHS, KnownZeroRHS, KnownOneRHS, 0, &CI);
Chris Lattner2b295a02010-01-04 07:53:58 +0000630
631 if (KnownZeroLHS == KnownZeroRHS && KnownOneLHS == KnownOneRHS) {
632 APInt KnownBits = KnownZeroLHS | KnownOneLHS;
633 APInt UnknownBit = ~KnownBits;
634 if (UnknownBit.countPopulation() == 1) {
635 if (!DoXform) return ICI;
636
637 Value *Result = Builder->CreateXor(LHS, RHS);
638
639 // Mask off any bits that are set and won't be shifted away.
640 if (KnownOneLHS.uge(UnknownBit))
641 Result = Builder->CreateAnd(Result,
642 ConstantInt::get(ITy, UnknownBit));
643
644 // Shift the bit we're testing down to the lsb.
645 Result = Builder->CreateLShr(
646 Result, ConstantInt::get(ITy, UnknownBit.countTrailingZeros()));
647
648 if (ICI->getPredicate() == ICmpInst::ICMP_EQ)
649 Result = Builder->CreateXor(Result, ConstantInt::get(ITy, 1));
650 Result->takeName(ICI);
651 return ReplaceInstUsesWith(CI, Result);
652 }
653 }
654 }
655 }
656
Craig Topperf40110f2014-04-25 05:29:35 +0000657 return nullptr;
Chris Lattner2b295a02010-01-04 07:53:58 +0000658}
659
Chris Lattnerc3aca382010-01-10 00:58:42 +0000660/// CanEvaluateZExtd - Determine if the specified value can be computed in the
Chris Lattner172630a2010-01-11 02:43:35 +0000661/// specified wider type and produce the same low bits. If not, return false.
662///
Chris Lattner12bd8992010-01-11 03:32:00 +0000663/// If this function returns true, it can also return a non-zero number of bits
664/// (in BitsToClear) which indicates that the value it computes is correct for
665/// the zero extend, but that the additional BitsToClear bits need to be zero'd
666/// out. For example, to promote something like:
667///
668/// %B = trunc i64 %A to i32
669/// %C = lshr i32 %B, 8
670/// %E = zext i32 %C to i64
671///
672/// CanEvaluateZExtd for the 'lshr' will return true, and BitsToClear will be
673/// set to 8 to indicate that the promoted value needs to have bits 24-31
674/// cleared in addition to bits 32-63. Since an 'and' will be generated to
675/// clear the top bits anyway, doing this has no extra cost.
676///
Chris Lattner172630a2010-01-11 02:43:35 +0000677/// This function works on both vectors and scalars.
Hal Finkel60db0582014-09-07 18:57:58 +0000678static bool CanEvaluateZExtd(Value *V, Type *Ty, unsigned &BitsToClear,
679 InstCombiner &IC, Instruction *CxtI) {
Chris Lattner12bd8992010-01-11 03:32:00 +0000680 BitsToClear = 0;
Chris Lattnerb7be7cc2010-01-10 02:50:04 +0000681 if (isa<Constant>(V))
682 return true;
Craig Topper3529aa52013-01-24 05:22:40 +0000683
Chris Lattnerc3aca382010-01-10 00:58:42 +0000684 Instruction *I = dyn_cast<Instruction>(V);
Chris Lattnerb7be7cc2010-01-10 02:50:04 +0000685 if (!I) return false;
Craig Topper3529aa52013-01-24 05:22:40 +0000686
Chris Lattnerc3aca382010-01-10 00:58:42 +0000687 // If the input is a truncate from the destination type, we can trivially
Jakob Stoklund Olesenc5c4e962012-06-22 16:36:43 +0000688 // eliminate it.
689 if (isa<TruncInst>(I) && I->getOperand(0)->getType() == Ty)
Chris Lattnerb7be7cc2010-01-10 02:50:04 +0000690 return true;
Craig Topper3529aa52013-01-24 05:22:40 +0000691
Chris Lattnerc3aca382010-01-10 00:58:42 +0000692 // We can't extend or shrink something that has multiple uses: doing so would
693 // require duplicating the instruction in general, which isn't profitable.
Chris Lattnerb7be7cc2010-01-10 02:50:04 +0000694 if (!I->hasOneUse()) return false;
Craig Topper3529aa52013-01-24 05:22:40 +0000695
Chris Lattner12bd8992010-01-11 03:32:00 +0000696 unsigned Opc = I->getOpcode(), Tmp;
Chris Lattnerc3aca382010-01-10 00:58:42 +0000697 switch (Opc) {
Chris Lattner39d2daa2010-01-10 20:25:54 +0000698 case Instruction::ZExt: // zext(zext(x)) -> zext(x).
699 case Instruction::SExt: // zext(sext(x)) -> sext(x).
700 case Instruction::Trunc: // zext(trunc(x)) -> trunc(x) or zext(x)
701 return true;
Chris Lattnerc3aca382010-01-10 00:58:42 +0000702 case Instruction::And:
Chris Lattnerc3aca382010-01-10 00:58:42 +0000703 case Instruction::Or:
704 case Instruction::Xor:
Chris Lattnerc3aca382010-01-10 00:58:42 +0000705 case Instruction::Add:
706 case Instruction::Sub:
707 case Instruction::Mul:
Hal Finkel60db0582014-09-07 18:57:58 +0000708 if (!CanEvaluateZExtd(I->getOperand(0), Ty, BitsToClear, IC, CxtI) ||
709 !CanEvaluateZExtd(I->getOperand(1), Ty, Tmp, IC, CxtI))
Chris Lattner12bd8992010-01-11 03:32:00 +0000710 return false;
711 // These can all be promoted if neither operand has 'bits to clear'.
712 if (BitsToClear == 0 && Tmp == 0)
713 return true;
Craig Topper3529aa52013-01-24 05:22:40 +0000714
Chris Lattner0a854202010-01-11 04:05:13 +0000715 // If the operation is an AND/OR/XOR and the bits to clear are zero in the
716 // other side, BitsToClear is ok.
717 if (Tmp == 0 &&
718 (Opc == Instruction::And || Opc == Instruction::Or ||
719 Opc == Instruction::Xor)) {
720 // We use MaskedValueIsZero here for generality, but the case we care
721 // about the most is constant RHS.
722 unsigned VSize = V->getType()->getScalarSizeInBits();
Hal Finkel60db0582014-09-07 18:57:58 +0000723 if (IC.MaskedValueIsZero(I->getOperand(1),
724 APInt::getHighBitsSet(VSize, BitsToClear),
725 0, CxtI))
Chris Lattner0a854202010-01-11 04:05:13 +0000726 return true;
727 }
Craig Topper3529aa52013-01-24 05:22:40 +0000728
Chris Lattner0a854202010-01-11 04:05:13 +0000729 // Otherwise, we don't know how to analyze this BitsToClear case yet.
Chris Lattner12bd8992010-01-11 03:32:00 +0000730 return false;
Craig Topper3529aa52013-01-24 05:22:40 +0000731
Benjamin Kramer14e915f2013-05-10 16:26:37 +0000732 case Instruction::Shl:
733 // We can promote shl(x, cst) if we can promote x. Since shl overwrites the
734 // upper bits we can reduce BitsToClear by the shift amount.
735 if (ConstantInt *Amt = dyn_cast<ConstantInt>(I->getOperand(1))) {
Hal Finkel60db0582014-09-07 18:57:58 +0000736 if (!CanEvaluateZExtd(I->getOperand(0), Ty, BitsToClear, IC, CxtI))
Benjamin Kramer14e915f2013-05-10 16:26:37 +0000737 return false;
738 uint64_t ShiftAmt = Amt->getZExtValue();
739 BitsToClear = ShiftAmt < BitsToClear ? BitsToClear - ShiftAmt : 0;
740 return true;
741 }
742 return false;
Chris Lattner12bd8992010-01-11 03:32:00 +0000743 case Instruction::LShr:
744 // We can promote lshr(x, cst) if we can promote x. This requires the
745 // ultimate 'and' to clear out the high zero bits we're clearing out though.
746 if (ConstantInt *Amt = dyn_cast<ConstantInt>(I->getOperand(1))) {
Hal Finkel60db0582014-09-07 18:57:58 +0000747 if (!CanEvaluateZExtd(I->getOperand(0), Ty, BitsToClear, IC, CxtI))
Chris Lattner12bd8992010-01-11 03:32:00 +0000748 return false;
749 BitsToClear += Amt->getZExtValue();
750 if (BitsToClear > V->getType()->getScalarSizeInBits())
751 BitsToClear = V->getType()->getScalarSizeInBits();
752 return true;
753 }
754 // Cannot promote variable LSHR.
755 return false;
Chris Lattnerc3aca382010-01-10 00:58:42 +0000756 case Instruction::Select:
Hal Finkel60db0582014-09-07 18:57:58 +0000757 if (!CanEvaluateZExtd(I->getOperand(1), Ty, Tmp, IC, CxtI) ||
758 !CanEvaluateZExtd(I->getOperand(2), Ty, BitsToClear, IC, CxtI) ||
Chris Lattner0a854202010-01-11 04:05:13 +0000759 // TODO: If important, we could handle the case when the BitsToClear are
760 // known zero in the disagreeing side.
Chris Lattner12bd8992010-01-11 03:32:00 +0000761 Tmp != BitsToClear)
762 return false;
763 return true;
Craig Topper3529aa52013-01-24 05:22:40 +0000764
Chris Lattnerc3aca382010-01-10 00:58:42 +0000765 case Instruction::PHI: {
766 // We can change a phi if we can change all operands. Note that we never
767 // get into trouble with cyclic PHIs here because we only consider
768 // instructions with a single use.
769 PHINode *PN = cast<PHINode>(I);
Hal Finkel60db0582014-09-07 18:57:58 +0000770 if (!CanEvaluateZExtd(PN->getIncomingValue(0), Ty, BitsToClear, IC, CxtI))
Chris Lattner12bd8992010-01-11 03:32:00 +0000771 return false;
Chris Lattnerb7be7cc2010-01-10 02:50:04 +0000772 for (unsigned i = 1, e = PN->getNumIncomingValues(); i != e; ++i)
Hal Finkel60db0582014-09-07 18:57:58 +0000773 if (!CanEvaluateZExtd(PN->getIncomingValue(i), Ty, Tmp, IC, CxtI) ||
Chris Lattner0a854202010-01-11 04:05:13 +0000774 // TODO: If important, we could handle the case when the BitsToClear
775 // are known zero in the disagreeing input.
Chris Lattner12bd8992010-01-11 03:32:00 +0000776 Tmp != BitsToClear)
777 return false;
Chris Lattnerb7be7cc2010-01-10 02:50:04 +0000778 return true;
Chris Lattnerc3aca382010-01-10 00:58:42 +0000779 }
780 default:
781 // TODO: Can handle more cases here.
Chris Lattnerb7be7cc2010-01-10 02:50:04 +0000782 return false;
Chris Lattnerc3aca382010-01-10 00:58:42 +0000783 }
784}
785
Chris Lattner2b295a02010-01-04 07:53:58 +0000786Instruction *InstCombiner::visitZExt(ZExtInst &CI) {
Nick Lewycky80ea0032013-01-14 20:56:10 +0000787 // If this zero extend is only used by a truncate, let the truncate be
Chris Lattner49d2c972010-01-10 02:39:31 +0000788 // eliminated before we try to optimize this zext.
Chandler Carruthcdf47882014-03-09 03:16:01 +0000789 if (CI.hasOneUse() && isa<TruncInst>(CI.user_back()))
Craig Topperf40110f2014-04-25 05:29:35 +0000790 return nullptr;
Craig Topper3529aa52013-01-24 05:22:40 +0000791
Chris Lattner2b295a02010-01-04 07:53:58 +0000792 // If one of the common conversion will work, do it.
Chris Lattner883550a2010-01-10 01:00:46 +0000793 if (Instruction *Result = commonCastTransforms(CI))
Chris Lattner2b295a02010-01-04 07:53:58 +0000794 return Result;
795
Craig Topper3529aa52013-01-24 05:22:40 +0000796 // See if we can simplify any instructions used by the input whose sole
Chris Lattner883550a2010-01-10 01:00:46 +0000797 // purpose is to compute bits we don't care about.
798 if (SimplifyDemandedInstructionBits(CI))
799 return &CI;
Craig Topper3529aa52013-01-24 05:22:40 +0000800
Chris Lattner883550a2010-01-10 01:00:46 +0000801 Value *Src = CI.getOperand(0);
Chris Lattner229907c2011-07-18 04:54:35 +0000802 Type *SrcTy = Src->getType(), *DestTy = CI.getType();
Craig Topper3529aa52013-01-24 05:22:40 +0000803
Chris Lattnerc3aca382010-01-10 00:58:42 +0000804 // Attempt to extend the entire input expression tree to the destination
805 // type. Only do this if the dest type is a simple type, don't convert the
806 // expression tree to something weird like i93 unless the source is also
807 // strange.
Chris Lattner12bd8992010-01-11 03:32:00 +0000808 unsigned BitsToClear;
Duncan Sands19d0b472010-02-16 11:11:14 +0000809 if ((DestTy->isVectorTy() || ShouldChangeType(SrcTy, DestTy)) &&
Hal Finkel60db0582014-09-07 18:57:58 +0000810 CanEvaluateZExtd(Src, DestTy, BitsToClear, *this, &CI)) {
Chris Lattner12bd8992010-01-11 03:32:00 +0000811 assert(BitsToClear < SrcTy->getScalarSizeInBits() &&
812 "Unreasonable BitsToClear");
Craig Topper3529aa52013-01-24 05:22:40 +0000813
Chris Lattner49d2c972010-01-10 02:39:31 +0000814 // Okay, we can transform this! Insert the new expression now.
815 DEBUG(dbgs() << "ICE: EvaluateInDifferentType converting expression type"
816 " to avoid zero extend: " << CI);
817 Value *Res = EvaluateInDifferentType(Src, DestTy, false);
818 assert(Res->getType() == DestTy);
Craig Topper3529aa52013-01-24 05:22:40 +0000819
Chris Lattner12bd8992010-01-11 03:32:00 +0000820 uint32_t SrcBitsKept = SrcTy->getScalarSizeInBits()-BitsToClear;
821 uint32_t DestBitSize = DestTy->getScalarSizeInBits();
Craig Topper3529aa52013-01-24 05:22:40 +0000822
Chris Lattner49d2c972010-01-10 02:39:31 +0000823 // If the high bits are already filled with zeros, just replace this
824 // cast with the result.
Hal Finkel60db0582014-09-07 18:57:58 +0000825 if (MaskedValueIsZero(Res,
826 APInt::getHighBitsSet(DestBitSize,
827 DestBitSize-SrcBitsKept),
828 0, &CI))
Chris Lattner49d2c972010-01-10 02:39:31 +0000829 return ReplaceInstUsesWith(CI, Res);
Craig Topper3529aa52013-01-24 05:22:40 +0000830
Chris Lattner49d2c972010-01-10 02:39:31 +0000831 // We need to emit an AND to clear the high bits.
Chris Lattner39d2daa2010-01-10 20:25:54 +0000832 Constant *C = ConstantInt::get(Res->getType(),
Chris Lattner12bd8992010-01-11 03:32:00 +0000833 APInt::getLowBitsSet(DestBitSize, SrcBitsKept));
Chris Lattner49d2c972010-01-10 02:39:31 +0000834 return BinaryOperator::CreateAnd(Res, C);
Chris Lattnerc3aca382010-01-10 00:58:42 +0000835 }
Chris Lattner2b295a02010-01-04 07:53:58 +0000836
837 // If this is a TRUNC followed by a ZEXT then we are dealing with integral
838 // types and if the sizes are just right we can convert this into a logical
839 // 'and' which will be much cheaper than the pair of casts.
840 if (TruncInst *CSrc = dyn_cast<TruncInst>(Src)) { // A->B->C cast
Chris Lattnerd8509422010-01-10 07:08:30 +0000841 // TODO: Subsume this into EvaluateInDifferentType.
Craig Topper3529aa52013-01-24 05:22:40 +0000842
Chris Lattner2b295a02010-01-04 07:53:58 +0000843 // Get the sizes of the types involved. We know that the intermediate type
844 // will be smaller than A or C, but don't know the relation between A and C.
845 Value *A = CSrc->getOperand(0);
846 unsigned SrcSize = A->getType()->getScalarSizeInBits();
847 unsigned MidSize = CSrc->getType()->getScalarSizeInBits();
848 unsigned DstSize = CI.getType()->getScalarSizeInBits();
849 // If we're actually extending zero bits, then if
850 // SrcSize < DstSize: zext(a & mask)
851 // SrcSize == DstSize: a & mask
852 // SrcSize > DstSize: trunc(a) & mask
853 if (SrcSize < DstSize) {
854 APInt AndValue(APInt::getLowBitsSet(SrcSize, MidSize));
855 Constant *AndConst = ConstantInt::get(A->getType(), AndValue);
856 Value *And = Builder->CreateAnd(A, AndConst, CSrc->getName()+".mask");
857 return new ZExtInst(And, CI.getType());
858 }
Craig Topper3529aa52013-01-24 05:22:40 +0000859
Chris Lattner2b295a02010-01-04 07:53:58 +0000860 if (SrcSize == DstSize) {
861 APInt AndValue(APInt::getLowBitsSet(SrcSize, MidSize));
862 return BinaryOperator::CreateAnd(A, ConstantInt::get(A->getType(),
863 AndValue));
864 }
865 if (SrcSize > DstSize) {
Benjamin Kramer547b6c52011-09-27 20:39:19 +0000866 Value *Trunc = Builder->CreateTrunc(A, CI.getType());
Chris Lattner2b295a02010-01-04 07:53:58 +0000867 APInt AndValue(APInt::getLowBitsSet(DstSize, MidSize));
Craig Topper3529aa52013-01-24 05:22:40 +0000868 return BinaryOperator::CreateAnd(Trunc,
Chris Lattner2b295a02010-01-04 07:53:58 +0000869 ConstantInt::get(Trunc->getType(),
Chris Lattnerd8509422010-01-10 07:08:30 +0000870 AndValue));
Chris Lattner2b295a02010-01-04 07:53:58 +0000871 }
872 }
873
874 if (ICmpInst *ICI = dyn_cast<ICmpInst>(Src))
875 return transformZExtICmp(ICI, CI);
876
877 BinaryOperator *SrcI = dyn_cast<BinaryOperator>(Src);
878 if (SrcI && SrcI->getOpcode() == Instruction::Or) {
879 // zext (or icmp, icmp) --> or (zext icmp), (zext icmp) if at least one
880 // of the (zext icmp) will be transformed.
881 ICmpInst *LHS = dyn_cast<ICmpInst>(SrcI->getOperand(0));
882 ICmpInst *RHS = dyn_cast<ICmpInst>(SrcI->getOperand(1));
883 if (LHS && RHS && LHS->hasOneUse() && RHS->hasOneUse() &&
884 (transformZExtICmp(LHS, CI, false) ||
885 transformZExtICmp(RHS, CI, false))) {
886 Value *LCast = Builder->CreateZExt(LHS, CI.getType(), LHS->getName());
887 Value *RCast = Builder->CreateZExt(RHS, CI.getType(), RHS->getName());
888 return BinaryOperator::Create(Instruction::Or, LCast, RCast);
889 }
890 }
891
Benjamin Kramerb80e1692014-01-19 20:05:13 +0000892 // zext(trunc(X) & C) -> (X & zext(C)).
893 Constant *C;
894 Value *X;
895 if (SrcI &&
896 match(SrcI, m_OneUse(m_And(m_Trunc(m_Value(X)), m_Constant(C)))) &&
897 X->getType() == CI.getType())
898 return BinaryOperator::CreateAnd(X, ConstantExpr::getZExt(C, CI.getType()));
Chris Lattner2b295a02010-01-04 07:53:58 +0000899
Benjamin Kramerb80e1692014-01-19 20:05:13 +0000900 // zext((trunc(X) & C) ^ C) -> ((X & zext(C)) ^ zext(C)).
901 Value *And;
902 if (SrcI && match(SrcI, m_OneUse(m_Xor(m_Value(And), m_Constant(C)))) &&
903 match(And, m_OneUse(m_And(m_Trunc(m_Value(X)), m_Specific(C)))) &&
904 X->getType() == CI.getType()) {
905 Constant *ZC = ConstantExpr::getZExt(C, CI.getType());
906 return BinaryOperator::CreateXor(Builder->CreateAnd(X, ZC), ZC);
907 }
Chris Lattner2b295a02010-01-04 07:53:58 +0000908
Chris Lattnerfd7e42b2010-01-05 21:04:47 +0000909 // zext (xor i1 X, true) to i32 --> xor (zext i1 X to i32), 1
Benjamin Kramerb80e1692014-01-19 20:05:13 +0000910 if (SrcI && SrcI->hasOneUse() &&
911 SrcI->getType()->getScalarType()->isIntegerTy(1) &&
912 match(SrcI, m_Not(m_Value(X))) && (!X->hasOneUse() || !isa<CmpInst>(X))) {
Chris Lattnerfd7e42b2010-01-05 21:04:47 +0000913 Value *New = Builder->CreateZExt(X, CI.getType());
914 return BinaryOperator::CreateXor(New, ConstantInt::get(CI.getType(), 1));
915 }
Craig Topper3529aa52013-01-24 05:22:40 +0000916
Craig Topperf40110f2014-04-25 05:29:35 +0000917 return nullptr;
Chris Lattner2b295a02010-01-04 07:53:58 +0000918}
919
Benjamin Kramer398b8c52011-04-01 20:09:03 +0000920/// transformSExtICmp - Transform (sext icmp) to bitwise / integer operations
921/// in order to eliminate the icmp.
922Instruction *InstCombiner::transformSExtICmp(ICmpInst *ICI, Instruction &CI) {
923 Value *Op0 = ICI->getOperand(0), *Op1 = ICI->getOperand(1);
924 ICmpInst::Predicate Pred = ICI->getPredicate();
925
David Majnemerc8bdd232014-10-27 05:47:49 +0000926 // Don't bother if Op1 isn't of vector or integer type.
927 if (!Op1->getType()->isIntOrIntVectorTy())
928 return nullptr;
929
Benjamin Kramerb80e1692014-01-19 20:05:13 +0000930 if (Constant *Op1C = dyn_cast<Constant>(Op1)) {
Benjamin Kramer8b94c292011-04-01 22:29:18 +0000931 // (x <s 0) ? -1 : 0 -> ashr x, 31 -> all ones if negative
932 // (x >s -1) ? -1 : 0 -> not (ashr x, 31) -> all ones if positive
Benjamin Kramerb80e1692014-01-19 20:05:13 +0000933 if ((Pred == ICmpInst::ICMP_SLT && Op1C->isNullValue()) ||
Benjamin Kramer398b8c52011-04-01 20:09:03 +0000934 (Pred == ICmpInst::ICMP_SGT && Op1C->isAllOnesValue())) {
935
936 Value *Sh = ConstantInt::get(Op0->getType(),
937 Op0->getType()->getScalarSizeInBits()-1);
938 Value *In = Builder->CreateAShr(Op0, Sh, Op0->getName()+".lobit");
939 if (In->getType() != CI.getType())
Benjamin Kramer547b6c52011-09-27 20:39:19 +0000940 In = Builder->CreateIntCast(In, CI.getType(), true/*SExt*/);
Benjamin Kramer398b8c52011-04-01 20:09:03 +0000941
942 if (Pred == ICmpInst::ICMP_SGT)
943 In = Builder->CreateNot(In, In->getName()+".not");
944 return ReplaceInstUsesWith(CI, In);
945 }
Benjamin Kramerb80e1692014-01-19 20:05:13 +0000946 }
Benjamin Kramerd1217652011-04-01 20:09:10 +0000947
Benjamin Kramerb80e1692014-01-19 20:05:13 +0000948 if (ConstantInt *Op1C = dyn_cast<ConstantInt>(Op1)) {
Benjamin Kramerd1217652011-04-01 20:09:10 +0000949 // If we know that only one bit of the LHS of the icmp can be set and we
950 // have an equality comparison with zero or a power of 2, we can transform
951 // the icmp and sext into bitwise/integer operations.
Benjamin Kramer5cad4532011-04-01 22:22:11 +0000952 if (ICI->hasOneUse() &&
953 ICI->isEquality() && (Op1C->isZero() || Op1C->getValue().isPowerOf2())){
Benjamin Kramerd1217652011-04-01 20:09:10 +0000954 unsigned BitWidth = Op1C->getType()->getBitWidth();
955 APInt KnownZero(BitWidth, 0), KnownOne(BitWidth, 0);
Hal Finkel60db0582014-09-07 18:57:58 +0000956 computeKnownBits(Op0, KnownZero, KnownOne, 0, &CI);
Benjamin Kramerd1217652011-04-01 20:09:10 +0000957
Benjamin Kramerac2d5652011-04-01 20:15:16 +0000958 APInt KnownZeroMask(~KnownZero);
959 if (KnownZeroMask.isPowerOf2()) {
Benjamin Kramerd1217652011-04-01 20:09:10 +0000960 Value *In = ICI->getOperand(0);
961
Benjamin Kramer50a281a2011-04-02 18:50:58 +0000962 // If the icmp tests for a known zero bit we can constant fold it.
963 if (!Op1C->isZero() && Op1C->getValue() != KnownZeroMask) {
964 Value *V = Pred == ICmpInst::ICMP_NE ?
965 ConstantInt::getAllOnesValue(CI.getType()) :
966 ConstantInt::getNullValue(CI.getType());
967 return ReplaceInstUsesWith(CI, V);
968 }
Benjamin Kramer5cad4532011-04-01 22:22:11 +0000969
Benjamin Kramerd1217652011-04-01 20:09:10 +0000970 if (!Op1C->isZero() == (Pred == ICmpInst::ICMP_NE)) {
971 // sext ((x & 2^n) == 0) -> (x >> n) - 1
972 // sext ((x & 2^n) != 2^n) -> (x >> n) - 1
973 unsigned ShiftAmt = KnownZeroMask.countTrailingZeros();
974 // Perform a right shift to place the desired bit in the LSB.
975 if (ShiftAmt)
976 In = Builder->CreateLShr(In,
977 ConstantInt::get(In->getType(), ShiftAmt));
978
979 // At this point "In" is either 1 or 0. Subtract 1 to turn
980 // {1, 0} -> {0, -1}.
981 In = Builder->CreateAdd(In,
982 ConstantInt::getAllOnesValue(In->getType()),
983 "sext");
984 } else {
985 // sext ((x & 2^n) != 0) -> (x << bitwidth-n) a>> bitwidth-1
Benjamin Kramer5cad4532011-04-01 22:22:11 +0000986 // sext ((x & 2^n) == 2^n) -> (x << bitwidth-n) a>> bitwidth-1
Benjamin Kramerd1217652011-04-01 20:09:10 +0000987 unsigned ShiftAmt = KnownZeroMask.countLeadingZeros();
988 // Perform a left shift to place the desired bit in the MSB.
989 if (ShiftAmt)
990 In = Builder->CreateShl(In,
991 ConstantInt::get(In->getType(), ShiftAmt));
992
993 // Distribute the bit over the whole bit width.
994 In = Builder->CreateAShr(In, ConstantInt::get(In->getType(),
995 BitWidth - 1), "sext");
996 }
997
998 if (CI.getType() == In->getType())
999 return ReplaceInstUsesWith(CI, In);
1000 return CastInst::CreateIntegerCast(In, CI.getType(), true/*SExt*/);
1001 }
1002 }
Benjamin Kramer398b8c52011-04-01 20:09:03 +00001003 }
1004
Craig Topperf40110f2014-04-25 05:29:35 +00001005 return nullptr;
Benjamin Kramer398b8c52011-04-01 20:09:03 +00001006}
1007
Chris Lattnerc3aca382010-01-10 00:58:42 +00001008/// CanEvaluateSExtd - Return true if we can take the specified value
1009/// and return it as type Ty without inserting any new casts and without
1010/// changing the value of the common low bits. This is used by code that tries
1011/// to promote integer operations to a wider types will allow us to eliminate
1012/// the extension.
1013///
Chris Lattner1a05fdd2010-01-10 07:57:20 +00001014/// This function works on both vectors and scalars.
Chris Lattnerc3aca382010-01-10 00:58:42 +00001015///
Chris Lattner229907c2011-07-18 04:54:35 +00001016static bool CanEvaluateSExtd(Value *V, Type *Ty) {
Chris Lattnerc3aca382010-01-10 00:58:42 +00001017 assert(V->getType()->getScalarSizeInBits() < Ty->getScalarSizeInBits() &&
1018 "Can't sign extend type to a smaller type");
Chris Lattner1a05fdd2010-01-10 07:57:20 +00001019 // If this is a constant, it can be trivially promoted.
1020 if (isa<Constant>(V))
1021 return true;
Craig Topper3529aa52013-01-24 05:22:40 +00001022
Chris Lattnerc3aca382010-01-10 00:58:42 +00001023 Instruction *I = dyn_cast<Instruction>(V);
Chris Lattner1a05fdd2010-01-10 07:57:20 +00001024 if (!I) return false;
Craig Topper3529aa52013-01-24 05:22:40 +00001025
Jakob Stoklund Olesenc5c4e962012-06-22 16:36:43 +00001026 // If this is a truncate from the dest type, we can trivially eliminate it.
1027 if (isa<TruncInst>(I) && I->getOperand(0)->getType() == Ty)
Chris Lattner1a05fdd2010-01-10 07:57:20 +00001028 return true;
Craig Topper3529aa52013-01-24 05:22:40 +00001029
Chris Lattnerc3aca382010-01-10 00:58:42 +00001030 // We can't extend or shrink something that has multiple uses: doing so would
1031 // require duplicating the instruction in general, which isn't profitable.
Chris Lattner1a05fdd2010-01-10 07:57:20 +00001032 if (!I->hasOneUse()) return false;
Chris Lattnerc3aca382010-01-10 00:58:42 +00001033
Chris Lattner1a05fdd2010-01-10 07:57:20 +00001034 switch (I->getOpcode()) {
Chris Lattner7dd540e2010-01-10 20:30:41 +00001035 case Instruction::SExt: // sext(sext(x)) -> sext(x)
1036 case Instruction::ZExt: // sext(zext(x)) -> zext(x)
1037 case Instruction::Trunc: // sext(trunc(x)) -> trunc(x) or sext(x)
1038 return true;
Chris Lattnerc3aca382010-01-10 00:58:42 +00001039 case Instruction::And:
1040 case Instruction::Or:
1041 case Instruction::Xor:
Chris Lattnerc3aca382010-01-10 00:58:42 +00001042 case Instruction::Add:
1043 case Instruction::Sub:
Chris Lattnerc3aca382010-01-10 00:58:42 +00001044 case Instruction::Mul:
Chris Lattner1a05fdd2010-01-10 07:57:20 +00001045 // These operators can all arbitrarily be extended if their inputs can.
Chris Lattner172630a2010-01-11 02:43:35 +00001046 return CanEvaluateSExtd(I->getOperand(0), Ty) &&
1047 CanEvaluateSExtd(I->getOperand(1), Ty);
Craig Topper3529aa52013-01-24 05:22:40 +00001048
Chris Lattnerc3aca382010-01-10 00:58:42 +00001049 //case Instruction::Shl: TODO
1050 //case Instruction::LShr: TODO
Craig Topper3529aa52013-01-24 05:22:40 +00001051
Chris Lattner1a05fdd2010-01-10 07:57:20 +00001052 case Instruction::Select:
Chris Lattner172630a2010-01-11 02:43:35 +00001053 return CanEvaluateSExtd(I->getOperand(1), Ty) &&
1054 CanEvaluateSExtd(I->getOperand(2), Ty);
Craig Topper3529aa52013-01-24 05:22:40 +00001055
Chris Lattnerc3aca382010-01-10 00:58:42 +00001056 case Instruction::PHI: {
1057 // We can change a phi if we can change all operands. Note that we never
1058 // get into trouble with cyclic PHIs here because we only consider
1059 // instructions with a single use.
1060 PHINode *PN = cast<PHINode>(I);
Pete Cooper833f34d2015-05-12 20:05:31 +00001061 for (Value *IncValue : PN->incoming_values())
1062 if (!CanEvaluateSExtd(IncValue, Ty)) return false;
Chris Lattner1a05fdd2010-01-10 07:57:20 +00001063 return true;
Chris Lattnerc3aca382010-01-10 00:58:42 +00001064 }
1065 default:
1066 // TODO: Can handle more cases here.
1067 break;
1068 }
Craig Topper3529aa52013-01-24 05:22:40 +00001069
Chris Lattner1a05fdd2010-01-10 07:57:20 +00001070 return false;
Chris Lattnerc3aca382010-01-10 00:58:42 +00001071}
1072
Chris Lattner2b295a02010-01-04 07:53:58 +00001073Instruction *InstCombiner::visitSExt(SExtInst &CI) {
Arnaud A. de Grandmaison2e4df4f2013-02-13 00:19:19 +00001074 // If this sign extend is only used by a truncate, let the truncate be
1075 // eliminated before we try to optimize this sext.
Chandler Carruthcdf47882014-03-09 03:16:01 +00001076 if (CI.hasOneUse() && isa<TruncInst>(CI.user_back()))
Craig Topperf40110f2014-04-25 05:29:35 +00001077 return nullptr;
Craig Topper3529aa52013-01-24 05:22:40 +00001078
Chris Lattner883550a2010-01-10 01:00:46 +00001079 if (Instruction *I = commonCastTransforms(CI))
Chris Lattner2b295a02010-01-04 07:53:58 +00001080 return I;
Craig Topper3529aa52013-01-24 05:22:40 +00001081
1082 // See if we can simplify any instructions used by the input whose sole
Chris Lattner883550a2010-01-10 01:00:46 +00001083 // purpose is to compute bits we don't care about.
1084 if (SimplifyDemandedInstructionBits(CI))
1085 return &CI;
Craig Topper3529aa52013-01-24 05:22:40 +00001086
Chris Lattner2b295a02010-01-04 07:53:58 +00001087 Value *Src = CI.getOperand(0);
Chris Lattner229907c2011-07-18 04:54:35 +00001088 Type *SrcTy = Src->getType(), *DestTy = CI.getType();
Chris Lattnerc3aca382010-01-10 00:58:42 +00001089
Philip Reames9ae15202015-02-14 00:05:36 +00001090 // If we know that the value being extended is positive, we can use a zext
1091 // instead.
1092 bool KnownZero, KnownOne;
1093 ComputeSignBit(Src, KnownZero, KnownOne, 0, &CI);
1094 if (KnownZero) {
1095 Value *ZExt = Builder->CreateZExt(Src, DestTy);
1096 return ReplaceInstUsesWith(CI, ZExt);
1097 }
1098
Chris Lattnerc3aca382010-01-10 00:58:42 +00001099 // Attempt to extend the entire input expression tree to the destination
1100 // type. Only do this if the dest type is a simple type, don't convert the
1101 // expression tree to something weird like i93 unless the source is also
1102 // strange.
Duncan Sands19d0b472010-02-16 11:11:14 +00001103 if ((DestTy->isVectorTy() || ShouldChangeType(SrcTy, DestTy)) &&
Chris Lattner172630a2010-01-11 02:43:35 +00001104 CanEvaluateSExtd(Src, DestTy)) {
Chris Lattner2fff10c2010-01-10 07:40:50 +00001105 // Okay, we can transform this! Insert the new expression now.
1106 DEBUG(dbgs() << "ICE: EvaluateInDifferentType converting expression type"
1107 " to avoid sign extend: " << CI);
1108 Value *Res = EvaluateInDifferentType(Src, DestTy, true);
1109 assert(Res->getType() == DestTy);
1110
Chris Lattnerc3aca382010-01-10 00:58:42 +00001111 uint32_t SrcBitSize = SrcTy->getScalarSizeInBits();
1112 uint32_t DestBitSize = DestTy->getScalarSizeInBits();
Chris Lattner2fff10c2010-01-10 07:40:50 +00001113
1114 // If the high bits are already filled with sign bit, just replace this
1115 // cast with the result.
Hal Finkel60db0582014-09-07 18:57:58 +00001116 if (ComputeNumSignBits(Res, 0, &CI) > DestBitSize - SrcBitSize)
Chris Lattner2fff10c2010-01-10 07:40:50 +00001117 return ReplaceInstUsesWith(CI, Res);
Craig Topper3529aa52013-01-24 05:22:40 +00001118
Chris Lattner2fff10c2010-01-10 07:40:50 +00001119 // We need to emit a shl + ashr to do the sign extend.
1120 Value *ShAmt = ConstantInt::get(DestTy, DestBitSize-SrcBitSize);
1121 return BinaryOperator::CreateAShr(Builder->CreateShl(Res, ShAmt, "sext"),
1122 ShAmt);
Chris Lattnerc3aca382010-01-10 00:58:42 +00001123 }
Chris Lattner2b295a02010-01-04 07:53:58 +00001124
Chris Lattner43f2fa62010-01-18 22:19:16 +00001125 // If this input is a trunc from our destination, then turn sext(trunc(x))
1126 // into shifts.
1127 if (TruncInst *TI = dyn_cast<TruncInst>(Src))
1128 if (TI->hasOneUse() && TI->getOperand(0)->getType() == DestTy) {
1129 uint32_t SrcBitSize = SrcTy->getScalarSizeInBits();
1130 uint32_t DestBitSize = DestTy->getScalarSizeInBits();
Craig Topper3529aa52013-01-24 05:22:40 +00001131
Chris Lattner43f2fa62010-01-18 22:19:16 +00001132 // We need to emit a shl + ashr to do the sign extend.
1133 Value *ShAmt = ConstantInt::get(DestTy, DestBitSize-SrcBitSize);
1134 Value *Res = Builder->CreateShl(TI->getOperand(0), ShAmt, "sext");
1135 return BinaryOperator::CreateAShr(Res, ShAmt);
1136 }
Nate Begeman7aa18bf2010-12-17 23:12:19 +00001137
Benjamin Kramer398b8c52011-04-01 20:09:03 +00001138 if (ICmpInst *ICI = dyn_cast<ICmpInst>(Src))
1139 return transformSExtICmp(ICI, CI);
Bill Wendling5e360552010-12-17 23:27:41 +00001140
Chris Lattner2b295a02010-01-04 07:53:58 +00001141 // If the input is a shl/ashr pair of a same constant, then this is a sign
1142 // extension from a smaller value. If we could trust arbitrary bitwidth
1143 // integers, we could turn this into a truncate to the smaller bit and then
1144 // use a sext for the whole extension. Since we don't, look deeper and check
1145 // for a truncate. If the source and dest are the same type, eliminate the
1146 // trunc and extend and just do shifts. For example, turn:
1147 // %a = trunc i32 %i to i8
1148 // %b = shl i8 %a, 6
1149 // %c = ashr i8 %b, 6
1150 // %d = sext i8 %c to i32
1151 // into:
1152 // %a = shl i32 %i, 30
1153 // %d = ashr i32 %a, 30
Craig Topperf40110f2014-04-25 05:29:35 +00001154 Value *A = nullptr;
Chris Lattnerc95a7a22010-01-10 01:04:31 +00001155 // TODO: Eventually this could be subsumed by EvaluateInDifferentType.
Craig Topperf40110f2014-04-25 05:29:35 +00001156 ConstantInt *BA = nullptr, *CA = nullptr;
Chris Lattnerc95a7a22010-01-10 01:04:31 +00001157 if (match(Src, m_AShr(m_Shl(m_Trunc(m_Value(A)), m_ConstantInt(BA)),
Chris Lattner2b295a02010-01-04 07:53:58 +00001158 m_ConstantInt(CA))) &&
Chris Lattnerc95a7a22010-01-10 01:04:31 +00001159 BA == CA && A->getType() == CI.getType()) {
1160 unsigned MidSize = Src->getType()->getScalarSizeInBits();
1161 unsigned SrcDstSize = CI.getType()->getScalarSizeInBits();
1162 unsigned ShAmt = CA->getZExtValue()+SrcDstSize-MidSize;
1163 Constant *ShAmtV = ConstantInt::get(CI.getType(), ShAmt);
1164 A = Builder->CreateShl(A, ShAmtV, CI.getName());
1165 return BinaryOperator::CreateAShr(A, ShAmtV);
Chris Lattner2b295a02010-01-04 07:53:58 +00001166 }
Craig Topper3529aa52013-01-24 05:22:40 +00001167
Craig Topperf40110f2014-04-25 05:29:35 +00001168 return nullptr;
Chris Lattner2b295a02010-01-04 07:53:58 +00001169}
1170
1171
1172/// FitsInFPType - Return a Constant* for the specified FP constant if it fits
1173/// in the specified FP type without changing its value.
1174static Constant *FitsInFPType(ConstantFP *CFP, const fltSemantics &Sem) {
1175 bool losesInfo;
1176 APFloat F = CFP->getValueAPF();
1177 (void)F.convert(Sem, APFloat::rmNearestTiesToEven, &losesInfo);
1178 if (!losesInfo)
1179 return ConstantFP::get(CFP->getContext(), F);
Craig Topperf40110f2014-04-25 05:29:35 +00001180 return nullptr;
Chris Lattner2b295a02010-01-04 07:53:58 +00001181}
1182
1183/// LookThroughFPExtensions - If this is an fp extension instruction, look
1184/// through it until we get the source value.
1185static Value *LookThroughFPExtensions(Value *V) {
1186 if (Instruction *I = dyn_cast<Instruction>(V))
1187 if (I->getOpcode() == Instruction::FPExt)
1188 return LookThroughFPExtensions(I->getOperand(0));
Craig Topper3529aa52013-01-24 05:22:40 +00001189
Chris Lattner2b295a02010-01-04 07:53:58 +00001190 // If this value is a constant, return the constant in the smallest FP type
1191 // that can accurately represent it. This allows us to turn
1192 // (float)((double)X+2.0) into x+2.0f.
1193 if (ConstantFP *CFP = dyn_cast<ConstantFP>(V)) {
1194 if (CFP->getType() == Type::getPPC_FP128Ty(V->getContext()))
1195 return V; // No constant folding of this.
Dan Gohman518cda42011-12-17 00:04:22 +00001196 // See if the value can be truncated to half and then reextended.
1197 if (Value *V = FitsInFPType(CFP, APFloat::IEEEhalf))
1198 return V;
Chris Lattner2b295a02010-01-04 07:53:58 +00001199 // See if the value can be truncated to float and then reextended.
1200 if (Value *V = FitsInFPType(CFP, APFloat::IEEEsingle))
1201 return V;
Benjamin Kramerccce8ba2010-01-05 13:12:22 +00001202 if (CFP->getType()->isDoubleTy())
Chris Lattner2b295a02010-01-04 07:53:58 +00001203 return V; // Won't shrink.
1204 if (Value *V = FitsInFPType(CFP, APFloat::IEEEdouble))
1205 return V;
1206 // Don't try to shrink to various long double types.
1207 }
Craig Topper3529aa52013-01-24 05:22:40 +00001208
Chris Lattner2b295a02010-01-04 07:53:58 +00001209 return V;
1210}
1211
1212Instruction *InstCombiner::visitFPTrunc(FPTruncInst &CI) {
1213 if (Instruction *I = commonCastTransforms(CI))
1214 return I;
Stephen Canonc4549642013-11-28 21:38:05 +00001215 // If we have fptrunc(OpI (fpextend x), (fpextend y)), we would like to
1216 // simpilify this expression to avoid one or more of the trunc/extend
1217 // operations if we can do so without changing the numerical results.
1218 //
1219 // The exact manner in which the widths of the operands interact to limit
1220 // what we can and cannot do safely varies from operation to operation, and
1221 // is explained below in the various case statements.
Chris Lattner2b295a02010-01-04 07:53:58 +00001222 BinaryOperator *OpI = dyn_cast<BinaryOperator>(CI.getOperand(0));
1223 if (OpI && OpI->hasOneUse()) {
Stephen Canonc4549642013-11-28 21:38:05 +00001224 Value *LHSOrig = LookThroughFPExtensions(OpI->getOperand(0));
1225 Value *RHSOrig = LookThroughFPExtensions(OpI->getOperand(1));
1226 unsigned OpWidth = OpI->getType()->getFPMantissaWidth();
1227 unsigned LHSWidth = LHSOrig->getType()->getFPMantissaWidth();
1228 unsigned RHSWidth = RHSOrig->getType()->getFPMantissaWidth();
1229 unsigned SrcWidth = std::max(LHSWidth, RHSWidth);
1230 unsigned DstWidth = CI.getType()->getFPMantissaWidth();
Chris Lattner2b295a02010-01-04 07:53:58 +00001231 switch (OpI->getOpcode()) {
Stephen Canonc4549642013-11-28 21:38:05 +00001232 default: break;
1233 case Instruction::FAdd:
1234 case Instruction::FSub:
1235 // For addition and subtraction, the infinitely precise result can
1236 // essentially be arbitrarily wide; proving that double rounding
1237 // will not occur because the result of OpI is exact (as we will for
1238 // FMul, for example) is hopeless. However, we *can* nonetheless
1239 // frequently know that double rounding cannot occur (or that it is
Alp Tokercb402912014-01-24 17:20:08 +00001240 // innocuous) by taking advantage of the specific structure of
Stephen Canonc4549642013-11-28 21:38:05 +00001241 // infinitely-precise results that admit double rounding.
1242 //
Alp Tokercb402912014-01-24 17:20:08 +00001243 // Specifically, if OpWidth >= 2*DstWdith+1 and DstWidth is sufficient
Stephen Canonc4549642013-11-28 21:38:05 +00001244 // to represent both sources, we can guarantee that the double
1245 // rounding is innocuous (See p50 of Figueroa's 2000 PhD thesis,
1246 // "A Rigorous Framework for Fully Supporting the IEEE Standard ..."
1247 // for proof of this fact).
1248 //
1249 // Note: Figueroa does not consider the case where DstFormat !=
1250 // SrcFormat. It's possible (likely even!) that this analysis
1251 // could be tightened for those cases, but they are rare (the main
1252 // case of interest here is (float)((double)float + float)).
1253 if (OpWidth >= 2*DstWidth+1 && DstWidth >= SrcWidth) {
1254 if (LHSOrig->getType() != CI.getType())
1255 LHSOrig = Builder->CreateFPExt(LHSOrig, CI.getType());
1256 if (RHSOrig->getType() != CI.getType())
1257 RHSOrig = Builder->CreateFPExt(RHSOrig, CI.getType());
Owen Anderson48b842e2014-01-18 00:48:14 +00001258 Instruction *RI =
1259 BinaryOperator::Create(OpI->getOpcode(), LHSOrig, RHSOrig);
1260 RI->copyFastMathFlags(OpI);
1261 return RI;
Chris Lattner2b295a02010-01-04 07:53:58 +00001262 }
Stephen Canonc4549642013-11-28 21:38:05 +00001263 break;
1264 case Instruction::FMul:
1265 // For multiplication, the infinitely precise result has at most
1266 // LHSWidth + RHSWidth significant bits; if OpWidth is sufficient
1267 // that such a value can be exactly represented, then no double
1268 // rounding can possibly occur; we can safely perform the operation
1269 // in the destination format if it can represent both sources.
1270 if (OpWidth >= LHSWidth + RHSWidth && DstWidth >= SrcWidth) {
1271 if (LHSOrig->getType() != CI.getType())
1272 LHSOrig = Builder->CreateFPExt(LHSOrig, CI.getType());
1273 if (RHSOrig->getType() != CI.getType())
1274 RHSOrig = Builder->CreateFPExt(RHSOrig, CI.getType());
Owen Anderson48b842e2014-01-18 00:48:14 +00001275 Instruction *RI =
1276 BinaryOperator::CreateFMul(LHSOrig, RHSOrig);
1277 RI->copyFastMathFlags(OpI);
1278 return RI;
Stephen Canonc4549642013-11-28 21:38:05 +00001279 }
1280 break;
1281 case Instruction::FDiv:
1282 // For division, we use again use the bound from Figueroa's
1283 // dissertation. I am entirely certain that this bound can be
1284 // tightened in the unbalanced operand case by an analysis based on
1285 // the diophantine rational approximation bound, but the well-known
1286 // condition used here is a good conservative first pass.
1287 // TODO: Tighten bound via rigorous analysis of the unbalanced case.
1288 if (OpWidth >= 2*DstWidth && DstWidth >= SrcWidth) {
1289 if (LHSOrig->getType() != CI.getType())
1290 LHSOrig = Builder->CreateFPExt(LHSOrig, CI.getType());
1291 if (RHSOrig->getType() != CI.getType())
1292 RHSOrig = Builder->CreateFPExt(RHSOrig, CI.getType());
Owen Anderson48b842e2014-01-18 00:48:14 +00001293 Instruction *RI =
1294 BinaryOperator::CreateFDiv(LHSOrig, RHSOrig);
1295 RI->copyFastMathFlags(OpI);
1296 return RI;
Stephen Canonc4549642013-11-28 21:38:05 +00001297 }
1298 break;
1299 case Instruction::FRem:
1300 // Remainder is straightforward. Remainder is always exact, so the
1301 // type of OpI doesn't enter into things at all. We simply evaluate
1302 // in whichever source type is larger, then convert to the
1303 // destination type.
Steven Wuf179d122014-12-12 18:48:37 +00001304 if (SrcWidth == OpWidth)
Steven Wu1f7402a2014-12-12 17:21:54 +00001305 break;
Steven Wu1f7402a2014-12-12 17:21:54 +00001306 if (LHSWidth < SrcWidth)
1307 LHSOrig = Builder->CreateFPExt(LHSOrig, RHSOrig->getType());
1308 else if (RHSWidth <= SrcWidth)
1309 RHSOrig = Builder->CreateFPExt(RHSOrig, LHSOrig->getType());
1310 if (LHSOrig != OpI->getOperand(0) || RHSOrig != OpI->getOperand(1)) {
1311 Value *ExactResult = Builder->CreateFRem(LHSOrig, RHSOrig);
1312 if (Instruction *RI = dyn_cast<Instruction>(ExactResult))
1313 RI->copyFastMathFlags(OpI);
1314 return CastInst::CreateFPCast(ExactResult, CI.getType());
1315 }
Chris Lattner2b295a02010-01-04 07:53:58 +00001316 }
Owen Andersondbf0ca52013-01-10 22:06:52 +00001317
1318 // (fptrunc (fneg x)) -> (fneg (fptrunc x))
1319 if (BinaryOperator::isFNeg(OpI)) {
1320 Value *InnerTrunc = Builder->CreateFPTrunc(OpI->getOperand(1),
1321 CI.getType());
Owen Anderson48b842e2014-01-18 00:48:14 +00001322 Instruction *RI = BinaryOperator::CreateFNeg(InnerTrunc);
1323 RI->copyFastMathFlags(OpI);
1324 return RI;
Owen Andersondbf0ca52013-01-10 22:06:52 +00001325 }
Chris Lattner2b295a02010-01-04 07:53:58 +00001326 }
Owen Andersondbf0ca52013-01-10 22:06:52 +00001327
Owen Anderson5797bfd2013-10-03 21:08:05 +00001328 // (fptrunc (select cond, R1, Cst)) -->
1329 // (select cond, (fptrunc R1), (fptrunc Cst))
James Molloy134bec22015-08-11 09:12:57 +00001330 //
1331 // - but only if this isn't part of a min/max operation, else we'll
1332 // ruin min/max canonical form which is to have the select and
1333 // compare's operands be of the same type with no casts to look through.
1334 Value *LHS, *RHS;
Owen Anderson5797bfd2013-10-03 21:08:05 +00001335 SelectInst *SI = dyn_cast<SelectInst>(CI.getOperand(0));
1336 if (SI &&
1337 (isa<ConstantFP>(SI->getOperand(1)) ||
James Molloy134bec22015-08-11 09:12:57 +00001338 isa<ConstantFP>(SI->getOperand(2))) &&
1339 matchSelectPattern(SI, LHS, RHS).Flavor == SPF_UNKNOWN) {
Owen Anderson5797bfd2013-10-03 21:08:05 +00001340 Value *LHSTrunc = Builder->CreateFPTrunc(SI->getOperand(1),
1341 CI.getType());
1342 Value *RHSTrunc = Builder->CreateFPTrunc(SI->getOperand(2),
1343 CI.getType());
1344 return SelectInst::Create(SI->getOperand(0), LHSTrunc, RHSTrunc);
1345 }
1346
Owen Andersondbf0ca52013-01-10 22:06:52 +00001347 IntrinsicInst *II = dyn_cast<IntrinsicInst>(CI.getOperand(0));
1348 if (II) {
1349 switch (II->getIntrinsicID()) {
1350 default: break;
1351 case Intrinsic::fabs: {
1352 // (fptrunc (fabs x)) -> (fabs (fptrunc x))
1353 Value *InnerTrunc = Builder->CreateFPTrunc(II->getArgOperand(0),
1354 CI.getType());
1355 Type *IntrinsicType[] = { CI.getType() };
1356 Function *Overload =
1357 Intrinsic::getDeclaration(CI.getParent()->getParent()->getParent(),
1358 II->getIntrinsicID(), IntrinsicType);
1359
1360 Value *Args[] = { InnerTrunc };
1361 return CallInst::Create(Overload, Args, II->getName());
1362 }
1363 }
1364 }
1365
Craig Topperf40110f2014-04-25 05:29:35 +00001366 return nullptr;
Chris Lattner2b295a02010-01-04 07:53:58 +00001367}
1368
1369Instruction *InstCombiner::visitFPExt(CastInst &CI) {
1370 return commonCastTransforms(CI);
1371}
1372
Mehdi Aminib9a0fa42015-02-16 21:47:54 +00001373// fpto{s/u}i({u/s}itofp(X)) --> X or zext(X) or sext(X) or trunc(X)
1374// This is safe if the intermediate type has enough bits in its mantissa to
1375// accurately represent all values of X. For example, this won't work with
1376// i64 -> float -> i64.
1377Instruction *InstCombiner::FoldItoFPtoI(Instruction &FI) {
1378 if (!isa<UIToFPInst>(FI.getOperand(0)) && !isa<SIToFPInst>(FI.getOperand(0)))
1379 return nullptr;
1380 Instruction *OpI = cast<Instruction>(FI.getOperand(0));
1381
1382 Value *SrcI = OpI->getOperand(0);
1383 Type *FITy = FI.getType();
1384 Type *OpITy = OpI->getType();
1385 Type *SrcTy = SrcI->getType();
1386 bool IsInputSigned = isa<SIToFPInst>(OpI);
1387 bool IsOutputSigned = isa<FPToSIInst>(FI);
1388
1389 // We can safely assume the conversion won't overflow the output range,
1390 // because (for example) (uint8_t)18293.f is undefined behavior.
1391
1392 // Since we can assume the conversion won't overflow, our decision as to
1393 // whether the input will fit in the float should depend on the minimum
1394 // of the input range and output range.
1395
1396 // This means this is also safe for a signed input and unsigned output, since
1397 // a negative input would lead to undefined behavior.
1398 int InputSize = (int)SrcTy->getScalarSizeInBits() - IsInputSigned;
1399 int OutputSize = (int)FITy->getScalarSizeInBits() - IsOutputSigned;
1400 int ActualSize = std::min(InputSize, OutputSize);
1401
1402 if (ActualSize <= OpITy->getFPMantissaWidth()) {
1403 if (FITy->getScalarSizeInBits() > SrcTy->getScalarSizeInBits()) {
1404 if (IsInputSigned && IsOutputSigned)
1405 return new SExtInst(SrcI, FITy);
1406 return new ZExtInst(SrcI, FITy);
1407 }
1408 if (FITy->getScalarSizeInBits() < SrcTy->getScalarSizeInBits())
1409 return new TruncInst(SrcI, FITy);
1410 if (SrcTy == FITy)
1411 return ReplaceInstUsesWith(FI, SrcI);
1412 return new BitCastInst(SrcI, FITy);
1413 }
1414 return nullptr;
1415}
1416
Chris Lattner2b295a02010-01-04 07:53:58 +00001417Instruction *InstCombiner::visitFPToUI(FPToUIInst &FI) {
1418 Instruction *OpI = dyn_cast<Instruction>(FI.getOperand(0));
Craig Topperf40110f2014-04-25 05:29:35 +00001419 if (!OpI)
Chris Lattner2b295a02010-01-04 07:53:58 +00001420 return commonCastTransforms(FI);
1421
Mehdi Aminib9a0fa42015-02-16 21:47:54 +00001422 if (Instruction *I = FoldItoFPtoI(FI))
1423 return I;
Chris Lattner2b295a02010-01-04 07:53:58 +00001424
1425 return commonCastTransforms(FI);
1426}
1427
1428Instruction *InstCombiner::visitFPToSI(FPToSIInst &FI) {
1429 Instruction *OpI = dyn_cast<Instruction>(FI.getOperand(0));
Craig Topperf40110f2014-04-25 05:29:35 +00001430 if (!OpI)
Chris Lattner2b295a02010-01-04 07:53:58 +00001431 return commonCastTransforms(FI);
Craig Topper3529aa52013-01-24 05:22:40 +00001432
Mehdi Aminib9a0fa42015-02-16 21:47:54 +00001433 if (Instruction *I = FoldItoFPtoI(FI))
1434 return I;
Craig Topper3529aa52013-01-24 05:22:40 +00001435
Chris Lattner2b295a02010-01-04 07:53:58 +00001436 return commonCastTransforms(FI);
1437}
1438
1439Instruction *InstCombiner::visitUIToFP(CastInst &CI) {
1440 return commonCastTransforms(CI);
1441}
1442
1443Instruction *InstCombiner::visitSIToFP(CastInst &CI) {
1444 return commonCastTransforms(CI);
1445}
1446
Chris Lattner2b295a02010-01-04 07:53:58 +00001447Instruction *InstCombiner::visitIntToPtr(IntToPtrInst &CI) {
Dan Gohman949458d2010-02-02 01:44:02 +00001448 // If the source integer type is not the intptr_t type for this target, do a
1449 // trunc or zext to the intptr_t type, then inttoptr of it. This allows the
1450 // cast to be exposed to other transforms.
Mehdi Aminia28d91d2015-03-10 02:37:25 +00001451 unsigned AS = CI.getAddressSpace();
1452 if (CI.getOperand(0)->getType()->getScalarSizeInBits() !=
1453 DL.getPointerSizeInBits(AS)) {
1454 Type *Ty = DL.getIntPtrType(CI.getContext(), AS);
1455 if (CI.getType()->isVectorTy()) // Handle vectors of pointers.
1456 Ty = VectorType::get(Ty, CI.getType()->getVectorNumElements());
Benjamin Kramer944e0ab2013-02-05 20:22:40 +00001457
Mehdi Aminia28d91d2015-03-10 02:37:25 +00001458 Value *P = Builder->CreateZExtOrTrunc(CI.getOperand(0), Ty);
1459 return new IntToPtrInst(P, CI.getType());
Chris Lattner2b295a02010-01-04 07:53:58 +00001460 }
Craig Topper3529aa52013-01-24 05:22:40 +00001461
Chris Lattner2b295a02010-01-04 07:53:58 +00001462 if (Instruction *I = commonCastTransforms(CI))
1463 return I;
1464
Craig Topperf40110f2014-04-25 05:29:35 +00001465 return nullptr;
Chris Lattner2b295a02010-01-04 07:53:58 +00001466}
1467
Chris Lattnera93c63c2010-01-05 22:21:18 +00001468/// @brief Implement the transforms for cast of pointer (bitcast/ptrtoint)
1469Instruction *InstCombiner::commonPointerCastTransforms(CastInst &CI) {
1470 Value *Src = CI.getOperand(0);
Craig Topper3529aa52013-01-24 05:22:40 +00001471
Chris Lattnera93c63c2010-01-05 22:21:18 +00001472 if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(Src)) {
1473 // If casting the result of a getelementptr instruction with no offset, turn
1474 // this into a cast of the original pointer!
Jingyue Wu77145d92014-06-06 21:52:55 +00001475 if (GEP->hasAllZeroIndices() &&
1476 // If CI is an addrspacecast and GEP changes the poiner type, merging
1477 // GEP into CI would undo canonicalizing addrspacecast with different
1478 // pointer types, causing infinite loops.
1479 (!isa<AddrSpaceCastInst>(CI) ||
1480 GEP->getType() == GEP->getPointerOperand()->getType())) {
Chris Lattnera93c63c2010-01-05 22:21:18 +00001481 // Changing the cast operand is usually not a good idea but it is safe
Craig Topper3529aa52013-01-24 05:22:40 +00001482 // here because the pointer operand is being replaced with another
Chris Lattnera93c63c2010-01-05 22:21:18 +00001483 // pointer operand so the opcode doesn't need to change.
1484 Worklist.Add(GEP);
1485 CI.setOperand(0, GEP->getOperand(0));
1486 return &CI;
1487 }
Chris Lattnera93c63c2010-01-05 22:21:18 +00001488 }
Craig Topper3529aa52013-01-24 05:22:40 +00001489
Chris Lattnera93c63c2010-01-05 22:21:18 +00001490 return commonCastTransforms(CI);
1491}
1492
1493Instruction *InstCombiner::visitPtrToInt(PtrToIntInst &CI) {
Dan Gohman949458d2010-02-02 01:44:02 +00001494 // If the destination integer type is not the intptr_t type for this target,
1495 // do a ptrtoint to intptr_t then do a trunc or zext. This allows the cast
1496 // to be exposed to other transforms.
Benjamin Kramere4778752013-02-05 19:21:56 +00001497
Matt Arsenault745101d2013-08-21 19:53:10 +00001498 Type *Ty = CI.getType();
1499 unsigned AS = CI.getPointerAddressSpace();
1500
Mehdi Aminia28d91d2015-03-10 02:37:25 +00001501 if (Ty->getScalarSizeInBits() == DL.getPointerSizeInBits(AS))
Matt Arsenault745101d2013-08-21 19:53:10 +00001502 return commonPointerCastTransforms(CI);
1503
Mehdi Aminia28d91d2015-03-10 02:37:25 +00001504 Type *PtrTy = DL.getIntPtrType(CI.getContext(), AS);
Matt Arsenault745101d2013-08-21 19:53:10 +00001505 if (Ty->isVectorTy()) // Handle vectors of pointers.
1506 PtrTy = VectorType::get(PtrTy, Ty->getVectorNumElements());
1507
1508 Value *P = Builder->CreatePtrToInt(CI.getOperand(0), PtrTy);
1509 return CastInst::CreateIntegerCast(P, Ty, /*isSigned=*/false);
Chris Lattnera93c63c2010-01-05 22:21:18 +00001510}
1511
Chris Lattner02b0df52010-05-08 21:50:26 +00001512/// OptimizeVectorResize - This input value (which is known to have vector type)
1513/// is being zero extended or truncated to the specified vector type. Try to
1514/// replace it with a shuffle (and vector/vector bitcast) if possible.
1515///
1516/// The source and destination vector types may have different element types.
Chris Lattner229907c2011-07-18 04:54:35 +00001517static Instruction *OptimizeVectorResize(Value *InVal, VectorType *DestTy,
Chris Lattner02b0df52010-05-08 21:50:26 +00001518 InstCombiner &IC) {
1519 // We can only do this optimization if the output is a multiple of the input
1520 // element size, or the input is a multiple of the output element size.
1521 // Convert the input type to have the same element type as the output.
Chris Lattner229907c2011-07-18 04:54:35 +00001522 VectorType *SrcTy = cast<VectorType>(InVal->getType());
Craig Topper3529aa52013-01-24 05:22:40 +00001523
Chris Lattner02b0df52010-05-08 21:50:26 +00001524 if (SrcTy->getElementType() != DestTy->getElementType()) {
1525 // The input types don't need to be identical, but for now they must be the
1526 // same size. There is no specific reason we couldn't handle things like
1527 // <4 x i16> -> <4 x i32> by bitcasting to <2 x i32> but haven't gotten
Craig Topper3529aa52013-01-24 05:22:40 +00001528 // there yet.
Chris Lattner02b0df52010-05-08 21:50:26 +00001529 if (SrcTy->getElementType()->getPrimitiveSizeInBits() !=
1530 DestTy->getElementType()->getPrimitiveSizeInBits())
Craig Topperf40110f2014-04-25 05:29:35 +00001531 return nullptr;
Craig Topper3529aa52013-01-24 05:22:40 +00001532
Chris Lattner02b0df52010-05-08 21:50:26 +00001533 SrcTy = VectorType::get(DestTy->getElementType(), SrcTy->getNumElements());
1534 InVal = IC.Builder->CreateBitCast(InVal, SrcTy);
1535 }
Craig Topper3529aa52013-01-24 05:22:40 +00001536
Chris Lattner02b0df52010-05-08 21:50:26 +00001537 // Now that the element types match, get the shuffle mask and RHS of the
1538 // shuffle to use, which depends on whether we're increasing or decreasing the
1539 // size of the input.
Chris Lattner8213c8a2012-02-06 21:56:39 +00001540 SmallVector<uint32_t, 16> ShuffleMask;
Chris Lattner02b0df52010-05-08 21:50:26 +00001541 Value *V2;
Craig Topper3529aa52013-01-24 05:22:40 +00001542
Chris Lattner02b0df52010-05-08 21:50:26 +00001543 if (SrcTy->getNumElements() > DestTy->getNumElements()) {
1544 // If we're shrinking the number of elements, just shuffle in the low
1545 // elements from the input and use undef as the second shuffle input.
1546 V2 = UndefValue::get(SrcTy);
1547 for (unsigned i = 0, e = DestTy->getNumElements(); i != e; ++i)
Chris Lattner8213c8a2012-02-06 21:56:39 +00001548 ShuffleMask.push_back(i);
Craig Topper3529aa52013-01-24 05:22:40 +00001549
Chris Lattner02b0df52010-05-08 21:50:26 +00001550 } else {
1551 // If we're increasing the number of elements, shuffle in all of the
1552 // elements from InVal and fill the rest of the result elements with zeros
1553 // from a constant zero.
1554 V2 = Constant::getNullValue(SrcTy);
1555 unsigned SrcElts = SrcTy->getNumElements();
1556 for (unsigned i = 0, e = SrcElts; i != e; ++i)
Chris Lattner8213c8a2012-02-06 21:56:39 +00001557 ShuffleMask.push_back(i);
Chris Lattner02b0df52010-05-08 21:50:26 +00001558
1559 // The excess elements reference the first element of the zero input.
Chris Lattner8213c8a2012-02-06 21:56:39 +00001560 for (unsigned i = 0, e = DestTy->getNumElements()-SrcElts; i != e; ++i)
1561 ShuffleMask.push_back(SrcElts);
Chris Lattner02b0df52010-05-08 21:50:26 +00001562 }
Craig Topper3529aa52013-01-24 05:22:40 +00001563
Chris Lattner8213c8a2012-02-06 21:56:39 +00001564 return new ShuffleVectorInst(InVal, V2,
1565 ConstantDataVector::get(V2->getContext(),
1566 ShuffleMask));
Chris Lattner02b0df52010-05-08 21:50:26 +00001567}
1568
Chris Lattner229907c2011-07-18 04:54:35 +00001569static bool isMultipleOfTypeSize(unsigned Value, Type *Ty) {
Chris Lattnerdd660102010-08-28 01:20:38 +00001570 return Value % Ty->getPrimitiveSizeInBits() == 0;
1571}
1572
Chris Lattner229907c2011-07-18 04:54:35 +00001573static unsigned getTypeSizeIndex(unsigned Value, Type *Ty) {
Chris Lattnerdd660102010-08-28 01:20:38 +00001574 return Value / Ty->getPrimitiveSizeInBits();
1575}
1576
1577/// CollectInsertionElements - V is a value which is inserted into a vector of
1578/// VecEltTy. Look through the value to see if we can decompose it into
1579/// insertions into the vector. See the example in the comment for
1580/// OptimizeIntegerToVectorInsertions for the pattern this handles.
1581/// The type of V is always a non-zero multiple of VecEltTy's size.
Richard Sandifordfeb34712013-08-12 07:26:09 +00001582/// Shift is the number of bits between the lsb of V and the lsb of
1583/// the vector.
Chris Lattnerdd660102010-08-28 01:20:38 +00001584///
1585/// This returns false if the pattern can't be matched or true if it can,
1586/// filling in Elements with the elements found here.
Richard Sandifordfeb34712013-08-12 07:26:09 +00001587static bool CollectInsertionElements(Value *V, unsigned Shift,
Mehdi Aminia28d91d2015-03-10 02:37:25 +00001588 SmallVectorImpl<Value *> &Elements,
1589 Type *VecEltTy, bool isBigEndian) {
Richard Sandifordfeb34712013-08-12 07:26:09 +00001590 assert(isMultipleOfTypeSize(Shift, VecEltTy) &&
1591 "Shift should be a multiple of the element type size");
1592
Chris Lattner50df36a2010-08-28 03:36:51 +00001593 // Undef values never contribute useful bits to the result.
1594 if (isa<UndefValue>(V)) return true;
Craig Topper3529aa52013-01-24 05:22:40 +00001595
Chris Lattnerdd660102010-08-28 01:20:38 +00001596 // If we got down to a value of the right type, we win, try inserting into the
1597 // right element.
1598 if (V->getType() == VecEltTy) {
Chris Lattnerd0214f32010-08-28 01:50:57 +00001599 // Inserting null doesn't actually insert any elements.
1600 if (Constant *C = dyn_cast<Constant>(V))
1601 if (C->isNullValue())
1602 return true;
Craig Topper3529aa52013-01-24 05:22:40 +00001603
Richard Sandifordfeb34712013-08-12 07:26:09 +00001604 unsigned ElementIndex = getTypeSizeIndex(Shift, VecEltTy);
Mehdi Aminia28d91d2015-03-10 02:37:25 +00001605 if (isBigEndian)
Richard Sandifordfeb34712013-08-12 07:26:09 +00001606 ElementIndex = Elements.size() - ElementIndex - 1;
1607
Chris Lattnerdd660102010-08-28 01:20:38 +00001608 // Fail if multiple elements are inserted into this slot.
Craig Topperf40110f2014-04-25 05:29:35 +00001609 if (Elements[ElementIndex])
Chris Lattnerdd660102010-08-28 01:20:38 +00001610 return false;
Craig Topper3529aa52013-01-24 05:22:40 +00001611
Chris Lattnerdd660102010-08-28 01:20:38 +00001612 Elements[ElementIndex] = V;
1613 return true;
1614 }
Craig Topper3529aa52013-01-24 05:22:40 +00001615
Chris Lattnerd0214f32010-08-28 01:50:57 +00001616 if (Constant *C = dyn_cast<Constant>(V)) {
Chris Lattnerdd660102010-08-28 01:20:38 +00001617 // Figure out the # elements this provides, and bitcast it or slice it up
1618 // as required.
Chris Lattnerd0214f32010-08-28 01:50:57 +00001619 unsigned NumElts = getTypeSizeIndex(C->getType()->getPrimitiveSizeInBits(),
1620 VecEltTy);
1621 // If the constant is the size of a vector element, we just need to bitcast
1622 // it to the right type so it gets properly inserted.
1623 if (NumElts == 1)
1624 return CollectInsertionElements(ConstantExpr::getBitCast(C, VecEltTy),
Mehdi Aminia28d91d2015-03-10 02:37:25 +00001625 Shift, Elements, VecEltTy, isBigEndian);
Craig Topper3529aa52013-01-24 05:22:40 +00001626
Chris Lattnerd0214f32010-08-28 01:50:57 +00001627 // Okay, this is a constant that covers multiple elements. Slice it up into
1628 // pieces and insert each element-sized piece into the vector.
1629 if (!isa<IntegerType>(C->getType()))
1630 C = ConstantExpr::getBitCast(C, IntegerType::get(V->getContext(),
1631 C->getType()->getPrimitiveSizeInBits()));
1632 unsigned ElementSize = VecEltTy->getPrimitiveSizeInBits();
Chris Lattner229907c2011-07-18 04:54:35 +00001633 Type *ElementIntTy = IntegerType::get(C->getContext(), ElementSize);
Craig Topper3529aa52013-01-24 05:22:40 +00001634
Chris Lattnerd0214f32010-08-28 01:50:57 +00001635 for (unsigned i = 0; i != NumElts; ++i) {
Richard Sandifordfeb34712013-08-12 07:26:09 +00001636 unsigned ShiftI = Shift+i*ElementSize;
Chris Lattnerd0214f32010-08-28 01:50:57 +00001637 Constant *Piece = ConstantExpr::getLShr(C, ConstantInt::get(C->getType(),
Richard Sandifordfeb34712013-08-12 07:26:09 +00001638 ShiftI));
Chris Lattnerd0214f32010-08-28 01:50:57 +00001639 Piece = ConstantExpr::getTrunc(Piece, ElementIntTy);
Mehdi Aminia28d91d2015-03-10 02:37:25 +00001640 if (!CollectInsertionElements(Piece, ShiftI, Elements, VecEltTy,
1641 isBigEndian))
Chris Lattnerd0214f32010-08-28 01:50:57 +00001642 return false;
1643 }
1644 return true;
1645 }
Craig Topper3529aa52013-01-24 05:22:40 +00001646
Chris Lattnerdd660102010-08-28 01:20:38 +00001647 if (!V->hasOneUse()) return false;
Craig Topper3529aa52013-01-24 05:22:40 +00001648
Chris Lattnerdd660102010-08-28 01:20:38 +00001649 Instruction *I = dyn_cast<Instruction>(V);
Craig Topperf40110f2014-04-25 05:29:35 +00001650 if (!I) return false;
Chris Lattnerdd660102010-08-28 01:20:38 +00001651 switch (I->getOpcode()) {
1652 default: return false; // Unhandled case.
1653 case Instruction::BitCast:
Mehdi Aminia28d91d2015-03-10 02:37:25 +00001654 return CollectInsertionElements(I->getOperand(0), Shift, Elements, VecEltTy,
1655 isBigEndian);
Chris Lattnerdd660102010-08-28 01:20:38 +00001656 case Instruction::ZExt:
1657 if (!isMultipleOfTypeSize(
1658 I->getOperand(0)->getType()->getPrimitiveSizeInBits(),
1659 VecEltTy))
1660 return false;
Mehdi Aminia28d91d2015-03-10 02:37:25 +00001661 return CollectInsertionElements(I->getOperand(0), Shift, Elements, VecEltTy,
1662 isBigEndian);
Chris Lattnerdd660102010-08-28 01:20:38 +00001663 case Instruction::Or:
Mehdi Aminia28d91d2015-03-10 02:37:25 +00001664 return CollectInsertionElements(I->getOperand(0), Shift, Elements, VecEltTy,
1665 isBigEndian) &&
1666 CollectInsertionElements(I->getOperand(1), Shift, Elements, VecEltTy,
1667 isBigEndian);
Chris Lattnerdd660102010-08-28 01:20:38 +00001668 case Instruction::Shl: {
1669 // Must be shifting by a constant that is a multiple of the element size.
1670 ConstantInt *CI = dyn_cast<ConstantInt>(I->getOperand(1));
Craig Topperf40110f2014-04-25 05:29:35 +00001671 if (!CI) return false;
Richard Sandifordfeb34712013-08-12 07:26:09 +00001672 Shift += CI->getZExtValue();
1673 if (!isMultipleOfTypeSize(Shift, VecEltTy)) return false;
Mehdi Aminia28d91d2015-03-10 02:37:25 +00001674 return CollectInsertionElements(I->getOperand(0), Shift, Elements, VecEltTy,
1675 isBigEndian);
Chris Lattnerdd660102010-08-28 01:20:38 +00001676 }
Craig Topper3529aa52013-01-24 05:22:40 +00001677
Chris Lattnerdd660102010-08-28 01:20:38 +00001678 }
1679}
1680
1681
1682/// OptimizeIntegerToVectorInsertions - If the input is an 'or' instruction, we
1683/// may be doing shifts and ors to assemble the elements of the vector manually.
1684/// Try to rip the code out and replace it with insertelements. This is to
1685/// optimize code like this:
1686///
1687/// %tmp37 = bitcast float %inc to i32
1688/// %tmp38 = zext i32 %tmp37 to i64
1689/// %tmp31 = bitcast float %inc5 to i32
1690/// %tmp32 = zext i32 %tmp31 to i64
1691/// %tmp33 = shl i64 %tmp32, 32
1692/// %ins35 = or i64 %tmp33, %tmp38
1693/// %tmp43 = bitcast i64 %ins35 to <2 x float>
1694///
1695/// Into two insertelements that do "buildvector{%inc, %inc5}".
1696static Value *OptimizeIntegerToVectorInsertions(BitCastInst &CI,
1697 InstCombiner &IC) {
Chris Lattner229907c2011-07-18 04:54:35 +00001698 VectorType *DestVecTy = cast<VectorType>(CI.getType());
Chris Lattnerdd660102010-08-28 01:20:38 +00001699 Value *IntInput = CI.getOperand(0);
1700
1701 SmallVector<Value*, 8> Elements(DestVecTy->getNumElements());
1702 if (!CollectInsertionElements(IntInput, 0, Elements,
Mehdi Aminia28d91d2015-03-10 02:37:25 +00001703 DestVecTy->getElementType(),
1704 IC.getDataLayout().isBigEndian()))
Craig Topperf40110f2014-04-25 05:29:35 +00001705 return nullptr;
Chris Lattnerdd660102010-08-28 01:20:38 +00001706
1707 // If we succeeded, we know that all of the element are specified by Elements
1708 // or are zero if Elements has a null entry. Recast this as a set of
1709 // insertions.
1710 Value *Result = Constant::getNullValue(CI.getType());
1711 for (unsigned i = 0, e = Elements.size(); i != e; ++i) {
Craig Topperf40110f2014-04-25 05:29:35 +00001712 if (!Elements[i]) continue; // Unset element.
Craig Topper3529aa52013-01-24 05:22:40 +00001713
Chris Lattnerdd660102010-08-28 01:20:38 +00001714 Result = IC.Builder->CreateInsertElement(Result, Elements[i],
1715 IC.Builder->getInt32(i));
1716 }
Craig Topper3529aa52013-01-24 05:22:40 +00001717
Chris Lattnerdd660102010-08-28 01:20:38 +00001718 return Result;
1719}
1720
1721
Chris Lattnerd4ebd6d2010-08-26 21:55:42 +00001722/// OptimizeIntToFloatBitCast - See if we can optimize an integer->float/double
1723/// bitcast. The various long double bitcasts can't get in here.
Mehdi Aminia28d91d2015-03-10 02:37:25 +00001724static Instruction *OptimizeIntToFloatBitCast(BitCastInst &CI, InstCombiner &IC,
1725 const DataLayout &DL) {
Chris Lattnerd4ebd6d2010-08-26 21:55:42 +00001726 Value *Src = CI.getOperand(0);
Chris Lattner229907c2011-07-18 04:54:35 +00001727 Type *DestTy = CI.getType();
Chris Lattnerd4ebd6d2010-08-26 21:55:42 +00001728
1729 // If this is a bitcast from int to float, check to see if the int is an
1730 // extraction from a vector.
Craig Topperf40110f2014-04-25 05:29:35 +00001731 Value *VecInput = nullptr;
Chris Lattnerbfd22282010-08-26 22:14:59 +00001732 // bitcast(trunc(bitcast(somevector)))
Chris Lattnerd4ebd6d2010-08-26 21:55:42 +00001733 if (match(Src, m_Trunc(m_BitCast(m_Value(VecInput)))) &&
1734 isa<VectorType>(VecInput->getType())) {
Chris Lattner229907c2011-07-18 04:54:35 +00001735 VectorType *VecTy = cast<VectorType>(VecInput->getType());
Chris Lattnerbfd22282010-08-26 22:14:59 +00001736 unsigned DestWidth = DestTy->getPrimitiveSizeInBits();
1737
1738 if (VecTy->getPrimitiveSizeInBits() % DestWidth == 0) {
1739 // If the element type of the vector doesn't match the result type,
1740 // bitcast it to be a vector type we can extract from.
1741 if (VecTy->getElementType() != DestTy) {
1742 VecTy = VectorType::get(DestTy,
1743 VecTy->getPrimitiveSizeInBits() / DestWidth);
1744 VecInput = IC.Builder->CreateBitCast(VecInput, VecTy);
1745 }
Craig Topper3529aa52013-01-24 05:22:40 +00001746
Ulrich Weigand8a51d8e2013-03-26 15:36:14 +00001747 unsigned Elt = 0;
Mehdi Aminia28d91d2015-03-10 02:37:25 +00001748 if (DL.isBigEndian())
Ulrich Weigand8a51d8e2013-03-26 15:36:14 +00001749 Elt = VecTy->getPrimitiveSizeInBits() / DestWidth - 1;
1750 return ExtractElementInst::Create(VecInput, IC.Builder->getInt32(Elt));
Chris Lattnerbfd22282010-08-26 22:14:59 +00001751 }
Chris Lattnerd4ebd6d2010-08-26 21:55:42 +00001752 }
Craig Topper3529aa52013-01-24 05:22:40 +00001753
Chris Lattnerbfd22282010-08-26 22:14:59 +00001754 // bitcast(trunc(lshr(bitcast(somevector), cst))
Craig Topperf40110f2014-04-25 05:29:35 +00001755 ConstantInt *ShAmt = nullptr;
Chris Lattnerbfd22282010-08-26 22:14:59 +00001756 if (match(Src, m_Trunc(m_LShr(m_BitCast(m_Value(VecInput)),
1757 m_ConstantInt(ShAmt)))) &&
1758 isa<VectorType>(VecInput->getType())) {
Chris Lattner229907c2011-07-18 04:54:35 +00001759 VectorType *VecTy = cast<VectorType>(VecInput->getType());
Chris Lattnerbfd22282010-08-26 22:14:59 +00001760 unsigned DestWidth = DestTy->getPrimitiveSizeInBits();
1761 if (VecTy->getPrimitiveSizeInBits() % DestWidth == 0 &&
1762 ShAmt->getZExtValue() % DestWidth == 0) {
1763 // If the element type of the vector doesn't match the result type,
1764 // bitcast it to be a vector type we can extract from.
1765 if (VecTy->getElementType() != DestTy) {
1766 VecTy = VectorType::get(DestTy,
1767 VecTy->getPrimitiveSizeInBits() / DestWidth);
1768 VecInput = IC.Builder->CreateBitCast(VecInput, VecTy);
1769 }
Craig Topper3529aa52013-01-24 05:22:40 +00001770
Chris Lattnerbfd22282010-08-26 22:14:59 +00001771 unsigned Elt = ShAmt->getZExtValue() / DestWidth;
Mehdi Aminia28d91d2015-03-10 02:37:25 +00001772 if (DL.isBigEndian())
Ulrich Weigand8a51d8e2013-03-26 15:36:14 +00001773 Elt = VecTy->getPrimitiveSizeInBits() / DestWidth - 1 - Elt;
Chris Lattnerbfd22282010-08-26 22:14:59 +00001774 return ExtractElementInst::Create(VecInput, IC.Builder->getInt32(Elt));
1775 }
1776 }
Craig Topperf40110f2014-04-25 05:29:35 +00001777 return nullptr;
Chris Lattnerd4ebd6d2010-08-26 21:55:42 +00001778}
Chris Lattner02b0df52010-05-08 21:50:26 +00001779
Chris Lattner2b295a02010-01-04 07:53:58 +00001780Instruction *InstCombiner::visitBitCast(BitCastInst &CI) {
1781 // If the operands are integer typed then apply the integer transforms,
1782 // otherwise just apply the common ones.
1783 Value *Src = CI.getOperand(0);
Chris Lattner229907c2011-07-18 04:54:35 +00001784 Type *SrcTy = Src->getType();
1785 Type *DestTy = CI.getType();
Chris Lattner2b295a02010-01-04 07:53:58 +00001786
Chris Lattner2b295a02010-01-04 07:53:58 +00001787 // Get rid of casts from one type to the same type. These are useless and can
1788 // be replaced by the operand.
1789 if (DestTy == Src->getType())
1790 return ReplaceInstUsesWith(CI, Src);
1791
Chris Lattner229907c2011-07-18 04:54:35 +00001792 if (PointerType *DstPTy = dyn_cast<PointerType>(DestTy)) {
1793 PointerType *SrcPTy = cast<PointerType>(SrcTy);
1794 Type *DstElTy = DstPTy->getElementType();
1795 Type *SrcElTy = SrcPTy->getElementType();
Craig Topper3529aa52013-01-24 05:22:40 +00001796
Chris Lattner2b295a02010-01-04 07:53:58 +00001797 // If we are casting a alloca to a pointer to a type of the same
1798 // size, rewrite the allocation instruction to allocate the "right" type.
1799 // There is no need to modify malloc calls because it is their bitcast that
1800 // needs to be cleaned up.
1801 if (AllocaInst *AI = dyn_cast<AllocaInst>(Src))
1802 if (Instruction *V = PromoteCastOfAllocation(CI, *AI))
1803 return V;
Craig Topper3529aa52013-01-24 05:22:40 +00001804
Chris Lattner2b295a02010-01-04 07:53:58 +00001805 // If the source and destination are pointers, and this cast is equivalent
1806 // to a getelementptr X, 0, 0, 0... turn it into the appropriate gep.
1807 // This can enhance SROA and other transforms that want type-safe pointers.
Chris Lattner2b295a02010-01-04 07:53:58 +00001808 unsigned NumZeros = 0;
Craig Topper3529aa52013-01-24 05:22:40 +00001809 while (SrcElTy != DstElTy &&
Duncan Sands19d0b472010-02-16 11:11:14 +00001810 isa<CompositeType>(SrcElTy) && !SrcElTy->isPointerTy() &&
Chris Lattner2b295a02010-01-04 07:53:58 +00001811 SrcElTy->getNumContainedTypes() /* not "{}" */) {
Benjamin Kramer2a7404a2015-04-18 16:52:08 +00001812 SrcElTy = cast<CompositeType>(SrcElTy)->getTypeAtIndex(0U);
Chris Lattner2b295a02010-01-04 07:53:58 +00001813 ++NumZeros;
1814 }
1815
1816 // If we found a path from the src to dest, create the getelementptr now.
1817 if (SrcElTy == DstElTy) {
Benjamin Kramer2a7404a2015-04-18 16:52:08 +00001818 SmallVector<Value *, 8> Idxs(NumZeros + 1, Builder->getInt32(0));
Jay Foadd1b78492011-07-25 09:48:08 +00001819 return GetElementPtrInst::CreateInBounds(Src, Idxs);
Chris Lattner2b295a02010-01-04 07:53:58 +00001820 }
1821 }
Craig Topper3529aa52013-01-24 05:22:40 +00001822
Chris Lattnerd4ebd6d2010-08-26 21:55:42 +00001823 // Try to optimize int -> float bitcasts.
1824 if ((DestTy->isFloatTy() || DestTy->isDoubleTy()) && isa<IntegerType>(SrcTy))
Mehdi Aminia28d91d2015-03-10 02:37:25 +00001825 if (Instruction *I = OptimizeIntToFloatBitCast(CI, *this, DL))
Chris Lattnerd4ebd6d2010-08-26 21:55:42 +00001826 return I;
Chris Lattner2b295a02010-01-04 07:53:58 +00001827
Chris Lattner229907c2011-07-18 04:54:35 +00001828 if (VectorType *DestVTy = dyn_cast<VectorType>(DestTy)) {
Duncan Sands19d0b472010-02-16 11:11:14 +00001829 if (DestVTy->getNumElements() == 1 && !SrcTy->isVectorTy()) {
Chris Lattnera93c63c2010-01-05 22:21:18 +00001830 Value *Elem = Builder->CreateBitCast(Src, DestVTy->getElementType());
1831 return InsertElementInst::Create(UndefValue::get(DestTy), Elem,
Chris Lattner2b295a02010-01-04 07:53:58 +00001832 Constant::getNullValue(Type::getInt32Ty(CI.getContext())));
Chris Lattner2b295a02010-01-04 07:53:58 +00001833 // FIXME: Canonicalize bitcast(insertelement) -> insertelement(bitcast)
1834 }
Craig Topper3529aa52013-01-24 05:22:40 +00001835
Chris Lattnerdd660102010-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 Lattner02b0df52010-05-08 21:50:26 +00001845 cast<VectorType>(DestTy), *this))
Chris Lattnerdd660102010-08-28 01:20:38 +00001846 return I;
1847 }
Craig Topper3529aa52013-01-24 05:22:40 +00001848
Chris Lattnerdd660102010-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 Lattner02b0df52010-05-08 21:50:26 +00001854 }
Chris Lattner2b295a02010-01-04 07:53:58 +00001855 }
1856
Chris Lattner229907c2011-07-18 04:54:35 +00001857 if (VectorType *SrcVTy = dyn_cast<VectorType>(SrcTy)) {
Michael Ilseman74a6da92013-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 Lattner2b295a02010-01-04 07:53:58 +00001874 }
1875 }
1876
1877 if (ShuffleVectorInst *SVI = dyn_cast<ShuffleVectorInst>(Src)) {
Chris Lattnera93c63c2010-01-05 22:21:18 +00001878 // Okay, we have (bitcast (shuffle ..)). Check to see if this is
Dan Gohmaneb7111b2010-04-07 23:22:42 +00001879 // a bitcast to a vector with the same # elts.
Craig Topper3529aa52013-01-24 05:22:40 +00001880 if (SVI->hasOneUse() && DestTy->isVectorTy() &&
Matt Arsenaultfc00f7e2013-08-14 00:24:34 +00001881 DestTy->getVectorNumElements() == SVI->getType()->getNumElements() &&
Chris Lattnera93c63c2010-01-05 22:21:18 +00001882 SVI->getType()->getNumElements() ==
Matt Arsenaultfc00f7e2013-08-14 00:24:34 +00001883 SVI->getOperand(0)->getType()->getVectorNumElements()) {
Chris Lattnera93c63c2010-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 Topper3529aa52013-01-24 05:22:40 +00001888 if (((Tmp = dyn_cast<BitCastInst>(SVI->getOperand(0))) &&
Chris Lattnera93c63c2010-01-05 22:21:18 +00001889 Tmp->getOperand(0)->getType() == DestTy) ||
Craig Topper3529aa52013-01-24 05:22:40 +00001890 ((Tmp = dyn_cast<BitCastInst>(SVI->getOperand(1))) &&
Chris Lattnera93c63c2010-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 Lattner2b295a02010-01-04 07:53:58 +00001897 }
1898 }
1899 }
Craig Topper3529aa52013-01-24 05:22:40 +00001900
Duncan Sands19d0b472010-02-16 11:11:14 +00001901 if (SrcTy->isPointerTy())
Chris Lattnera93c63c2010-01-05 22:21:18 +00001902 return commonPointerCastTransforms(CI);
1903 return commonCastTransforms(CI);
Chris Lattner2b295a02010-01-04 07:53:58 +00001904}
Matt Arsenaulta9e95ab2013-11-15 05:45:08 +00001905
1906Instruction *InstCombiner::visitAddrSpaceCast(AddrSpaceCastInst &CI) {
Manuel Jacobb4db99c2014-07-16 01:34:21 +00001907 // If the destination pointer element type is not the same as the source's
1908 // first do a bitcast to the destination type, and then the addrspacecast.
1909 // This allows the cast to be exposed to other transforms.
Jingyue Wu77145d92014-06-06 21:52:55 +00001910 Value *Src = CI.getOperand(0);
1911 PointerType *SrcTy = cast<PointerType>(Src->getType()->getScalarType());
1912 PointerType *DestTy = cast<PointerType>(CI.getType()->getScalarType());
1913
1914 Type *DestElemTy = DestTy->getElementType();
1915 if (SrcTy->getElementType() != DestElemTy) {
1916 Type *MidTy = PointerType::get(DestElemTy, SrcTy->getAddressSpace());
Jingyue Wubaabe502014-06-15 21:40:57 +00001917 if (VectorType *VT = dyn_cast<VectorType>(CI.getType())) {
1918 // Handle vectors of pointers.
1919 MidTy = VectorType::get(MidTy, VT->getNumElements());
1920 }
Jingyue Wu77145d92014-06-06 21:52:55 +00001921
1922 Value *NewBitCast = Builder->CreateBitCast(Src, MidTy);
1923 return new AddrSpaceCastInst(NewBitCast, CI.getType());
1924 }
1925
Matt Arsenault2d353d12014-01-14 20:00:45 +00001926 return commonPointerCastTransforms(CI);
Matt Arsenaulta9e95ab2013-11-15 05:45:08 +00001927}