blob: c78f6cd3c6860d0d6c28248b35786584622e4fce [file] [log] [blame]
Chris Lattner80f43d32010-01-04 07:53:58 +00001//===- InstCombineCasts.cpp -----------------------------------------------===//
2//
3// The LLVM Compiler Infrastructure
4//
5// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
9//
10// This file implements the visit functions for cast operations.
11//
12//===----------------------------------------------------------------------===//
13
14#include "InstCombine.h"
Eli Friedman74703252011-07-20 21:57:23 +000015#include "llvm/Analysis/ConstantFolding.h"
Chris Lattner80f43d32010-01-04 07:53:58 +000016#include "llvm/Target/TargetData.h"
Chad Rosier3d925d22011-11-29 23:57:10 +000017#include "llvm/Target/TargetLibraryInfo.h"
Chris Lattner80f43d32010-01-04 07:53:58 +000018#include "llvm/Support/PatternMatch.h"
19using namespace llvm;
20using namespace PatternMatch;
21
Chris Lattnerf3d1b5d2010-01-04 07:59:07 +000022/// DecomposeSimpleLinearExpr - Analyze 'Val', seeing if it is a simple linear
23/// expression. If so, decompose it, returning some value X, such that Val is
24/// X*Scale+Offset.
25///
26static Value *DecomposeSimpleLinearExpr(Value *Val, unsigned &Scale,
Dan Gohman28d2e0a2010-05-28 04:33:04 +000027 uint64_t &Offset) {
Chris Lattnerf3d1b5d2010-01-04 07:59:07 +000028 if (ConstantInt *CI = dyn_cast<ConstantInt>(Val)) {
29 Offset = CI->getZExtValue();
30 Scale = 0;
Dan Gohman28d2e0a2010-05-28 04:33:04 +000031 return ConstantInt::get(Val->getType(), 0);
Chris Lattnerf86d7992010-01-05 20:57:30 +000032 }
33
34 if (BinaryOperator *I = dyn_cast<BinaryOperator>(Val)) {
Bob Wilsone2e86f62011-07-08 22:09:33 +000035 // Cannot look past anything that might overflow.
36 OverflowingBinaryOperator *OBI = dyn_cast<OverflowingBinaryOperator>(Val);
37 if (OBI && !OBI->hasNoUnsignedWrap()) {
38 Scale = 1;
39 Offset = 0;
40 return Val;
41 }
42
Chris Lattnerf3d1b5d2010-01-04 07:59:07 +000043 if (ConstantInt *RHS = dyn_cast<ConstantInt>(I->getOperand(1))) {
44 if (I->getOpcode() == Instruction::Shl) {
45 // This is a value scaled by '1 << the shift amt'.
Dan Gohman28d2e0a2010-05-28 04:33:04 +000046 Scale = UINT64_C(1) << RHS->getZExtValue();
Chris Lattnerf3d1b5d2010-01-04 07:59:07 +000047 Offset = 0;
48 return I->getOperand(0);
Chris Lattnerf86d7992010-01-05 20:57:30 +000049 }
50
51 if (I->getOpcode() == Instruction::Mul) {
Chris Lattnerf3d1b5d2010-01-04 07:59:07 +000052 // This value is scaled by 'RHS'.
53 Scale = RHS->getZExtValue();
54 Offset = 0;
55 return I->getOperand(0);
Chris Lattnerf86d7992010-01-05 20:57:30 +000056 }
57
58 if (I->getOpcode() == Instruction::Add) {
Chris Lattnerf3d1b5d2010-01-04 07:59:07 +000059 // We have X+C. Check to see if we really have (X*C2)+C1,
60 // where C1 is divisible by C2.
61 unsigned SubScale;
62 Value *SubVal =
63 DecomposeSimpleLinearExpr(I->getOperand(0), SubScale, Offset);
64 Offset += RHS->getZExtValue();
65 Scale = SubScale;
66 return SubVal;
67 }
68 }
69 }
70
71 // Otherwise, we can't look past this.
72 Scale = 1;
73 Offset = 0;
74 return Val;
75}
76
77/// PromoteCastOfAllocation - If we find a cast of an allocation instruction,
78/// try to eliminate the cast by moving the type information into the alloc.
79Instruction *InstCombiner::PromoteCastOfAllocation(BitCastInst &CI,
80 AllocaInst &AI) {
81 // This requires TargetData to get the alloca alignment and size information.
82 if (!TD) return 0;
83
Chris Lattnerdb125cf2011-07-18 04:54:35 +000084 PointerType *PTy = cast<PointerType>(CI.getType());
Chris Lattnerf3d1b5d2010-01-04 07:59:07 +000085
86 BuilderTy AllocaBuilder(*Builder);
87 AllocaBuilder.SetInsertPoint(AI.getParent(), &AI);
88
89 // Get the type really allocated and the type casted to.
Chris Lattnerdb125cf2011-07-18 04:54:35 +000090 Type *AllocElTy = AI.getAllocatedType();
91 Type *CastElTy = PTy->getElementType();
Chris Lattnerf3d1b5d2010-01-04 07:59:07 +000092 if (!AllocElTy->isSized() || !CastElTy->isSized()) return 0;
93
94 unsigned AllocElTyAlign = TD->getABITypeAlignment(AllocElTy);
95 unsigned CastElTyAlign = TD->getABITypeAlignment(CastElTy);
96 if (CastElTyAlign < AllocElTyAlign) return 0;
97
98 // If the allocation has multiple uses, only promote it if we are strictly
99 // increasing the alignment of the resultant allocation. If we keep it the
Devang Patel5aa3fa62011-03-08 22:12:11 +0000100 // same, we open the door to infinite loops of various kinds.
101 if (!AI.hasOneUse() && CastElTyAlign == AllocElTyAlign) return 0;
Chris Lattnerf3d1b5d2010-01-04 07:59:07 +0000102
103 uint64_t AllocElTySize = TD->getTypeAllocSize(AllocElTy);
104 uint64_t CastElTySize = TD->getTypeAllocSize(CastElTy);
105 if (CastElTySize == 0 || AllocElTySize == 0) return 0;
106
107 // See if we can satisfy the modulus by pulling a scale out of the array
108 // size argument.
109 unsigned ArraySizeScale;
Dan Gohman28d2e0a2010-05-28 04:33:04 +0000110 uint64_t ArrayOffset;
Chris Lattnerf3d1b5d2010-01-04 07:59:07 +0000111 Value *NumElements = // See if the array size is a decomposable linear expr.
112 DecomposeSimpleLinearExpr(AI.getOperand(0), ArraySizeScale, ArrayOffset);
113
114 // If we can now satisfy the modulus, by using a non-1 scale, we really can
115 // do the xform.
116 if ((AllocElTySize*ArraySizeScale) % CastElTySize != 0 ||
117 (AllocElTySize*ArrayOffset ) % CastElTySize != 0) return 0;
118
119 unsigned Scale = (AllocElTySize*ArraySizeScale)/CastElTySize;
120 Value *Amt = 0;
121 if (Scale == 1) {
122 Amt = NumElements;
123 } else {
Dan Gohman28d2e0a2010-05-28 04:33:04 +0000124 Amt = ConstantInt::get(AI.getArraySize()->getType(), Scale);
Chris Lattnerf3d1b5d2010-01-04 07:59:07 +0000125 // Insert before the alloca, not before the cast.
Benjamin Kramera9390a42011-09-27 20:39:19 +0000126 Amt = AllocaBuilder.CreateMul(Amt, NumElements);
Chris Lattnerf3d1b5d2010-01-04 07:59:07 +0000127 }
128
Dan Gohman28d2e0a2010-05-28 04:33:04 +0000129 if (uint64_t Offset = (AllocElTySize*ArrayOffset)/CastElTySize) {
130 Value *Off = ConstantInt::get(AI.getArraySize()->getType(),
Chris Lattnerf3d1b5d2010-01-04 07:59:07 +0000131 Offset, true);
Benjamin Kramera9390a42011-09-27 20:39:19 +0000132 Amt = AllocaBuilder.CreateAdd(Amt, Off);
Chris Lattnerf3d1b5d2010-01-04 07:59:07 +0000133 }
134
135 AllocaInst *New = AllocaBuilder.CreateAlloca(CastElTy, Amt);
136 New->setAlignment(AI.getAlignment());
137 New->takeName(&AI);
138
Chris Lattnerf3d1b5d2010-01-04 07:59:07 +0000139 // If the allocation has multiple real uses, insert a cast and change all
140 // things that used it to use the new cast. This will also hack on CI, but it
141 // will die soon.
Devang Patel5aa3fa62011-03-08 22:12:11 +0000142 if (!AI.hasOneUse()) {
Chris Lattnerf3d1b5d2010-01-04 07:59:07 +0000143 // New is the allocation instruction, pointer typed. AI is the original
144 // allocation instruction, also pointer typed. Thus, cast to use is BitCast.
145 Value *NewCast = AllocaBuilder.CreateBitCast(New, AI.getType(), "tmpcast");
Eli Friedman3e22cb92011-05-18 00:32:01 +0000146 ReplaceInstUsesWith(AI, NewCast);
Chris Lattnerf3d1b5d2010-01-04 07:59:07 +0000147 }
148 return ReplaceInstUsesWith(CI, New);
149}
150
151
Chris Lattnere0e4cc72010-01-06 01:56:21 +0000152
Chris Lattner5f0290e2010-01-04 07:54:59 +0000153/// EvaluateInDifferentType - Given an expression that
Chris Lattner14bf8f02010-01-08 19:19:23 +0000154/// CanEvaluateTruncated or CanEvaluateSExtd returns true for, actually
Chris Lattnere0e4cc72010-01-06 01:56:21 +0000155/// insert the code to evaluate the expression.
Chris Lattnerdb125cf2011-07-18 04:54:35 +0000156Value *InstCombiner::EvaluateInDifferentType(Value *V, Type *Ty,
Chris Lattner5f0290e2010-01-04 07:54:59 +0000157 bool isSigned) {
Chris Lattnerc8b3fce2010-01-08 19:28:47 +0000158 if (Constant *C = dyn_cast<Constant>(V)) {
159 C = ConstantExpr::getIntegerCast(C, Ty, isSigned /*Sext or ZExt*/);
160 // If we got a constantexpr back, try to simplify it with TD info.
161 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(C))
162 C = ConstantFoldConstantExpression(CE, TD);
163 return C;
164 }
Chris Lattner5f0290e2010-01-04 07:54:59 +0000165
166 // Otherwise, it must be an instruction.
167 Instruction *I = cast<Instruction>(V);
168 Instruction *Res = 0;
169 unsigned Opc = I->getOpcode();
170 switch (Opc) {
171 case Instruction::Add:
172 case Instruction::Sub:
173 case Instruction::Mul:
174 case Instruction::And:
175 case Instruction::Or:
176 case Instruction::Xor:
177 case Instruction::AShr:
178 case Instruction::LShr:
179 case Instruction::Shl:
180 case Instruction::UDiv:
181 case Instruction::URem: {
182 Value *LHS = EvaluateInDifferentType(I->getOperand(0), Ty, isSigned);
183 Value *RHS = EvaluateInDifferentType(I->getOperand(1), Ty, isSigned);
184 Res = BinaryOperator::Create((Instruction::BinaryOps)Opc, LHS, RHS);
185 break;
186 }
187 case Instruction::Trunc:
188 case Instruction::ZExt:
189 case Instruction::SExt:
190 // If the source type of the cast is the type we're trying for then we can
191 // just return the source. There's no need to insert it because it is not
192 // new.
193 if (I->getOperand(0)->getType() == Ty)
194 return I->getOperand(0);
195
196 // Otherwise, must be the same type of cast, so just reinsert a new one.
Chris Lattner9ee947c2010-01-10 20:25:54 +0000197 // This also handles the case of zext(trunc(x)) -> zext(x).
198 Res = CastInst::CreateIntegerCast(I->getOperand(0), Ty,
199 Opc == Instruction::SExt);
Chris Lattner5f0290e2010-01-04 07:54:59 +0000200 break;
201 case Instruction::Select: {
202 Value *True = EvaluateInDifferentType(I->getOperand(1), Ty, isSigned);
203 Value *False = EvaluateInDifferentType(I->getOperand(2), Ty, isSigned);
204 Res = SelectInst::Create(I->getOperand(0), True, False);
205 break;
206 }
207 case Instruction::PHI: {
208 PHINode *OPN = cast<PHINode>(I);
Jay Foad3ecfc862011-03-30 11:28:46 +0000209 PHINode *NPN = PHINode::Create(Ty, OPN->getNumIncomingValues());
Chris Lattner5f0290e2010-01-04 07:54:59 +0000210 for (unsigned i = 0, e = OPN->getNumIncomingValues(); i != e; ++i) {
211 Value *V =EvaluateInDifferentType(OPN->getIncomingValue(i), Ty, isSigned);
212 NPN->addIncoming(V, OPN->getIncomingBlock(i));
213 }
214 Res = NPN;
215 break;
216 }
217 default:
218 // TODO: Can handle more cases here.
219 llvm_unreachable("Unreachable!");
220 break;
221 }
222
223 Res->takeName(I);
Eli Friedmana311c342011-05-27 00:19:40 +0000224 return InsertNewInstWith(Res, *I);
Chris Lattner5f0290e2010-01-04 07:54:59 +0000225}
Chris Lattner80f43d32010-01-04 07:53:58 +0000226
227
228/// This function is a wrapper around CastInst::isEliminableCastPair. It
229/// simply extracts arguments and returns what that function returns.
230static Instruction::CastOps
231isEliminableCastPair(
232 const CastInst *CI, ///< The first cast instruction
233 unsigned opcode, ///< The opcode of the second cast instruction
Chris Lattnerdb125cf2011-07-18 04:54:35 +0000234 Type *DstTy, ///< The target type for the second cast instruction
Chris Lattner80f43d32010-01-04 07:53:58 +0000235 TargetData *TD ///< The target data for pointer size
236) {
237
Chris Lattnerdb125cf2011-07-18 04:54:35 +0000238 Type *SrcTy = CI->getOperand(0)->getType(); // A from above
239 Type *MidTy = CI->getType(); // B from above
Chris Lattner80f43d32010-01-04 07:53:58 +0000240
241 // Get the opcodes of the two Cast instructions
242 Instruction::CastOps firstOp = Instruction::CastOps(CI->getOpcode());
243 Instruction::CastOps secondOp = Instruction::CastOps(opcode);
244
245 unsigned Res = CastInst::isEliminableCastPair(firstOp, secondOp, SrcTy, MidTy,
246 DstTy,
247 TD ? TD->getIntPtrType(CI->getContext()) : 0);
248
249 // We don't want to form an inttoptr or ptrtoint that converts to an integer
250 // type that differs from the pointer size.
251 if ((Res == Instruction::IntToPtr &&
252 (!TD || SrcTy != TD->getIntPtrType(CI->getContext()))) ||
253 (Res == Instruction::PtrToInt &&
254 (!TD || DstTy != TD->getIntPtrType(CI->getContext()))))
255 Res = 0;
256
257 return Instruction::CastOps(Res);
258}
259
Chris Lattner8c5ad3a2010-02-11 06:26:33 +0000260/// ShouldOptimizeCast - Return true if the cast from "V to Ty" actually
261/// results in any code being generated and is interesting to optimize out. If
262/// the cast can be eliminated by some other simple transformation, we prefer
263/// to do the simplification first.
264bool InstCombiner::ShouldOptimizeCast(Instruction::CastOps opc, const Value *V,
Chris Lattnerdb125cf2011-07-18 04:54:35 +0000265 Type *Ty) {
Chris Lattner8c5ad3a2010-02-11 06:26:33 +0000266 // Noop casts and casts of constants should be eliminated trivially.
Chris Lattner80f43d32010-01-04 07:53:58 +0000267 if (V->getType() == Ty || isa<Constant>(V)) return false;
268
Chris Lattner8c5ad3a2010-02-11 06:26:33 +0000269 // If this is another cast that can be eliminated, we prefer to have it
270 // eliminated.
Chris Lattner80f43d32010-01-04 07:53:58 +0000271 if (const CastInst *CI = dyn_cast<CastInst>(V))
Chris Lattner8c5ad3a2010-02-11 06:26:33 +0000272 if (isEliminableCastPair(CI, opc, Ty, TD))
Chris Lattner80f43d32010-01-04 07:53:58 +0000273 return false;
Chris Lattner8c5ad3a2010-02-11 06:26:33 +0000274
275 // If this is a vector sext from a compare, then we don't want to break the
276 // idiom where each element of the extended vector is either zero or all ones.
Duncan Sands1df98592010-02-16 11:11:14 +0000277 if (opc == Instruction::SExt && isa<CmpInst>(V) && Ty->isVectorTy())
Chris Lattner8c5ad3a2010-02-11 06:26:33 +0000278 return false;
279
Chris Lattner80f43d32010-01-04 07:53:58 +0000280 return true;
281}
282
283
284/// @brief Implement the transforms common to all CastInst visitors.
285Instruction *InstCombiner::commonCastTransforms(CastInst &CI) {
286 Value *Src = CI.getOperand(0);
287
288 // Many cases of "cast of a cast" are eliminable. If it's eliminable we just
289 // eliminate it now.
290 if (CastInst *CSrc = dyn_cast<CastInst>(Src)) { // A->B->C cast
291 if (Instruction::CastOps opc =
292 isEliminableCastPair(CSrc, CI.getOpcode(), CI.getType(), TD)) {
293 // The first cast (CSrc) is eliminable so we need to fix up or replace
294 // the second cast (CI). CSrc will then have a good chance of being dead.
295 return CastInst::Create(opc, CSrc->getOperand(0), CI.getType());
296 }
297 }
298
299 // If we are casting a select then fold the cast into the select
300 if (SelectInst *SI = dyn_cast<SelectInst>(Src))
301 if (Instruction *NV = FoldOpIntoSelect(CI, SI))
302 return NV;
303
304 // If we are casting a PHI then fold the cast into the PHI
305 if (isa<PHINode>(Src)) {
306 // We don't do this if this would create a PHI node with an illegal type if
307 // it is currently legal.
Duncan Sands1df98592010-02-16 11:11:14 +0000308 if (!Src->getType()->isIntegerTy() ||
309 !CI.getType()->isIntegerTy() ||
Chris Lattner80f43d32010-01-04 07:53:58 +0000310 ShouldChangeType(CI.getType(), Src->getType()))
311 if (Instruction *NV = FoldOpIntoPhi(CI))
312 return NV;
313 }
314
315 return 0;
316}
317
Chris Lattner75215c92010-01-10 00:58:42 +0000318/// CanEvaluateTruncated - Return true if we can evaluate the specified
319/// expression tree as type Ty instead of its larger type, and arrive with the
320/// same value. This is used by code that tries to eliminate truncates.
321///
322/// Ty will always be a type smaller than V. We should return true if trunc(V)
323/// can be computed by computing V in the smaller type. If V is an instruction,
324/// then trunc(inst(x,y)) can be computed as inst(trunc(x),trunc(y)), which only
325/// makes sense if x and y can be efficiently truncated.
326///
Chris Lattner8cf4f6f2010-01-11 02:43:35 +0000327/// This function works on both vectors and scalars.
328///
Chris Lattnerdb125cf2011-07-18 04:54:35 +0000329static bool CanEvaluateTruncated(Value *V, Type *Ty) {
Chris Lattner75215c92010-01-10 00:58:42 +0000330 // We can always evaluate constants in another type.
331 if (isa<Constant>(V))
332 return true;
Chris Lattner68c6e892010-01-05 23:00:30 +0000333
Chris Lattner75215c92010-01-10 00:58:42 +0000334 Instruction *I = dyn_cast<Instruction>(V);
335 if (!I) return false;
336
Chris Lattnerdb125cf2011-07-18 04:54:35 +0000337 Type *OrigTy = V->getType();
Chris Lattner75215c92010-01-10 00:58:42 +0000338
Chris Lattnera958cbf2010-01-11 22:45:25 +0000339 // If this is an extension from the dest type, we can eliminate it, even if it
340 // has multiple uses.
Chris Lattner53af2d12010-01-11 22:49:40 +0000341 if ((isa<ZExtInst>(I) || isa<SExtInst>(I)) &&
Chris Lattner75215c92010-01-10 00:58:42 +0000342 I->getOperand(0)->getType() == Ty)
343 return true;
344
345 // We can't extend or shrink something that has multiple uses: doing so would
346 // require duplicating the instruction in general, which isn't profitable.
347 if (!I->hasOneUse()) return false;
348
349 unsigned Opc = I->getOpcode();
350 switch (Opc) {
351 case Instruction::Add:
352 case Instruction::Sub:
353 case Instruction::Mul:
354 case Instruction::And:
355 case Instruction::Or:
356 case Instruction::Xor:
357 // These operators can all arbitrarily be extended or truncated.
358 return CanEvaluateTruncated(I->getOperand(0), Ty) &&
359 CanEvaluateTruncated(I->getOperand(1), Ty);
360
361 case Instruction::UDiv:
362 case Instruction::URem: {
363 // UDiv and URem can be truncated if all the truncated bits are zero.
364 uint32_t OrigBitWidth = OrigTy->getScalarSizeInBits();
365 uint32_t BitWidth = Ty->getScalarSizeInBits();
366 if (BitWidth < OrigBitWidth) {
367 APInt Mask = APInt::getHighBitsSet(OrigBitWidth, OrigBitWidth-BitWidth);
368 if (MaskedValueIsZero(I->getOperand(0), Mask) &&
369 MaskedValueIsZero(I->getOperand(1), Mask)) {
370 return CanEvaluateTruncated(I->getOperand(0), Ty) &&
371 CanEvaluateTruncated(I->getOperand(1), Ty);
372 }
373 }
374 break;
375 }
376 case Instruction::Shl:
377 // If we are truncating the result of this SHL, and if it's a shift of a
378 // constant amount, we can always perform a SHL in a smaller type.
379 if (ConstantInt *CI = dyn_cast<ConstantInt>(I->getOperand(1))) {
380 uint32_t BitWidth = Ty->getScalarSizeInBits();
381 if (CI->getLimitedValue(BitWidth) < BitWidth)
382 return CanEvaluateTruncated(I->getOperand(0), Ty);
383 }
384 break;
385 case Instruction::LShr:
386 // If this is a truncate of a logical shr, we can truncate it to a smaller
387 // lshr iff we know that the bits we would otherwise be shifting in are
388 // already zeros.
389 if (ConstantInt *CI = dyn_cast<ConstantInt>(I->getOperand(1))) {
390 uint32_t OrigBitWidth = OrigTy->getScalarSizeInBits();
391 uint32_t BitWidth = Ty->getScalarSizeInBits();
392 if (MaskedValueIsZero(I->getOperand(0),
393 APInt::getHighBitsSet(OrigBitWidth, OrigBitWidth-BitWidth)) &&
394 CI->getLimitedValue(BitWidth) < BitWidth) {
395 return CanEvaluateTruncated(I->getOperand(0), Ty);
396 }
397 }
398 break;
399 case Instruction::Trunc:
400 // trunc(trunc(x)) -> trunc(x)
401 return true;
Chris Lattnerf9d05ab2010-08-27 20:32:06 +0000402 case Instruction::ZExt:
403 case Instruction::SExt:
404 // trunc(ext(x)) -> ext(x) if the source type is smaller than the new dest
405 // trunc(ext(x)) -> trunc(x) if the source type is larger than the new dest
406 return true;
Chris Lattner75215c92010-01-10 00:58:42 +0000407 case Instruction::Select: {
408 SelectInst *SI = cast<SelectInst>(I);
409 return CanEvaluateTruncated(SI->getTrueValue(), Ty) &&
410 CanEvaluateTruncated(SI->getFalseValue(), Ty);
411 }
412 case Instruction::PHI: {
413 // We can change a phi if we can change all operands. Note that we never
414 // get into trouble with cyclic PHIs here because we only consider
415 // instructions with a single use.
416 PHINode *PN = cast<PHINode>(I);
417 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i)
418 if (!CanEvaluateTruncated(PN->getIncomingValue(i), Ty))
419 return false;
420 return true;
421 }
422 default:
423 // TODO: Can handle more cases here.
424 break;
425 }
426
427 return false;
428}
429
430Instruction *InstCombiner::visitTrunc(TruncInst &CI) {
Chris Lattnerd84dfa42010-01-10 01:00:46 +0000431 if (Instruction *Result = commonCastTransforms(CI))
Chris Lattner75215c92010-01-10 00:58:42 +0000432 return Result;
433
Chris Lattnerd84dfa42010-01-10 01:00:46 +0000434 // See if we can simplify any instructions used by the input whose sole
435 // purpose is to compute bits we don't care about.
436 if (SimplifyDemandedInstructionBits(CI))
437 return &CI;
438
Chris Lattner75215c92010-01-10 00:58:42 +0000439 Value *Src = CI.getOperand(0);
Chris Lattnerdb125cf2011-07-18 04:54:35 +0000440 Type *DestTy = CI.getType(), *SrcTy = Src->getType();
Chris Lattner75215c92010-01-10 00:58:42 +0000441
442 // Attempt to truncate the entire input expression tree to the destination
443 // type. Only do this if the dest type is a simple type, don't convert the
Chris Lattner80f43d32010-01-04 07:53:58 +0000444 // expression tree to something weird like i93 unless the source is also
445 // strange.
Duncan Sands1df98592010-02-16 11:11:14 +0000446 if ((DestTy->isVectorTy() || ShouldChangeType(SrcTy, DestTy)) &&
Chris Lattner75215c92010-01-10 00:58:42 +0000447 CanEvaluateTruncated(Src, DestTy)) {
Chris Lattnere0e4cc72010-01-06 01:56:21 +0000448
Chris Lattner80f43d32010-01-04 07:53:58 +0000449 // If this cast is a truncate, evaluting in a different type always
Chris Lattner68c6e892010-01-05 23:00:30 +0000450 // eliminates the cast, so it is always a win.
Chris Lattner075f6922010-01-07 23:41:00 +0000451 DEBUG(dbgs() << "ICE: EvaluateInDifferentType converting expression type"
Dan Gohman5b71dce2010-05-25 21:50:35 +0000452 " to avoid cast: " << CI << '\n');
Chris Lattner075f6922010-01-07 23:41:00 +0000453 Value *Res = EvaluateInDifferentType(Src, DestTy, false);
454 assert(Res->getType() == DestTy);
455 return ReplaceInstUsesWith(CI, Res);
456 }
Chris Lattner80f43d32010-01-04 07:53:58 +0000457
Chris Lattner7a34d6c2010-01-05 22:21:18 +0000458 // Canonicalize trunc x to i1 -> (icmp ne (and x, 1), 0), likewise for vector.
459 if (DestTy->getScalarSizeInBits() == 1) {
Chris Lattner80f43d32010-01-04 07:53:58 +0000460 Constant *One = ConstantInt::get(Src->getType(), 1);
Benjamin Kramera9390a42011-09-27 20:39:19 +0000461 Src = Builder->CreateAnd(Src, One);
Chris Lattner80f43d32010-01-04 07:53:58 +0000462 Value *Zero = Constant::getNullValue(Src->getType());
463 return new ICmpInst(ICmpInst::ICMP_NE, Src, Zero);
464 }
Chris Lattner784f3332010-08-27 18:31:05 +0000465
466 // Transform trunc(lshr (zext A), Cst) to eliminate one type conversion.
467 Value *A = 0; ConstantInt *Cst = 0;
Chris Lattner62fe4062011-01-15 06:32:33 +0000468 if (Src->hasOneUse() &&
469 match(Src, m_LShr(m_ZExt(m_Value(A)), m_ConstantInt(Cst)))) {
Chris Lattner784f3332010-08-27 18:31:05 +0000470 // We have three types to worry about here, the type of A, the source of
471 // the truncate (MidSize), and the destination of the truncate. We know that
472 // ASize < MidSize and MidSize > ResultSize, but don't know the relation
473 // between ASize and ResultSize.
474 unsigned ASize = A->getType()->getPrimitiveSizeInBits();
475
476 // If the shift amount is larger than the size of A, then the result is
477 // known to be zero because all the input bits got shifted out.
478 if (Cst->getZExtValue() >= ASize)
479 return ReplaceInstUsesWith(CI, Constant::getNullValue(CI.getType()));
480
481 // Since we're doing an lshr and a zero extend, and know that the shift
482 // amount is smaller than ASize, it is always safe to do the shift in A's
483 // type, then zero extend or truncate to the result.
484 Value *Shift = Builder->CreateLShr(A, Cst->getZExtValue());
485 Shift->takeName(Src);
486 return CastInst::CreateIntegerCast(Shift, CI.getType(), false);
487 }
Chris Lattner62fe4062011-01-15 06:32:33 +0000488
489 // Transform "trunc (and X, cst)" -> "and (trunc X), cst" so long as the dest
490 // type isn't non-native.
491 if (Src->hasOneUse() && isa<IntegerType>(Src->getType()) &&
492 ShouldChangeType(Src->getType(), CI.getType()) &&
493 match(Src, m_And(m_Value(A), m_ConstantInt(Cst)))) {
494 Value *NewTrunc = Builder->CreateTrunc(A, CI.getType(), A->getName()+".tr");
495 return BinaryOperator::CreateAnd(NewTrunc,
496 ConstantExpr::getTrunc(Cst, CI.getType()));
497 }
Chris Lattner80f43d32010-01-04 07:53:58 +0000498
Chris Lattner80f43d32010-01-04 07:53:58 +0000499 return 0;
500}
501
502/// transformZExtICmp - Transform (zext icmp) to bitwise / integer operations
503/// in order to eliminate the icmp.
504Instruction *InstCombiner::transformZExtICmp(ICmpInst *ICI, Instruction &CI,
505 bool DoXform) {
506 // If we are just checking for a icmp eq of a single bit and zext'ing it
507 // to an integer, then shift the bit to the appropriate place and then
508 // cast to integer to avoid the comparison.
509 if (ConstantInt *Op1C = dyn_cast<ConstantInt>(ICI->getOperand(1))) {
510 const APInt &Op1CV = Op1C->getValue();
511
512 // zext (x <s 0) to i32 --> x>>u31 true if signbit set.
513 // zext (x >s -1) to i32 --> (x>>u31)^1 true if signbit clear.
514 if ((ICI->getPredicate() == ICmpInst::ICMP_SLT && Op1CV == 0) ||
515 (ICI->getPredicate() == ICmpInst::ICMP_SGT &&Op1CV.isAllOnesValue())) {
516 if (!DoXform) return ICI;
517
518 Value *In = ICI->getOperand(0);
519 Value *Sh = ConstantInt::get(In->getType(),
520 In->getType()->getScalarSizeInBits()-1);
521 In = Builder->CreateLShr(In, Sh, In->getName()+".lobit");
522 if (In->getType() != CI.getType())
Benjamin Kramera9390a42011-09-27 20:39:19 +0000523 In = Builder->CreateIntCast(In, CI.getType(), false/*ZExt*/);
Chris Lattner80f43d32010-01-04 07:53:58 +0000524
525 if (ICI->getPredicate() == ICmpInst::ICMP_SGT) {
526 Constant *One = ConstantInt::get(In->getType(), 1);
527 In = Builder->CreateXor(In, One, In->getName()+".not");
528 }
529
530 return ReplaceInstUsesWith(CI, In);
531 }
Chad Rosiercaebb1e2011-11-30 01:59:59 +0000532
Chris Lattner80f43d32010-01-04 07:53:58 +0000533 // zext (X == 0) to i32 --> X^1 iff X has only the low bit set.
534 // zext (X == 0) to i32 --> (X>>1)^1 iff X has only the 2nd bit set.
535 // zext (X == 1) to i32 --> X iff X has only the low bit set.
536 // zext (X == 2) to i32 --> X>>1 iff X has only the 2nd bit set.
537 // zext (X != 0) to i32 --> X iff X has only the low bit set.
538 // zext (X != 0) to i32 --> X>>1 iff X has only the 2nd bit set.
539 // zext (X != 1) to i32 --> X^1 iff X has only the low bit set.
540 // zext (X != 2) to i32 --> (X>>1)^1 iff X has only the 2nd bit set.
541 if ((Op1CV == 0 || Op1CV.isPowerOf2()) &&
542 // This only works for EQ and NE
543 ICI->isEquality()) {
544 // If Op1C some other power of two, convert:
545 uint32_t BitWidth = Op1C->getType()->getBitWidth();
546 APInt KnownZero(BitWidth, 0), KnownOne(BitWidth, 0);
547 APInt TypeMask(APInt::getAllOnesValue(BitWidth));
548 ComputeMaskedBits(ICI->getOperand(0), TypeMask, KnownZero, KnownOne);
549
550 APInt KnownZeroMask(~KnownZero);
551 if (KnownZeroMask.isPowerOf2()) { // Exactly 1 possible 1?
552 if (!DoXform) return ICI;
553
554 bool isNE = ICI->getPredicate() == ICmpInst::ICMP_NE;
555 if (Op1CV != 0 && (Op1CV != KnownZeroMask)) {
556 // (X&4) == 2 --> false
557 // (X&4) != 2 --> true
558 Constant *Res = ConstantInt::get(Type::getInt1Ty(CI.getContext()),
559 isNE);
560 Res = ConstantExpr::getZExt(Res, CI.getType());
561 return ReplaceInstUsesWith(CI, Res);
562 }
563
564 uint32_t ShiftAmt = KnownZeroMask.logBase2();
565 Value *In = ICI->getOperand(0);
566 if (ShiftAmt) {
567 // Perform a logical shr by shiftamt.
568 // Insert the shift to put the result in the low bit.
569 In = Builder->CreateLShr(In, ConstantInt::get(In->getType(),ShiftAmt),
570 In->getName()+".lobit");
571 }
572
573 if ((Op1CV != 0) == isNE) { // Toggle the low bit.
574 Constant *One = ConstantInt::get(In->getType(), 1);
Benjamin Kramera9390a42011-09-27 20:39:19 +0000575 In = Builder->CreateXor(In, One);
Chris Lattner80f43d32010-01-04 07:53:58 +0000576 }
577
578 if (CI.getType() == In->getType())
579 return ReplaceInstUsesWith(CI, In);
Chris Lattner29cc0b32010-08-27 22:24:38 +0000580 return CastInst::CreateIntegerCast(In, CI.getType(), false/*ZExt*/);
Chris Lattner80f43d32010-01-04 07:53:58 +0000581 }
582 }
583 }
584
585 // icmp ne A, B is equal to xor A, B when A and B only really have one bit.
586 // It is also profitable to transform icmp eq into not(xor(A, B)) because that
587 // may lead to additional simplifications.
588 if (ICI->isEquality() && CI.getType() == ICI->getOperand(0)->getType()) {
Chris Lattnerdb125cf2011-07-18 04:54:35 +0000589 if (IntegerType *ITy = dyn_cast<IntegerType>(CI.getType())) {
Chris Lattner80f43d32010-01-04 07:53:58 +0000590 uint32_t BitWidth = ITy->getBitWidth();
591 Value *LHS = ICI->getOperand(0);
592 Value *RHS = ICI->getOperand(1);
593
594 APInt KnownZeroLHS(BitWidth, 0), KnownOneLHS(BitWidth, 0);
595 APInt KnownZeroRHS(BitWidth, 0), KnownOneRHS(BitWidth, 0);
596 APInt TypeMask(APInt::getAllOnesValue(BitWidth));
597 ComputeMaskedBits(LHS, TypeMask, KnownZeroLHS, KnownOneLHS);
598 ComputeMaskedBits(RHS, TypeMask, KnownZeroRHS, KnownOneRHS);
599
600 if (KnownZeroLHS == KnownZeroRHS && KnownOneLHS == KnownOneRHS) {
601 APInt KnownBits = KnownZeroLHS | KnownOneLHS;
602 APInt UnknownBit = ~KnownBits;
603 if (UnknownBit.countPopulation() == 1) {
604 if (!DoXform) return ICI;
605
606 Value *Result = Builder->CreateXor(LHS, RHS);
607
608 // Mask off any bits that are set and won't be shifted away.
609 if (KnownOneLHS.uge(UnknownBit))
610 Result = Builder->CreateAnd(Result,
611 ConstantInt::get(ITy, UnknownBit));
612
613 // Shift the bit we're testing down to the lsb.
614 Result = Builder->CreateLShr(
615 Result, ConstantInt::get(ITy, UnknownBit.countTrailingZeros()));
616
617 if (ICI->getPredicate() == ICmpInst::ICMP_EQ)
618 Result = Builder->CreateXor(Result, ConstantInt::get(ITy, 1));
619 Result->takeName(ICI);
620 return ReplaceInstUsesWith(CI, Result);
621 }
622 }
623 }
624 }
625
626 return 0;
627}
628
Chris Lattner75215c92010-01-10 00:58:42 +0000629/// CanEvaluateZExtd - Determine if the specified value can be computed in the
Chris Lattner8cf4f6f2010-01-11 02:43:35 +0000630/// specified wider type and produce the same low bits. If not, return false.
631///
Chris Lattner789162a2010-01-11 03:32:00 +0000632/// If this function returns true, it can also return a non-zero number of bits
633/// (in BitsToClear) which indicates that the value it computes is correct for
634/// the zero extend, but that the additional BitsToClear bits need to be zero'd
635/// out. For example, to promote something like:
636///
637/// %B = trunc i64 %A to i32
638/// %C = lshr i32 %B, 8
639/// %E = zext i32 %C to i64
640///
641/// CanEvaluateZExtd for the 'lshr' will return true, and BitsToClear will be
642/// set to 8 to indicate that the promoted value needs to have bits 24-31
643/// cleared in addition to bits 32-63. Since an 'and' will be generated to
644/// clear the top bits anyway, doing this has no extra cost.
645///
Chris Lattner8cf4f6f2010-01-11 02:43:35 +0000646/// This function works on both vectors and scalars.
Chris Lattnerdb125cf2011-07-18 04:54:35 +0000647static bool CanEvaluateZExtd(Value *V, Type *Ty, unsigned &BitsToClear) {
Chris Lattner789162a2010-01-11 03:32:00 +0000648 BitsToClear = 0;
Chris Lattner9e390dd2010-01-10 02:50:04 +0000649 if (isa<Constant>(V))
650 return true;
Chris Lattner75215c92010-01-10 00:58:42 +0000651
652 Instruction *I = dyn_cast<Instruction>(V);
Chris Lattner9e390dd2010-01-10 02:50:04 +0000653 if (!I) return false;
Chris Lattner75215c92010-01-10 00:58:42 +0000654
655 // If the input is a truncate from the destination type, we can trivially
Chris Lattnera958cbf2010-01-11 22:45:25 +0000656 // eliminate it, even if it has multiple uses.
657 // FIXME: This is currently disabled until codegen can handle this without
658 // pessimizing code, PR5997.
659 if (0 && isa<TruncInst>(I) && I->getOperand(0)->getType() == Ty)
Chris Lattner9e390dd2010-01-10 02:50:04 +0000660 return true;
Chris Lattner75215c92010-01-10 00:58:42 +0000661
662 // We can't extend or shrink something that has multiple uses: doing so would
663 // require duplicating the instruction in general, which isn't profitable.
Chris Lattner9e390dd2010-01-10 02:50:04 +0000664 if (!I->hasOneUse()) return false;
Chris Lattner75215c92010-01-10 00:58:42 +0000665
Chris Lattner789162a2010-01-11 03:32:00 +0000666 unsigned Opc = I->getOpcode(), Tmp;
Chris Lattner75215c92010-01-10 00:58:42 +0000667 switch (Opc) {
Chris Lattner9ee947c2010-01-10 20:25:54 +0000668 case Instruction::ZExt: // zext(zext(x)) -> zext(x).
669 case Instruction::SExt: // zext(sext(x)) -> sext(x).
670 case Instruction::Trunc: // zext(trunc(x)) -> trunc(x) or zext(x)
671 return true;
Chris Lattner75215c92010-01-10 00:58:42 +0000672 case Instruction::And:
Chris Lattner75215c92010-01-10 00:58:42 +0000673 case Instruction::Or:
674 case Instruction::Xor:
Chris Lattner75215c92010-01-10 00:58:42 +0000675 case Instruction::Add:
676 case Instruction::Sub:
677 case Instruction::Mul:
Chris Lattnerd26c9e12010-01-10 02:22:12 +0000678 case Instruction::Shl:
Chris Lattner789162a2010-01-11 03:32:00 +0000679 if (!CanEvaluateZExtd(I->getOperand(0), Ty, BitsToClear) ||
680 !CanEvaluateZExtd(I->getOperand(1), Ty, Tmp))
681 return false;
682 // These can all be promoted if neither operand has 'bits to clear'.
683 if (BitsToClear == 0 && Tmp == 0)
684 return true;
Chris Lattner75215c92010-01-10 00:58:42 +0000685
Chris Lattner7acc4b12010-01-11 04:05:13 +0000686 // If the operation is an AND/OR/XOR and the bits to clear are zero in the
687 // other side, BitsToClear is ok.
688 if (Tmp == 0 &&
689 (Opc == Instruction::And || Opc == Instruction::Or ||
690 Opc == Instruction::Xor)) {
691 // We use MaskedValueIsZero here for generality, but the case we care
692 // about the most is constant RHS.
693 unsigned VSize = V->getType()->getScalarSizeInBits();
694 if (MaskedValueIsZero(I->getOperand(1),
695 APInt::getHighBitsSet(VSize, BitsToClear)))
696 return true;
697 }
698
699 // Otherwise, we don't know how to analyze this BitsToClear case yet.
Chris Lattner789162a2010-01-11 03:32:00 +0000700 return false;
Chris Lattnerd26c9e12010-01-10 02:22:12 +0000701
Chris Lattner789162a2010-01-11 03:32:00 +0000702 case Instruction::LShr:
703 // We can promote lshr(x, cst) if we can promote x. This requires the
704 // ultimate 'and' to clear out the high zero bits we're clearing out though.
705 if (ConstantInt *Amt = dyn_cast<ConstantInt>(I->getOperand(1))) {
706 if (!CanEvaluateZExtd(I->getOperand(0), Ty, BitsToClear))
707 return false;
708 BitsToClear += Amt->getZExtValue();
709 if (BitsToClear > V->getType()->getScalarSizeInBits())
710 BitsToClear = V->getType()->getScalarSizeInBits();
711 return true;
712 }
713 // Cannot promote variable LSHR.
714 return false;
Chris Lattner75215c92010-01-10 00:58:42 +0000715 case Instruction::Select:
Chris Lattner789162a2010-01-11 03:32:00 +0000716 if (!CanEvaluateZExtd(I->getOperand(1), Ty, Tmp) ||
717 !CanEvaluateZExtd(I->getOperand(2), Ty, BitsToClear) ||
Chris Lattner7acc4b12010-01-11 04:05:13 +0000718 // TODO: If important, we could handle the case when the BitsToClear are
719 // known zero in the disagreeing side.
Chris Lattner789162a2010-01-11 03:32:00 +0000720 Tmp != BitsToClear)
721 return false;
722 return true;
Chris Lattner75215c92010-01-10 00:58:42 +0000723
724 case Instruction::PHI: {
725 // We can change a phi if we can change all operands. Note that we never
726 // get into trouble with cyclic PHIs here because we only consider
727 // instructions with a single use.
728 PHINode *PN = cast<PHINode>(I);
Chris Lattner789162a2010-01-11 03:32:00 +0000729 if (!CanEvaluateZExtd(PN->getIncomingValue(0), Ty, BitsToClear))
730 return false;
Chris Lattner9e390dd2010-01-10 02:50:04 +0000731 for (unsigned i = 1, e = PN->getNumIncomingValues(); i != e; ++i)
Chris Lattner789162a2010-01-11 03:32:00 +0000732 if (!CanEvaluateZExtd(PN->getIncomingValue(i), Ty, Tmp) ||
Chris Lattner7acc4b12010-01-11 04:05:13 +0000733 // TODO: If important, we could handle the case when the BitsToClear
734 // are known zero in the disagreeing input.
Chris Lattner789162a2010-01-11 03:32:00 +0000735 Tmp != BitsToClear)
736 return false;
Chris Lattner9e390dd2010-01-10 02:50:04 +0000737 return true;
Chris Lattner75215c92010-01-10 00:58:42 +0000738 }
739 default:
740 // TODO: Can handle more cases here.
Chris Lattner9e390dd2010-01-10 02:50:04 +0000741 return false;
Chris Lattner75215c92010-01-10 00:58:42 +0000742 }
743}
744
Chris Lattner80f43d32010-01-04 07:53:58 +0000745Instruction *InstCombiner::visitZExt(ZExtInst &CI) {
Chris Lattner5324d802010-01-10 02:39:31 +0000746 // If this zero extend is only used by a truncate, let the truncate by
747 // eliminated before we try to optimize this zext.
748 if (CI.hasOneUse() && isa<TruncInst>(CI.use_back()))
749 return 0;
750
Chris Lattner80f43d32010-01-04 07:53:58 +0000751 // If one of the common conversion will work, do it.
Chris Lattnerd84dfa42010-01-10 01:00:46 +0000752 if (Instruction *Result = commonCastTransforms(CI))
Chris Lattner80f43d32010-01-04 07:53:58 +0000753 return Result;
754
Chris Lattnerd84dfa42010-01-10 01:00:46 +0000755 // See if we can simplify any instructions used by the input whose sole
756 // purpose is to compute bits we don't care about.
757 if (SimplifyDemandedInstructionBits(CI))
758 return &CI;
Chris Lattner75215c92010-01-10 00:58:42 +0000759
Chris Lattnerd84dfa42010-01-10 01:00:46 +0000760 Value *Src = CI.getOperand(0);
Chris Lattnerdb125cf2011-07-18 04:54:35 +0000761 Type *SrcTy = Src->getType(), *DestTy = CI.getType();
Chris Lattner75215c92010-01-10 00:58:42 +0000762
763 // Attempt to extend the entire input expression tree to the destination
764 // type. Only do this if the dest type is a simple type, don't convert the
765 // expression tree to something weird like i93 unless the source is also
766 // strange.
Chris Lattner789162a2010-01-11 03:32:00 +0000767 unsigned BitsToClear;
Duncan Sands1df98592010-02-16 11:11:14 +0000768 if ((DestTy->isVectorTy() || ShouldChangeType(SrcTy, DestTy)) &&
Chris Lattner789162a2010-01-11 03:32:00 +0000769 CanEvaluateZExtd(Src, DestTy, BitsToClear)) {
770 assert(BitsToClear < SrcTy->getScalarSizeInBits() &&
771 "Unreasonable BitsToClear");
772
Chris Lattner5324d802010-01-10 02:39:31 +0000773 // Okay, we can transform this! Insert the new expression now.
774 DEBUG(dbgs() << "ICE: EvaluateInDifferentType converting expression type"
775 " to avoid zero extend: " << CI);
776 Value *Res = EvaluateInDifferentType(Src, DestTy, false);
777 assert(Res->getType() == DestTy);
778
Chris Lattner789162a2010-01-11 03:32:00 +0000779 uint32_t SrcBitsKept = SrcTy->getScalarSizeInBits()-BitsToClear;
780 uint32_t DestBitSize = DestTy->getScalarSizeInBits();
781
Chris Lattner5324d802010-01-10 02:39:31 +0000782 // If the high bits are already filled with zeros, just replace this
783 // cast with the result.
Chris Lattner9e390dd2010-01-10 02:50:04 +0000784 if (MaskedValueIsZero(Res, APInt::getHighBitsSet(DestBitSize,
Chris Lattner789162a2010-01-11 03:32:00 +0000785 DestBitSize-SrcBitsKept)))
Chris Lattner5324d802010-01-10 02:39:31 +0000786 return ReplaceInstUsesWith(CI, Res);
787
788 // We need to emit an AND to clear the high bits.
Chris Lattner9ee947c2010-01-10 20:25:54 +0000789 Constant *C = ConstantInt::get(Res->getType(),
Chris Lattner789162a2010-01-11 03:32:00 +0000790 APInt::getLowBitsSet(DestBitSize, SrcBitsKept));
Chris Lattner5324d802010-01-10 02:39:31 +0000791 return BinaryOperator::CreateAnd(Res, C);
Chris Lattner75215c92010-01-10 00:58:42 +0000792 }
Chris Lattner80f43d32010-01-04 07:53:58 +0000793
794 // If this is a TRUNC followed by a ZEXT then we are dealing with integral
795 // types and if the sizes are just right we can convert this into a logical
796 // 'and' which will be much cheaper than the pair of casts.
797 if (TruncInst *CSrc = dyn_cast<TruncInst>(Src)) { // A->B->C cast
Chris Lattnerf4fb9112010-01-10 07:08:30 +0000798 // TODO: Subsume this into EvaluateInDifferentType.
799
Chris Lattner80f43d32010-01-04 07:53:58 +0000800 // Get the sizes of the types involved. We know that the intermediate type
801 // will be smaller than A or C, but don't know the relation between A and C.
802 Value *A = CSrc->getOperand(0);
803 unsigned SrcSize = A->getType()->getScalarSizeInBits();
804 unsigned MidSize = CSrc->getType()->getScalarSizeInBits();
805 unsigned DstSize = CI.getType()->getScalarSizeInBits();
806 // If we're actually extending zero bits, then if
807 // SrcSize < DstSize: zext(a & mask)
808 // SrcSize == DstSize: a & mask
809 // SrcSize > DstSize: trunc(a) & mask
810 if (SrcSize < DstSize) {
811 APInt AndValue(APInt::getLowBitsSet(SrcSize, MidSize));
812 Constant *AndConst = ConstantInt::get(A->getType(), AndValue);
813 Value *And = Builder->CreateAnd(A, AndConst, CSrc->getName()+".mask");
814 return new ZExtInst(And, CI.getType());
815 }
816
817 if (SrcSize == DstSize) {
818 APInt AndValue(APInt::getLowBitsSet(SrcSize, MidSize));
819 return BinaryOperator::CreateAnd(A, ConstantInt::get(A->getType(),
820 AndValue));
821 }
822 if (SrcSize > DstSize) {
Benjamin Kramera9390a42011-09-27 20:39:19 +0000823 Value *Trunc = Builder->CreateTrunc(A, CI.getType());
Chris Lattner80f43d32010-01-04 07:53:58 +0000824 APInt AndValue(APInt::getLowBitsSet(DstSize, MidSize));
825 return BinaryOperator::CreateAnd(Trunc,
826 ConstantInt::get(Trunc->getType(),
Chris Lattnerf4fb9112010-01-10 07:08:30 +0000827 AndValue));
Chris Lattner80f43d32010-01-04 07:53:58 +0000828 }
829 }
830
831 if (ICmpInst *ICI = dyn_cast<ICmpInst>(Src))
832 return transformZExtICmp(ICI, CI);
833
834 BinaryOperator *SrcI = dyn_cast<BinaryOperator>(Src);
835 if (SrcI && SrcI->getOpcode() == Instruction::Or) {
836 // zext (or icmp, icmp) --> or (zext icmp), (zext icmp) if at least one
837 // of the (zext icmp) will be transformed.
838 ICmpInst *LHS = dyn_cast<ICmpInst>(SrcI->getOperand(0));
839 ICmpInst *RHS = dyn_cast<ICmpInst>(SrcI->getOperand(1));
840 if (LHS && RHS && LHS->hasOneUse() && RHS->hasOneUse() &&
841 (transformZExtICmp(LHS, CI, false) ||
842 transformZExtICmp(RHS, CI, false))) {
843 Value *LCast = Builder->CreateZExt(LHS, CI.getType(), LHS->getName());
844 Value *RCast = Builder->CreateZExt(RHS, CI.getType(), RHS->getName());
845 return BinaryOperator::Create(Instruction::Or, LCast, RCast);
846 }
847 }
848
849 // zext(trunc(t) & C) -> (t & zext(C)).
850 if (SrcI && SrcI->getOpcode() == Instruction::And && SrcI->hasOneUse())
851 if (ConstantInt *C = dyn_cast<ConstantInt>(SrcI->getOperand(1)))
852 if (TruncInst *TI = dyn_cast<TruncInst>(SrcI->getOperand(0))) {
853 Value *TI0 = TI->getOperand(0);
854 if (TI0->getType() == CI.getType())
855 return
856 BinaryOperator::CreateAnd(TI0,
857 ConstantExpr::getZExt(C, CI.getType()));
858 }
859
860 // zext((trunc(t) & C) ^ C) -> ((t & zext(C)) ^ zext(C)).
861 if (SrcI && SrcI->getOpcode() == Instruction::Xor && SrcI->hasOneUse())
862 if (ConstantInt *C = dyn_cast<ConstantInt>(SrcI->getOperand(1)))
863 if (BinaryOperator *And = dyn_cast<BinaryOperator>(SrcI->getOperand(0)))
864 if (And->getOpcode() == Instruction::And && And->hasOneUse() &&
865 And->getOperand(1) == C)
866 if (TruncInst *TI = dyn_cast<TruncInst>(And->getOperand(0))) {
867 Value *TI0 = TI->getOperand(0);
868 if (TI0->getType() == CI.getType()) {
869 Constant *ZC = ConstantExpr::getZExt(C, CI.getType());
Benjamin Kramera9390a42011-09-27 20:39:19 +0000870 Value *NewAnd = Builder->CreateAnd(TI0, ZC);
Chris Lattner80f43d32010-01-04 07:53:58 +0000871 return BinaryOperator::CreateXor(NewAnd, ZC);
872 }
873 }
874
Chris Lattner718bf3f2010-01-05 21:04:47 +0000875 // zext (xor i1 X, true) to i32 --> xor (zext i1 X to i32), 1
876 Value *X;
Duncan Sandsb0bc6c32010-02-15 16:12:20 +0000877 if (SrcI && SrcI->hasOneUse() && SrcI->getType()->isIntegerTy(1) &&
Chris Lattner49bdfef2010-01-05 21:11:17 +0000878 match(SrcI, m_Not(m_Value(X))) &&
Chris Lattner718bf3f2010-01-05 21:04:47 +0000879 (!X->hasOneUse() || !isa<CmpInst>(X))) {
880 Value *New = Builder->CreateZExt(X, CI.getType());
881 return BinaryOperator::CreateXor(New, ConstantInt::get(CI.getType(), 1));
882 }
883
Chris Lattner80f43d32010-01-04 07:53:58 +0000884 return 0;
885}
886
Benjamin Kramer0a30c422011-04-01 20:09:03 +0000887/// transformSExtICmp - Transform (sext icmp) to bitwise / integer operations
888/// in order to eliminate the icmp.
889Instruction *InstCombiner::transformSExtICmp(ICmpInst *ICI, Instruction &CI) {
890 Value *Op0 = ICI->getOperand(0), *Op1 = ICI->getOperand(1);
891 ICmpInst::Predicate Pred = ICI->getPredicate();
892
893 if (ConstantInt *Op1C = dyn_cast<ConstantInt>(Op1)) {
Benjamin Kramer406a6502011-04-01 22:29:18 +0000894 // (x <s 0) ? -1 : 0 -> ashr x, 31 -> all ones if negative
895 // (x >s -1) ? -1 : 0 -> not (ashr x, 31) -> all ones if positive
Benjamin Kramer0a30c422011-04-01 20:09:03 +0000896 if ((Pred == ICmpInst::ICMP_SLT && Op1C->isZero()) ||
897 (Pred == ICmpInst::ICMP_SGT && Op1C->isAllOnesValue())) {
898
899 Value *Sh = ConstantInt::get(Op0->getType(),
900 Op0->getType()->getScalarSizeInBits()-1);
901 Value *In = Builder->CreateAShr(Op0, Sh, Op0->getName()+".lobit");
902 if (In->getType() != CI.getType())
Benjamin Kramera9390a42011-09-27 20:39:19 +0000903 In = Builder->CreateIntCast(In, CI.getType(), true/*SExt*/);
Benjamin Kramer0a30c422011-04-01 20:09:03 +0000904
905 if (Pred == ICmpInst::ICMP_SGT)
906 In = Builder->CreateNot(In, In->getName()+".not");
907 return ReplaceInstUsesWith(CI, In);
908 }
Benjamin Kramer0baa94a2011-04-01 20:09:10 +0000909
910 // If we know that only one bit of the LHS of the icmp can be set and we
911 // have an equality comparison with zero or a power of 2, we can transform
912 // the icmp and sext into bitwise/integer operations.
Benjamin Kramer5337fab2011-04-01 22:22:11 +0000913 if (ICI->hasOneUse() &&
914 ICI->isEquality() && (Op1C->isZero() || Op1C->getValue().isPowerOf2())){
Benjamin Kramer0baa94a2011-04-01 20:09:10 +0000915 unsigned BitWidth = Op1C->getType()->getBitWidth();
916 APInt KnownZero(BitWidth, 0), KnownOne(BitWidth, 0);
917 APInt TypeMask(APInt::getAllOnesValue(BitWidth));
918 ComputeMaskedBits(Op0, TypeMask, KnownZero, KnownOne);
919
Benjamin Kramerce1498b2011-04-01 20:15:16 +0000920 APInt KnownZeroMask(~KnownZero);
921 if (KnownZeroMask.isPowerOf2()) {
Benjamin Kramer0baa94a2011-04-01 20:09:10 +0000922 Value *In = ICI->getOperand(0);
923
Benjamin Kramerf5b75932011-04-02 18:50:58 +0000924 // If the icmp tests for a known zero bit we can constant fold it.
925 if (!Op1C->isZero() && Op1C->getValue() != KnownZeroMask) {
926 Value *V = Pred == ICmpInst::ICMP_NE ?
927 ConstantInt::getAllOnesValue(CI.getType()) :
928 ConstantInt::getNullValue(CI.getType());
929 return ReplaceInstUsesWith(CI, V);
930 }
Benjamin Kramer5337fab2011-04-01 22:22:11 +0000931
Benjamin Kramer0baa94a2011-04-01 20:09:10 +0000932 if (!Op1C->isZero() == (Pred == ICmpInst::ICMP_NE)) {
933 // sext ((x & 2^n) == 0) -> (x >> n) - 1
934 // sext ((x & 2^n) != 2^n) -> (x >> n) - 1
935 unsigned ShiftAmt = KnownZeroMask.countTrailingZeros();
936 // Perform a right shift to place the desired bit in the LSB.
937 if (ShiftAmt)
938 In = Builder->CreateLShr(In,
939 ConstantInt::get(In->getType(), ShiftAmt));
940
941 // At this point "In" is either 1 or 0. Subtract 1 to turn
942 // {1, 0} -> {0, -1}.
943 In = Builder->CreateAdd(In,
944 ConstantInt::getAllOnesValue(In->getType()),
945 "sext");
946 } else {
947 // sext ((x & 2^n) != 0) -> (x << bitwidth-n) a>> bitwidth-1
Benjamin Kramer5337fab2011-04-01 22:22:11 +0000948 // sext ((x & 2^n) == 2^n) -> (x << bitwidth-n) a>> bitwidth-1
Benjamin Kramer0baa94a2011-04-01 20:09:10 +0000949 unsigned ShiftAmt = KnownZeroMask.countLeadingZeros();
950 // Perform a left shift to place the desired bit in the MSB.
951 if (ShiftAmt)
952 In = Builder->CreateShl(In,
953 ConstantInt::get(In->getType(), ShiftAmt));
954
955 // Distribute the bit over the whole bit width.
956 In = Builder->CreateAShr(In, ConstantInt::get(In->getType(),
957 BitWidth - 1), "sext");
958 }
959
960 if (CI.getType() == In->getType())
961 return ReplaceInstUsesWith(CI, In);
962 return CastInst::CreateIntegerCast(In, CI.getType(), true/*SExt*/);
963 }
964 }
Benjamin Kramer0a30c422011-04-01 20:09:03 +0000965 }
966
967 // vector (x <s 0) ? -1 : 0 -> ashr x, 31 -> all ones if signed.
Chris Lattnerdb125cf2011-07-18 04:54:35 +0000968 if (VectorType *VTy = dyn_cast<VectorType>(CI.getType())) {
Benjamin Kramer0a30c422011-04-01 20:09:03 +0000969 if (Pred == ICmpInst::ICMP_SLT && match(Op1, m_Zero()) &&
970 Op0->getType() == CI.getType()) {
Chris Lattnerdb125cf2011-07-18 04:54:35 +0000971 Type *EltTy = VTy->getElementType();
Benjamin Kramer0a30c422011-04-01 20:09:03 +0000972
973 // splat the shift constant to a constant vector.
974 Constant *VSh = ConstantInt::get(VTy, EltTy->getScalarSizeInBits()-1);
975 Value *In = Builder->CreateAShr(Op0, VSh, Op0->getName()+".lobit");
976 return ReplaceInstUsesWith(CI, In);
977 }
978 }
979
980 return 0;
981}
982
Chris Lattner75215c92010-01-10 00:58:42 +0000983/// CanEvaluateSExtd - Return true if we can take the specified value
984/// and return it as type Ty without inserting any new casts and without
985/// changing the value of the common low bits. This is used by code that tries
986/// to promote integer operations to a wider types will allow us to eliminate
987/// the extension.
988///
Chris Lattneraa9c8942010-01-10 07:57:20 +0000989/// This function works on both vectors and scalars.
Chris Lattner75215c92010-01-10 00:58:42 +0000990///
Chris Lattnerdb125cf2011-07-18 04:54:35 +0000991static bool CanEvaluateSExtd(Value *V, Type *Ty) {
Chris Lattner75215c92010-01-10 00:58:42 +0000992 assert(V->getType()->getScalarSizeInBits() < Ty->getScalarSizeInBits() &&
993 "Can't sign extend type to a smaller type");
Chris Lattneraa9c8942010-01-10 07:57:20 +0000994 // If this is a constant, it can be trivially promoted.
995 if (isa<Constant>(V))
996 return true;
Chris Lattner75215c92010-01-10 00:58:42 +0000997
998 Instruction *I = dyn_cast<Instruction>(V);
Chris Lattneraa9c8942010-01-10 07:57:20 +0000999 if (!I) return false;
Chris Lattner75215c92010-01-10 00:58:42 +00001000
Chris Lattnera958cbf2010-01-11 22:45:25 +00001001 // If this is a truncate from the dest type, we can trivially eliminate it,
1002 // even if it has multiple uses.
1003 // FIXME: This is currently disabled until codegen can handle this without
1004 // pessimizing code, PR5997.
1005 if (0 && isa<TruncInst>(I) && I->getOperand(0)->getType() == Ty)
Chris Lattneraa9c8942010-01-10 07:57:20 +00001006 return true;
Chris Lattner75215c92010-01-10 00:58:42 +00001007
1008 // We can't extend or shrink something that has multiple uses: doing so would
1009 // require duplicating the instruction in general, which isn't profitable.
Chris Lattneraa9c8942010-01-10 07:57:20 +00001010 if (!I->hasOneUse()) return false;
Chris Lattner75215c92010-01-10 00:58:42 +00001011
Chris Lattneraa9c8942010-01-10 07:57:20 +00001012 switch (I->getOpcode()) {
Chris Lattner11ea8122010-01-10 20:30:41 +00001013 case Instruction::SExt: // sext(sext(x)) -> sext(x)
1014 case Instruction::ZExt: // sext(zext(x)) -> zext(x)
1015 case Instruction::Trunc: // sext(trunc(x)) -> trunc(x) or sext(x)
1016 return true;
Chris Lattner75215c92010-01-10 00:58:42 +00001017 case Instruction::And:
1018 case Instruction::Or:
1019 case Instruction::Xor:
Chris Lattner75215c92010-01-10 00:58:42 +00001020 case Instruction::Add:
1021 case Instruction::Sub:
Chris Lattner75215c92010-01-10 00:58:42 +00001022 case Instruction::Mul:
Chris Lattneraa9c8942010-01-10 07:57:20 +00001023 // These operators can all arbitrarily be extended if their inputs can.
Chris Lattner8cf4f6f2010-01-11 02:43:35 +00001024 return CanEvaluateSExtd(I->getOperand(0), Ty) &&
1025 CanEvaluateSExtd(I->getOperand(1), Ty);
Chris Lattner75215c92010-01-10 00:58:42 +00001026
1027 //case Instruction::Shl: TODO
1028 //case Instruction::LShr: TODO
Chris Lattner75215c92010-01-10 00:58:42 +00001029
Chris Lattneraa9c8942010-01-10 07:57:20 +00001030 case Instruction::Select:
Chris Lattner8cf4f6f2010-01-11 02:43:35 +00001031 return CanEvaluateSExtd(I->getOperand(1), Ty) &&
1032 CanEvaluateSExtd(I->getOperand(2), Ty);
Chris Lattner9ee947c2010-01-10 20:25:54 +00001033
Chris Lattner75215c92010-01-10 00:58:42 +00001034 case Instruction::PHI: {
1035 // We can change a phi if we can change all operands. Note that we never
1036 // get into trouble with cyclic PHIs here because we only consider
1037 // instructions with a single use.
1038 PHINode *PN = cast<PHINode>(I);
Chris Lattner9ee947c2010-01-10 20:25:54 +00001039 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i)
Chris Lattner8cf4f6f2010-01-11 02:43:35 +00001040 if (!CanEvaluateSExtd(PN->getIncomingValue(i), Ty)) return false;
Chris Lattneraa9c8942010-01-10 07:57:20 +00001041 return true;
Chris Lattner75215c92010-01-10 00:58:42 +00001042 }
1043 default:
1044 // TODO: Can handle more cases here.
1045 break;
1046 }
1047
Chris Lattneraa9c8942010-01-10 07:57:20 +00001048 return false;
Chris Lattner75215c92010-01-10 00:58:42 +00001049}
1050
Chris Lattner80f43d32010-01-04 07:53:58 +00001051Instruction *InstCombiner::visitSExt(SExtInst &CI) {
Chris Lattner5324d802010-01-10 02:39:31 +00001052 // If this sign extend is only used by a truncate, let the truncate by
1053 // eliminated before we try to optimize this zext.
1054 if (CI.hasOneUse() && isa<TruncInst>(CI.use_back()))
1055 return 0;
1056
Chris Lattnerd84dfa42010-01-10 01:00:46 +00001057 if (Instruction *I = commonCastTransforms(CI))
Chris Lattner80f43d32010-01-04 07:53:58 +00001058 return I;
1059
Chris Lattnerd84dfa42010-01-10 01:00:46 +00001060 // See if we can simplify any instructions used by the input whose sole
1061 // purpose is to compute bits we don't care about.
1062 if (SimplifyDemandedInstructionBits(CI))
1063 return &CI;
1064
Chris Lattner80f43d32010-01-04 07:53:58 +00001065 Value *Src = CI.getOperand(0);
Chris Lattnerdb125cf2011-07-18 04:54:35 +00001066 Type *SrcTy = Src->getType(), *DestTy = CI.getType();
Chris Lattner75215c92010-01-10 00:58:42 +00001067
Chris Lattner75215c92010-01-10 00:58:42 +00001068 // Attempt to extend the entire input expression tree to the destination
1069 // type. Only do this if the dest type is a simple type, don't convert the
1070 // expression tree to something weird like i93 unless the source is also
1071 // strange.
Duncan Sands1df98592010-02-16 11:11:14 +00001072 if ((DestTy->isVectorTy() || ShouldChangeType(SrcTy, DestTy)) &&
Chris Lattner8cf4f6f2010-01-11 02:43:35 +00001073 CanEvaluateSExtd(Src, DestTy)) {
Chris Lattnerdde5ee52010-01-10 07:40:50 +00001074 // Okay, we can transform this! Insert the new expression now.
1075 DEBUG(dbgs() << "ICE: EvaluateInDifferentType converting expression type"
1076 " to avoid sign extend: " << CI);
1077 Value *Res = EvaluateInDifferentType(Src, DestTy, true);
1078 assert(Res->getType() == DestTy);
1079
Chris Lattner75215c92010-01-10 00:58:42 +00001080 uint32_t SrcBitSize = SrcTy->getScalarSizeInBits();
1081 uint32_t DestBitSize = DestTy->getScalarSizeInBits();
Chris Lattnerdde5ee52010-01-10 07:40:50 +00001082
1083 // If the high bits are already filled with sign bit, just replace this
1084 // cast with the result.
Chris Lattneraa9c8942010-01-10 07:57:20 +00001085 if (ComputeNumSignBits(Res) > DestBitSize - SrcBitSize)
Chris Lattnerdde5ee52010-01-10 07:40:50 +00001086 return ReplaceInstUsesWith(CI, Res);
Chris Lattner75215c92010-01-10 00:58:42 +00001087
Chris Lattnerdde5ee52010-01-10 07:40:50 +00001088 // We need to emit a shl + ashr to do the sign extend.
1089 Value *ShAmt = ConstantInt::get(DestTy, DestBitSize-SrcBitSize);
1090 return BinaryOperator::CreateAShr(Builder->CreateShl(Res, ShAmt, "sext"),
1091 ShAmt);
Chris Lattner75215c92010-01-10 00:58:42 +00001092 }
Chris Lattner80f43d32010-01-04 07:53:58 +00001093
Chris Lattnercd5adbb2010-01-18 22:19:16 +00001094 // If this input is a trunc from our destination, then turn sext(trunc(x))
1095 // into shifts.
1096 if (TruncInst *TI = dyn_cast<TruncInst>(Src))
1097 if (TI->hasOneUse() && TI->getOperand(0)->getType() == DestTy) {
1098 uint32_t SrcBitSize = SrcTy->getScalarSizeInBits();
1099 uint32_t DestBitSize = DestTy->getScalarSizeInBits();
1100
1101 // We need to emit a shl + ashr to do the sign extend.
1102 Value *ShAmt = ConstantInt::get(DestTy, DestBitSize-SrcBitSize);
1103 Value *Res = Builder->CreateShl(TI->getOperand(0), ShAmt, "sext");
1104 return BinaryOperator::CreateAShr(Res, ShAmt);
1105 }
Nate Begeman9a3dc552010-12-17 23:12:19 +00001106
Benjamin Kramer0a30c422011-04-01 20:09:03 +00001107 if (ICmpInst *ICI = dyn_cast<ICmpInst>(Src))
1108 return transformSExtICmp(ICI, CI);
Bill Wendling2d0537c2010-12-17 23:27:41 +00001109
Chris Lattner80f43d32010-01-04 07:53:58 +00001110 // If the input is a shl/ashr pair of a same constant, then this is a sign
1111 // extension from a smaller value. If we could trust arbitrary bitwidth
1112 // integers, we could turn this into a truncate to the smaller bit and then
1113 // use a sext for the whole extension. Since we don't, look deeper and check
1114 // for a truncate. If the source and dest are the same type, eliminate the
1115 // trunc and extend and just do shifts. For example, turn:
1116 // %a = trunc i32 %i to i8
1117 // %b = shl i8 %a, 6
1118 // %c = ashr i8 %b, 6
1119 // %d = sext i8 %c to i32
1120 // into:
1121 // %a = shl i32 %i, 30
1122 // %d = ashr i32 %a, 30
1123 Value *A = 0;
Chris Lattner4f379782010-01-10 01:04:31 +00001124 // TODO: Eventually this could be subsumed by EvaluateInDifferentType.
Chris Lattner80f43d32010-01-04 07:53:58 +00001125 ConstantInt *BA = 0, *CA = 0;
Chris Lattner4f379782010-01-10 01:04:31 +00001126 if (match(Src, m_AShr(m_Shl(m_Trunc(m_Value(A)), m_ConstantInt(BA)),
Chris Lattner80f43d32010-01-04 07:53:58 +00001127 m_ConstantInt(CA))) &&
Chris Lattner4f379782010-01-10 01:04:31 +00001128 BA == CA && A->getType() == CI.getType()) {
1129 unsigned MidSize = Src->getType()->getScalarSizeInBits();
1130 unsigned SrcDstSize = CI.getType()->getScalarSizeInBits();
1131 unsigned ShAmt = CA->getZExtValue()+SrcDstSize-MidSize;
1132 Constant *ShAmtV = ConstantInt::get(CI.getType(), ShAmt);
1133 A = Builder->CreateShl(A, ShAmtV, CI.getName());
1134 return BinaryOperator::CreateAShr(A, ShAmtV);
Chris Lattner80f43d32010-01-04 07:53:58 +00001135 }
1136
1137 return 0;
1138}
1139
1140
1141/// FitsInFPType - Return a Constant* for the specified FP constant if it fits
1142/// in the specified FP type without changing its value.
1143static Constant *FitsInFPType(ConstantFP *CFP, const fltSemantics &Sem) {
1144 bool losesInfo;
1145 APFloat F = CFP->getValueAPF();
1146 (void)F.convert(Sem, APFloat::rmNearestTiesToEven, &losesInfo);
1147 if (!losesInfo)
1148 return ConstantFP::get(CFP->getContext(), F);
1149 return 0;
1150}
1151
1152/// LookThroughFPExtensions - If this is an fp extension instruction, look
1153/// through it until we get the source value.
1154static Value *LookThroughFPExtensions(Value *V) {
1155 if (Instruction *I = dyn_cast<Instruction>(V))
1156 if (I->getOpcode() == Instruction::FPExt)
1157 return LookThroughFPExtensions(I->getOperand(0));
1158
1159 // If this value is a constant, return the constant in the smallest FP type
1160 // that can accurately represent it. This allows us to turn
1161 // (float)((double)X+2.0) into x+2.0f.
1162 if (ConstantFP *CFP = dyn_cast<ConstantFP>(V)) {
1163 if (CFP->getType() == Type::getPPC_FP128Ty(V->getContext()))
1164 return V; // No constant folding of this.
1165 // See if the value can be truncated to float and then reextended.
1166 if (Value *V = FitsInFPType(CFP, APFloat::IEEEsingle))
1167 return V;
Benjamin Kramerf0127052010-01-05 13:12:22 +00001168 if (CFP->getType()->isDoubleTy())
Chris Lattner80f43d32010-01-04 07:53:58 +00001169 return V; // Won't shrink.
1170 if (Value *V = FitsInFPType(CFP, APFloat::IEEEdouble))
1171 return V;
1172 // Don't try to shrink to various long double types.
1173 }
1174
1175 return V;
1176}
1177
1178Instruction *InstCombiner::visitFPTrunc(FPTruncInst &CI) {
1179 if (Instruction *I = commonCastTransforms(CI))
1180 return I;
1181
1182 // If we have fptrunc(fadd (fpextend x), (fpextend y)), where x and y are
1183 // smaller than the destination type, we can eliminate the truncate by doing
1184 // the add as the smaller type. This applies to fadd/fsub/fmul/fdiv as well
1185 // as many builtins (sqrt, etc).
1186 BinaryOperator *OpI = dyn_cast<BinaryOperator>(CI.getOperand(0));
1187 if (OpI && OpI->hasOneUse()) {
1188 switch (OpI->getOpcode()) {
1189 default: break;
1190 case Instruction::FAdd:
1191 case Instruction::FSub:
1192 case Instruction::FMul:
1193 case Instruction::FDiv:
1194 case Instruction::FRem:
Chris Lattnerdb125cf2011-07-18 04:54:35 +00001195 Type *SrcTy = OpI->getType();
Chris Lattner80f43d32010-01-04 07:53:58 +00001196 Value *LHSTrunc = LookThroughFPExtensions(OpI->getOperand(0));
1197 Value *RHSTrunc = LookThroughFPExtensions(OpI->getOperand(1));
1198 if (LHSTrunc->getType() != SrcTy &&
1199 RHSTrunc->getType() != SrcTy) {
1200 unsigned DstSize = CI.getType()->getScalarSizeInBits();
1201 // If the source types were both smaller than the destination type of
1202 // the cast, do this xform.
1203 if (LHSTrunc->getType()->getScalarSizeInBits() <= DstSize &&
1204 RHSTrunc->getType()->getScalarSizeInBits() <= DstSize) {
1205 LHSTrunc = Builder->CreateFPExt(LHSTrunc, CI.getType());
1206 RHSTrunc = Builder->CreateFPExt(RHSTrunc, CI.getType());
1207 return BinaryOperator::Create(OpI->getOpcode(), LHSTrunc, RHSTrunc);
1208 }
1209 }
1210 break;
1211 }
1212 }
Owen Andersond9029012010-07-19 08:09:34 +00001213
1214 // Fold (fptrunc (sqrt (fpext x))) -> (sqrtf x)
Chad Rosier3d925d22011-11-29 23:57:10 +00001215 const TargetLibraryInfo &TLI = getAnalysis<TargetLibraryInfo>();
Owen Andersond9029012010-07-19 08:09:34 +00001216 CallInst *Call = dyn_cast<CallInst>(CI.getOperand(0));
Chad Rosier3d925d22011-11-29 23:57:10 +00001217 if (Call && Call->getCalledFunction() && TLI.has(LibFunc::sqrtf) &&
1218 Call->getCalledFunction()->getName() == TLI.getName(LibFunc::sqrt) &&
Evan Cheng93a635c2011-07-13 19:08:16 +00001219 Call->getNumArgOperands() == 1 &&
1220 Call->hasOneUse()) {
Owen Andersond9029012010-07-19 08:09:34 +00001221 CastInst *Arg = dyn_cast<CastInst>(Call->getArgOperand(0));
1222 if (Arg && Arg->getOpcode() == Instruction::FPExt &&
Owen Anderson5f23a932010-07-19 19:23:32 +00001223 CI.getType()->isFloatTy() &&
1224 Call->getType()->isDoubleTy() &&
1225 Arg->getType()->isDoubleTy() &&
1226 Arg->getOperand(0)->getType()->isFloatTy()) {
1227 Function *Callee = Call->getCalledFunction();
1228 Module *M = CI.getParent()->getParent()->getParent();
Chris Lattner979ed442010-09-07 20:01:38 +00001229 Constant *SqrtfFunc = M->getOrInsertFunction("sqrtf",
Owen Anderson5f23a932010-07-19 19:23:32 +00001230 Callee->getAttributes(),
Owen Andersond9029012010-07-19 08:09:34 +00001231 Builder->getFloatTy(),
1232 Builder->getFloatTy(),
1233 NULL);
1234 CallInst *ret = CallInst::Create(SqrtfFunc, Arg->getOperand(0),
1235 "sqrtfcall");
Owen Anderson5f23a932010-07-19 19:23:32 +00001236 ret->setAttributes(Callee->getAttributes());
Chris Lattner979ed442010-09-07 20:01:38 +00001237
1238
1239 // Remove the old Call. With -fmath-errno, it won't get marked readnone.
Eli Friedman3e22cb92011-05-18 00:32:01 +00001240 ReplaceInstUsesWith(*Call, UndefValue::get(Call->getType()));
Chris Lattner979ed442010-09-07 20:01:38 +00001241 EraseInstFromFunction(*Call);
Owen Andersond9029012010-07-19 08:09:34 +00001242 return ret;
1243 }
1244 }
1245
Chris Lattner80f43d32010-01-04 07:53:58 +00001246 return 0;
1247}
1248
1249Instruction *InstCombiner::visitFPExt(CastInst &CI) {
1250 return commonCastTransforms(CI);
1251}
1252
1253Instruction *InstCombiner::visitFPToUI(FPToUIInst &FI) {
1254 Instruction *OpI = dyn_cast<Instruction>(FI.getOperand(0));
1255 if (OpI == 0)
1256 return commonCastTransforms(FI);
1257
1258 // fptoui(uitofp(X)) --> X
1259 // fptoui(sitofp(X)) --> X
1260 // This is safe if the intermediate type has enough bits in its mantissa to
1261 // accurately represent all values of X. For example, do not do this with
1262 // i64->float->i64. This is also safe for sitofp case, because any negative
1263 // 'X' value would cause an undefined result for the fptoui.
1264 if ((isa<UIToFPInst>(OpI) || isa<SIToFPInst>(OpI)) &&
1265 OpI->getOperand(0)->getType() == FI.getType() &&
1266 (int)FI.getType()->getScalarSizeInBits() < /*extra bit for sign */
1267 OpI->getType()->getFPMantissaWidth())
1268 return ReplaceInstUsesWith(FI, OpI->getOperand(0));
1269
1270 return commonCastTransforms(FI);
1271}
1272
1273Instruction *InstCombiner::visitFPToSI(FPToSIInst &FI) {
1274 Instruction *OpI = dyn_cast<Instruction>(FI.getOperand(0));
1275 if (OpI == 0)
1276 return commonCastTransforms(FI);
1277
1278 // fptosi(sitofp(X)) --> X
1279 // fptosi(uitofp(X)) --> X
1280 // This is safe if the intermediate type has enough bits in its mantissa to
1281 // accurately represent all values of X. For example, do not do this with
1282 // i64->float->i64. This is also safe for sitofp case, because any negative
1283 // 'X' value would cause an undefined result for the fptoui.
1284 if ((isa<UIToFPInst>(OpI) || isa<SIToFPInst>(OpI)) &&
1285 OpI->getOperand(0)->getType() == FI.getType() &&
1286 (int)FI.getType()->getScalarSizeInBits() <=
1287 OpI->getType()->getFPMantissaWidth())
1288 return ReplaceInstUsesWith(FI, OpI->getOperand(0));
1289
1290 return commonCastTransforms(FI);
1291}
1292
1293Instruction *InstCombiner::visitUIToFP(CastInst &CI) {
1294 return commonCastTransforms(CI);
1295}
1296
1297Instruction *InstCombiner::visitSIToFP(CastInst &CI) {
1298 return commonCastTransforms(CI);
1299}
1300
Chris Lattner80f43d32010-01-04 07:53:58 +00001301Instruction *InstCombiner::visitIntToPtr(IntToPtrInst &CI) {
Dan Gohman3b5487e2010-02-02 01:44:02 +00001302 // If the source integer type is not the intptr_t type for this target, do a
1303 // trunc or zext to the intptr_t type, then inttoptr of it. This allows the
1304 // cast to be exposed to other transforms.
1305 if (TD) {
1306 if (CI.getOperand(0)->getType()->getScalarSizeInBits() >
1307 TD->getPointerSizeInBits()) {
1308 Value *P = Builder->CreateTrunc(CI.getOperand(0),
Benjamin Kramera9390a42011-09-27 20:39:19 +00001309 TD->getIntPtrType(CI.getContext()));
Dan Gohman3b5487e2010-02-02 01:44:02 +00001310 return new IntToPtrInst(P, CI.getType());
1311 }
1312 if (CI.getOperand(0)->getType()->getScalarSizeInBits() <
1313 TD->getPointerSizeInBits()) {
1314 Value *P = Builder->CreateZExt(CI.getOperand(0),
Benjamin Kramera9390a42011-09-27 20:39:19 +00001315 TD->getIntPtrType(CI.getContext()));
Dan Gohman3b5487e2010-02-02 01:44:02 +00001316 return new IntToPtrInst(P, CI.getType());
1317 }
Chris Lattner80f43d32010-01-04 07:53:58 +00001318 }
1319
1320 if (Instruction *I = commonCastTransforms(CI))
1321 return I;
1322
1323 return 0;
1324}
1325
Chris Lattner7a34d6c2010-01-05 22:21:18 +00001326/// @brief Implement the transforms for cast of pointer (bitcast/ptrtoint)
1327Instruction *InstCombiner::commonPointerCastTransforms(CastInst &CI) {
1328 Value *Src = CI.getOperand(0);
1329
1330 if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(Src)) {
1331 // If casting the result of a getelementptr instruction with no offset, turn
1332 // this into a cast of the original pointer!
1333 if (GEP->hasAllZeroIndices()) {
1334 // Changing the cast operand is usually not a good idea but it is safe
1335 // here because the pointer operand is being replaced with another
1336 // pointer operand so the opcode doesn't need to change.
1337 Worklist.Add(GEP);
1338 CI.setOperand(0, GEP->getOperand(0));
1339 return &CI;
1340 }
1341
1342 // If the GEP has a single use, and the base pointer is a bitcast, and the
1343 // GEP computes a constant offset, see if we can convert these three
1344 // instructions into fewer. This typically happens with unions and other
1345 // non-type-safe code.
1346 if (TD && GEP->hasOneUse() && isa<BitCastInst>(GEP->getOperand(0)) &&
1347 GEP->hasAllConstantIndices()) {
1348 // We are guaranteed to get a constant from EmitGEPOffset.
1349 ConstantInt *OffsetV = cast<ConstantInt>(EmitGEPOffset(GEP));
1350 int64_t Offset = OffsetV->getSExtValue();
1351
1352 // Get the base pointer input of the bitcast, and the type it points to.
1353 Value *OrigBase = cast<BitCastInst>(GEP->getOperand(0))->getOperand(0);
Chris Lattnerdb125cf2011-07-18 04:54:35 +00001354 Type *GEPIdxTy =
Chris Lattner7a34d6c2010-01-05 22:21:18 +00001355 cast<PointerType>(OrigBase->getType())->getElementType();
1356 SmallVector<Value*, 8> NewIndices;
1357 if (FindElementAtOffset(GEPIdxTy, Offset, NewIndices)) {
1358 // If we were able to index down into an element, create the GEP
1359 // and bitcast the result. This eliminates one bitcast, potentially
1360 // two.
1361 Value *NGEP = cast<GEPOperator>(GEP)->isInBounds() ?
Jay Foad0a2a60a2011-07-22 08:16:57 +00001362 Builder->CreateInBoundsGEP(OrigBase, NewIndices) :
1363 Builder->CreateGEP(OrigBase, NewIndices);
Chris Lattner7a34d6c2010-01-05 22:21:18 +00001364 NGEP->takeName(GEP);
1365
1366 if (isa<BitCastInst>(CI))
1367 return new BitCastInst(NGEP, CI.getType());
1368 assert(isa<PtrToIntInst>(CI));
1369 return new PtrToIntInst(NGEP, CI.getType());
1370 }
1371 }
1372 }
1373
1374 return commonCastTransforms(CI);
1375}
1376
1377Instruction *InstCombiner::visitPtrToInt(PtrToIntInst &CI) {
Dan Gohman3b5487e2010-02-02 01:44:02 +00001378 // If the destination integer type is not the intptr_t type for this target,
1379 // do a ptrtoint to intptr_t then do a trunc or zext. This allows the cast
1380 // to be exposed to other transforms.
1381 if (TD) {
1382 if (CI.getType()->getScalarSizeInBits() < TD->getPointerSizeInBits()) {
1383 Value *P = Builder->CreatePtrToInt(CI.getOperand(0),
Benjamin Kramera9390a42011-09-27 20:39:19 +00001384 TD->getIntPtrType(CI.getContext()));
Dan Gohman3b5487e2010-02-02 01:44:02 +00001385 return new TruncInst(P, CI.getType());
1386 }
1387 if (CI.getType()->getScalarSizeInBits() > TD->getPointerSizeInBits()) {
1388 Value *P = Builder->CreatePtrToInt(CI.getOperand(0),
Benjamin Kramera9390a42011-09-27 20:39:19 +00001389 TD->getIntPtrType(CI.getContext()));
Dan Gohman3b5487e2010-02-02 01:44:02 +00001390 return new ZExtInst(P, CI.getType());
1391 }
Chris Lattner7a34d6c2010-01-05 22:21:18 +00001392 }
1393
1394 return commonPointerCastTransforms(CI);
1395}
1396
Chris Lattner67451912010-05-08 21:50:26 +00001397/// OptimizeVectorResize - This input value (which is known to have vector type)
1398/// is being zero extended or truncated to the specified vector type. Try to
1399/// replace it with a shuffle (and vector/vector bitcast) if possible.
1400///
1401/// The source and destination vector types may have different element types.
Chris Lattnerdb125cf2011-07-18 04:54:35 +00001402static Instruction *OptimizeVectorResize(Value *InVal, VectorType *DestTy,
Chris Lattner67451912010-05-08 21:50:26 +00001403 InstCombiner &IC) {
1404 // We can only do this optimization if the output is a multiple of the input
1405 // element size, or the input is a multiple of the output element size.
1406 // Convert the input type to have the same element type as the output.
Chris Lattnerdb125cf2011-07-18 04:54:35 +00001407 VectorType *SrcTy = cast<VectorType>(InVal->getType());
Chris Lattner67451912010-05-08 21:50:26 +00001408
1409 if (SrcTy->getElementType() != DestTy->getElementType()) {
1410 // The input types don't need to be identical, but for now they must be the
1411 // same size. There is no specific reason we couldn't handle things like
1412 // <4 x i16> -> <4 x i32> by bitcasting to <2 x i32> but haven't gotten
1413 // there yet.
1414 if (SrcTy->getElementType()->getPrimitiveSizeInBits() !=
1415 DestTy->getElementType()->getPrimitiveSizeInBits())
1416 return 0;
1417
1418 SrcTy = VectorType::get(DestTy->getElementType(), SrcTy->getNumElements());
1419 InVal = IC.Builder->CreateBitCast(InVal, SrcTy);
1420 }
1421
1422 // Now that the element types match, get the shuffle mask and RHS of the
1423 // shuffle to use, which depends on whether we're increasing or decreasing the
1424 // size of the input.
1425 SmallVector<Constant*, 16> ShuffleMask;
1426 Value *V2;
Chris Lattnerdb125cf2011-07-18 04:54:35 +00001427 IntegerType *Int32Ty = Type::getInt32Ty(SrcTy->getContext());
Chris Lattner67451912010-05-08 21:50:26 +00001428
1429 if (SrcTy->getNumElements() > DestTy->getNumElements()) {
1430 // If we're shrinking the number of elements, just shuffle in the low
1431 // elements from the input and use undef as the second shuffle input.
1432 V2 = UndefValue::get(SrcTy);
1433 for (unsigned i = 0, e = DestTy->getNumElements(); i != e; ++i)
1434 ShuffleMask.push_back(ConstantInt::get(Int32Ty, i));
1435
1436 } else {
1437 // If we're increasing the number of elements, shuffle in all of the
1438 // elements from InVal and fill the rest of the result elements with zeros
1439 // from a constant zero.
1440 V2 = Constant::getNullValue(SrcTy);
1441 unsigned SrcElts = SrcTy->getNumElements();
1442 for (unsigned i = 0, e = SrcElts; i != e; ++i)
1443 ShuffleMask.push_back(ConstantInt::get(Int32Ty, i));
1444
1445 // The excess elements reference the first element of the zero input.
1446 ShuffleMask.append(DestTy->getNumElements()-SrcElts,
1447 ConstantInt::get(Int32Ty, SrcElts));
1448 }
1449
Chris Lattner2ca5c862011-02-15 00:14:00 +00001450 return new ShuffleVectorInst(InVal, V2, ConstantVector::get(ShuffleMask));
Chris Lattner67451912010-05-08 21:50:26 +00001451}
1452
Chris Lattnerdb125cf2011-07-18 04:54:35 +00001453static bool isMultipleOfTypeSize(unsigned Value, Type *Ty) {
Chris Lattner3dd08732010-08-28 01:20:38 +00001454 return Value % Ty->getPrimitiveSizeInBits() == 0;
1455}
1456
Chris Lattnerdb125cf2011-07-18 04:54:35 +00001457static unsigned getTypeSizeIndex(unsigned Value, Type *Ty) {
Chris Lattner3dd08732010-08-28 01:20:38 +00001458 return Value / Ty->getPrimitiveSizeInBits();
1459}
1460
1461/// CollectInsertionElements - V is a value which is inserted into a vector of
1462/// VecEltTy. Look through the value to see if we can decompose it into
1463/// insertions into the vector. See the example in the comment for
1464/// OptimizeIntegerToVectorInsertions for the pattern this handles.
1465/// The type of V is always a non-zero multiple of VecEltTy's size.
1466///
1467/// This returns false if the pattern can't be matched or true if it can,
1468/// filling in Elements with the elements found here.
1469static bool CollectInsertionElements(Value *V, unsigned ElementIndex,
1470 SmallVectorImpl<Value*> &Elements,
Chris Lattnerdb125cf2011-07-18 04:54:35 +00001471 Type *VecEltTy) {
Chris Lattner157d4ea2010-08-28 03:36:51 +00001472 // Undef values never contribute useful bits to the result.
1473 if (isa<UndefValue>(V)) return true;
1474
Chris Lattner3dd08732010-08-28 01:20:38 +00001475 // If we got down to a value of the right type, we win, try inserting into the
1476 // right element.
1477 if (V->getType() == VecEltTy) {
Chris Lattner79007792010-08-28 01:50:57 +00001478 // Inserting null doesn't actually insert any elements.
1479 if (Constant *C = dyn_cast<Constant>(V))
1480 if (C->isNullValue())
1481 return true;
1482
Chris Lattner3dd08732010-08-28 01:20:38 +00001483 // Fail if multiple elements are inserted into this slot.
1484 if (ElementIndex >= Elements.size() || Elements[ElementIndex] != 0)
1485 return false;
1486
1487 Elements[ElementIndex] = V;
1488 return true;
1489 }
1490
Chris Lattner79007792010-08-28 01:50:57 +00001491 if (Constant *C = dyn_cast<Constant>(V)) {
Chris Lattner3dd08732010-08-28 01:20:38 +00001492 // Figure out the # elements this provides, and bitcast it or slice it up
1493 // as required.
Chris Lattner79007792010-08-28 01:50:57 +00001494 unsigned NumElts = getTypeSizeIndex(C->getType()->getPrimitiveSizeInBits(),
1495 VecEltTy);
1496 // If the constant is the size of a vector element, we just need to bitcast
1497 // it to the right type so it gets properly inserted.
1498 if (NumElts == 1)
1499 return CollectInsertionElements(ConstantExpr::getBitCast(C, VecEltTy),
1500 ElementIndex, Elements, VecEltTy);
1501
1502 // Okay, this is a constant that covers multiple elements. Slice it up into
1503 // pieces and insert each element-sized piece into the vector.
1504 if (!isa<IntegerType>(C->getType()))
1505 C = ConstantExpr::getBitCast(C, IntegerType::get(V->getContext(),
1506 C->getType()->getPrimitiveSizeInBits()));
1507 unsigned ElementSize = VecEltTy->getPrimitiveSizeInBits();
Chris Lattnerdb125cf2011-07-18 04:54:35 +00001508 Type *ElementIntTy = IntegerType::get(C->getContext(), ElementSize);
Chris Lattner79007792010-08-28 01:50:57 +00001509
1510 for (unsigned i = 0; i != NumElts; ++i) {
1511 Constant *Piece = ConstantExpr::getLShr(C, ConstantInt::get(C->getType(),
1512 i*ElementSize));
1513 Piece = ConstantExpr::getTrunc(Piece, ElementIntTy);
1514 if (!CollectInsertionElements(Piece, ElementIndex+i, Elements, VecEltTy))
1515 return false;
1516 }
1517 return true;
1518 }
Chris Lattner3dd08732010-08-28 01:20:38 +00001519
1520 if (!V->hasOneUse()) return false;
1521
1522 Instruction *I = dyn_cast<Instruction>(V);
1523 if (I == 0) return false;
1524 switch (I->getOpcode()) {
1525 default: return false; // Unhandled case.
1526 case Instruction::BitCast:
1527 return CollectInsertionElements(I->getOperand(0), ElementIndex,
1528 Elements, VecEltTy);
1529 case Instruction::ZExt:
1530 if (!isMultipleOfTypeSize(
1531 I->getOperand(0)->getType()->getPrimitiveSizeInBits(),
1532 VecEltTy))
1533 return false;
1534 return CollectInsertionElements(I->getOperand(0), ElementIndex,
1535 Elements, VecEltTy);
1536 case Instruction::Or:
1537 return CollectInsertionElements(I->getOperand(0), ElementIndex,
1538 Elements, VecEltTy) &&
1539 CollectInsertionElements(I->getOperand(1), ElementIndex,
1540 Elements, VecEltTy);
1541 case Instruction::Shl: {
1542 // Must be shifting by a constant that is a multiple of the element size.
1543 ConstantInt *CI = dyn_cast<ConstantInt>(I->getOperand(1));
1544 if (CI == 0) return false;
1545 if (!isMultipleOfTypeSize(CI->getZExtValue(), VecEltTy)) return false;
1546 unsigned IndexShift = getTypeSizeIndex(CI->getZExtValue(), VecEltTy);
1547
1548 return CollectInsertionElements(I->getOperand(0), ElementIndex+IndexShift,
1549 Elements, VecEltTy);
1550 }
1551
1552 }
1553}
1554
1555
1556/// OptimizeIntegerToVectorInsertions - If the input is an 'or' instruction, we
1557/// may be doing shifts and ors to assemble the elements of the vector manually.
1558/// Try to rip the code out and replace it with insertelements. This is to
1559/// optimize code like this:
1560///
1561/// %tmp37 = bitcast float %inc to i32
1562/// %tmp38 = zext i32 %tmp37 to i64
1563/// %tmp31 = bitcast float %inc5 to i32
1564/// %tmp32 = zext i32 %tmp31 to i64
1565/// %tmp33 = shl i64 %tmp32, 32
1566/// %ins35 = or i64 %tmp33, %tmp38
1567/// %tmp43 = bitcast i64 %ins35 to <2 x float>
1568///
1569/// Into two insertelements that do "buildvector{%inc, %inc5}".
1570static Value *OptimizeIntegerToVectorInsertions(BitCastInst &CI,
1571 InstCombiner &IC) {
Chris Lattnerdb125cf2011-07-18 04:54:35 +00001572 VectorType *DestVecTy = cast<VectorType>(CI.getType());
Chris Lattner3dd08732010-08-28 01:20:38 +00001573 Value *IntInput = CI.getOperand(0);
1574
1575 SmallVector<Value*, 8> Elements(DestVecTy->getNumElements());
1576 if (!CollectInsertionElements(IntInput, 0, Elements,
1577 DestVecTy->getElementType()))
1578 return 0;
1579
1580 // If we succeeded, we know that all of the element are specified by Elements
1581 // or are zero if Elements has a null entry. Recast this as a set of
1582 // insertions.
1583 Value *Result = Constant::getNullValue(CI.getType());
1584 for (unsigned i = 0, e = Elements.size(); i != e; ++i) {
1585 if (Elements[i] == 0) continue; // Unset element.
1586
1587 Result = IC.Builder->CreateInsertElement(Result, Elements[i],
1588 IC.Builder->getInt32(i));
1589 }
1590
1591 return Result;
1592}
1593
1594
Chris Lattnere5a14262010-08-26 21:55:42 +00001595/// OptimizeIntToFloatBitCast - See if we can optimize an integer->float/double
1596/// bitcast. The various long double bitcasts can't get in here.
Chris Lattner26dbe7e2010-08-26 22:14:59 +00001597static Instruction *OptimizeIntToFloatBitCast(BitCastInst &CI,InstCombiner &IC){
Chris Lattnere5a14262010-08-26 21:55:42 +00001598 Value *Src = CI.getOperand(0);
Chris Lattnerdb125cf2011-07-18 04:54:35 +00001599 Type *DestTy = CI.getType();
Chris Lattnere5a14262010-08-26 21:55:42 +00001600
1601 // If this is a bitcast from int to float, check to see if the int is an
1602 // extraction from a vector.
1603 Value *VecInput = 0;
Chris Lattner26dbe7e2010-08-26 22:14:59 +00001604 // bitcast(trunc(bitcast(somevector)))
Chris Lattnere5a14262010-08-26 21:55:42 +00001605 if (match(Src, m_Trunc(m_BitCast(m_Value(VecInput)))) &&
1606 isa<VectorType>(VecInput->getType())) {
Chris Lattnerdb125cf2011-07-18 04:54:35 +00001607 VectorType *VecTy = cast<VectorType>(VecInput->getType());
Chris Lattner26dbe7e2010-08-26 22:14:59 +00001608 unsigned DestWidth = DestTy->getPrimitiveSizeInBits();
1609
1610 if (VecTy->getPrimitiveSizeInBits() % DestWidth == 0) {
1611 // If the element type of the vector doesn't match the result type,
1612 // bitcast it to be a vector type we can extract from.
1613 if (VecTy->getElementType() != DestTy) {
1614 VecTy = VectorType::get(DestTy,
1615 VecTy->getPrimitiveSizeInBits() / DestWidth);
1616 VecInput = IC.Builder->CreateBitCast(VecInput, VecTy);
1617 }
Chris Lattnere5a14262010-08-26 21:55:42 +00001618
Chris Lattnere5a14262010-08-26 21:55:42 +00001619 return ExtractElementInst::Create(VecInput, IC.Builder->getInt32(0));
Chris Lattner26dbe7e2010-08-26 22:14:59 +00001620 }
Chris Lattnere5a14262010-08-26 21:55:42 +00001621 }
1622
Chris Lattner26dbe7e2010-08-26 22:14:59 +00001623 // bitcast(trunc(lshr(bitcast(somevector), cst))
1624 ConstantInt *ShAmt = 0;
1625 if (match(Src, m_Trunc(m_LShr(m_BitCast(m_Value(VecInput)),
1626 m_ConstantInt(ShAmt)))) &&
1627 isa<VectorType>(VecInput->getType())) {
Chris Lattnerdb125cf2011-07-18 04:54:35 +00001628 VectorType *VecTy = cast<VectorType>(VecInput->getType());
Chris Lattner26dbe7e2010-08-26 22:14:59 +00001629 unsigned DestWidth = DestTy->getPrimitiveSizeInBits();
1630 if (VecTy->getPrimitiveSizeInBits() % DestWidth == 0 &&
1631 ShAmt->getZExtValue() % DestWidth == 0) {
1632 // If the element type of the vector doesn't match the result type,
1633 // bitcast it to be a vector type we can extract from.
1634 if (VecTy->getElementType() != DestTy) {
1635 VecTy = VectorType::get(DestTy,
1636 VecTy->getPrimitiveSizeInBits() / DestWidth);
1637 VecInput = IC.Builder->CreateBitCast(VecInput, VecTy);
1638 }
1639
1640 unsigned Elt = ShAmt->getZExtValue() / DestWidth;
1641 return ExtractElementInst::Create(VecInput, IC.Builder->getInt32(Elt));
1642 }
1643 }
Chris Lattnere5a14262010-08-26 21:55:42 +00001644 return 0;
1645}
Chris Lattner67451912010-05-08 21:50:26 +00001646
Chris Lattner80f43d32010-01-04 07:53:58 +00001647Instruction *InstCombiner::visitBitCast(BitCastInst &CI) {
1648 // If the operands are integer typed then apply the integer transforms,
1649 // otherwise just apply the common ones.
1650 Value *Src = CI.getOperand(0);
Chris Lattnerdb125cf2011-07-18 04:54:35 +00001651 Type *SrcTy = Src->getType();
1652 Type *DestTy = CI.getType();
Chris Lattner80f43d32010-01-04 07:53:58 +00001653
Chris Lattner80f43d32010-01-04 07:53:58 +00001654 // Get rid of casts from one type to the same type. These are useless and can
1655 // be replaced by the operand.
1656 if (DestTy == Src->getType())
1657 return ReplaceInstUsesWith(CI, Src);
1658
Chris Lattnerdb125cf2011-07-18 04:54:35 +00001659 if (PointerType *DstPTy = dyn_cast<PointerType>(DestTy)) {
1660 PointerType *SrcPTy = cast<PointerType>(SrcTy);
1661 Type *DstElTy = DstPTy->getElementType();
1662 Type *SrcElTy = SrcPTy->getElementType();
Chris Lattner80f43d32010-01-04 07:53:58 +00001663
1664 // If the address spaces don't match, don't eliminate the bitcast, which is
1665 // required for changing types.
1666 if (SrcPTy->getAddressSpace() != DstPTy->getAddressSpace())
1667 return 0;
1668
1669 // If we are casting a alloca to a pointer to a type of the same
1670 // size, rewrite the allocation instruction to allocate the "right" type.
1671 // There is no need to modify malloc calls because it is their bitcast that
1672 // needs to be cleaned up.
1673 if (AllocaInst *AI = dyn_cast<AllocaInst>(Src))
1674 if (Instruction *V = PromoteCastOfAllocation(CI, *AI))
1675 return V;
1676
1677 // If the source and destination are pointers, and this cast is equivalent
1678 // to a getelementptr X, 0, 0, 0... turn it into the appropriate gep.
1679 // This can enhance SROA and other transforms that want type-safe pointers.
1680 Constant *ZeroUInt =
1681 Constant::getNullValue(Type::getInt32Ty(CI.getContext()));
1682 unsigned NumZeros = 0;
1683 while (SrcElTy != DstElTy &&
Duncan Sands1df98592010-02-16 11:11:14 +00001684 isa<CompositeType>(SrcElTy) && !SrcElTy->isPointerTy() &&
Chris Lattner80f43d32010-01-04 07:53:58 +00001685 SrcElTy->getNumContainedTypes() /* not "{}" */) {
1686 SrcElTy = cast<CompositeType>(SrcElTy)->getTypeAtIndex(ZeroUInt);
1687 ++NumZeros;
1688 }
1689
1690 // If we found a path from the src to dest, create the getelementptr now.
1691 if (SrcElTy == DstElTy) {
1692 SmallVector<Value*, 8> Idxs(NumZeros+1, ZeroUInt);
Jay Foada9203102011-07-25 09:48:08 +00001693 return GetElementPtrInst::CreateInBounds(Src, Idxs);
Chris Lattner80f43d32010-01-04 07:53:58 +00001694 }
1695 }
Chris Lattnere5a14262010-08-26 21:55:42 +00001696
1697 // Try to optimize int -> float bitcasts.
1698 if ((DestTy->isFloatTy() || DestTy->isDoubleTy()) && isa<IntegerType>(SrcTy))
1699 if (Instruction *I = OptimizeIntToFloatBitCast(CI, *this))
1700 return I;
Chris Lattner80f43d32010-01-04 07:53:58 +00001701
Chris Lattnerdb125cf2011-07-18 04:54:35 +00001702 if (VectorType *DestVTy = dyn_cast<VectorType>(DestTy)) {
Duncan Sands1df98592010-02-16 11:11:14 +00001703 if (DestVTy->getNumElements() == 1 && !SrcTy->isVectorTy()) {
Chris Lattner7a34d6c2010-01-05 22:21:18 +00001704 Value *Elem = Builder->CreateBitCast(Src, DestVTy->getElementType());
1705 return InsertElementInst::Create(UndefValue::get(DestTy), Elem,
Chris Lattner80f43d32010-01-04 07:53:58 +00001706 Constant::getNullValue(Type::getInt32Ty(CI.getContext())));
Chris Lattner80f43d32010-01-04 07:53:58 +00001707 // FIXME: Canonicalize bitcast(insertelement) -> insertelement(bitcast)
1708 }
Chris Lattner67451912010-05-08 21:50:26 +00001709
Chris Lattner3dd08732010-08-28 01:20:38 +00001710 if (isa<IntegerType>(SrcTy)) {
1711 // If this is a cast from an integer to vector, check to see if the input
1712 // is a trunc or zext of a bitcast from vector. If so, we can replace all
1713 // the casts with a shuffle and (potentially) a bitcast.
1714 if (isa<TruncInst>(Src) || isa<ZExtInst>(Src)) {
1715 CastInst *SrcCast = cast<CastInst>(Src);
1716 if (BitCastInst *BCIn = dyn_cast<BitCastInst>(SrcCast->getOperand(0)))
1717 if (isa<VectorType>(BCIn->getOperand(0)->getType()))
1718 if (Instruction *I = OptimizeVectorResize(BCIn->getOperand(0),
Chris Lattner67451912010-05-08 21:50:26 +00001719 cast<VectorType>(DestTy), *this))
Chris Lattner3dd08732010-08-28 01:20:38 +00001720 return I;
1721 }
1722
1723 // If the input is an 'or' instruction, we may be doing shifts and ors to
1724 // assemble the elements of the vector manually. Try to rip the code out
1725 // and replace it with insertelements.
1726 if (Value *V = OptimizeIntegerToVectorInsertions(CI, *this))
1727 return ReplaceInstUsesWith(CI, V);
Chris Lattner67451912010-05-08 21:50:26 +00001728 }
Chris Lattner80f43d32010-01-04 07:53:58 +00001729 }
1730
Chris Lattnerdb125cf2011-07-18 04:54:35 +00001731 if (VectorType *SrcVTy = dyn_cast<VectorType>(SrcTy)) {
Duncan Sands1df98592010-02-16 11:11:14 +00001732 if (SrcVTy->getNumElements() == 1 && !DestTy->isVectorTy()) {
Chris Lattner7a34d6c2010-01-05 22:21:18 +00001733 Value *Elem =
1734 Builder->CreateExtractElement(Src,
1735 Constant::getNullValue(Type::getInt32Ty(CI.getContext())));
1736 return CastInst::Create(Instruction::BitCast, Elem, DestTy);
Chris Lattner80f43d32010-01-04 07:53:58 +00001737 }
1738 }
1739
1740 if (ShuffleVectorInst *SVI = dyn_cast<ShuffleVectorInst>(Src)) {
Chris Lattner7a34d6c2010-01-05 22:21:18 +00001741 // Okay, we have (bitcast (shuffle ..)). Check to see if this is
Dan Gohmana5ced592010-04-07 23:22:42 +00001742 // a bitcast to a vector with the same # elts.
Duncan Sands1df98592010-02-16 11:11:14 +00001743 if (SVI->hasOneUse() && DestTy->isVectorTy() &&
Chris Lattner7a34d6c2010-01-05 22:21:18 +00001744 cast<VectorType>(DestTy)->getNumElements() ==
1745 SVI->getType()->getNumElements() &&
1746 SVI->getType()->getNumElements() ==
1747 cast<VectorType>(SVI->getOperand(0)->getType())->getNumElements()) {
1748 BitCastInst *Tmp;
1749 // If either of the operands is a cast from CI.getType(), then
1750 // evaluating the shuffle in the casted destination's type will allow
1751 // us to eliminate at least one cast.
1752 if (((Tmp = dyn_cast<BitCastInst>(SVI->getOperand(0))) &&
1753 Tmp->getOperand(0)->getType() == DestTy) ||
1754 ((Tmp = dyn_cast<BitCastInst>(SVI->getOperand(1))) &&
1755 Tmp->getOperand(0)->getType() == DestTy)) {
1756 Value *LHS = Builder->CreateBitCast(SVI->getOperand(0), DestTy);
1757 Value *RHS = Builder->CreateBitCast(SVI->getOperand(1), DestTy);
1758 // Return a new shuffle vector. Use the same element ID's, as we
1759 // know the vector types match #elts.
1760 return new ShuffleVectorInst(LHS, RHS, SVI->getOperand(2));
Chris Lattner80f43d32010-01-04 07:53:58 +00001761 }
1762 }
1763 }
Chris Lattner7a34d6c2010-01-05 22:21:18 +00001764
Duncan Sands1df98592010-02-16 11:11:14 +00001765 if (SrcTy->isPointerTy())
Chris Lattner7a34d6c2010-01-05 22:21:18 +00001766 return commonPointerCastTransforms(CI);
1767 return commonCastTransforms(CI);
Chris Lattner80f43d32010-01-04 07:53:58 +00001768}