1 //===- 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"
15 #include "llvm/Analysis/ConstantFolding.h"
16 #include "llvm/Target/TargetData.h"
17 #include "llvm/Support/PatternMatch.h"
18 using namespace llvm;
19 using namespace PatternMatch;
20
21 /// DecomposeSimpleLinearExpr - Analyze 'Val', seeing if it is a simple linear
22 /// expression. If so, decompose it, returning some value X, such that Val is
23 /// X*Scale+Offset.
24 ///
DecomposeSimpleLinearExpr(Value * Val,unsigned & Scale,uint64_t & Offset)25 static Value *DecomposeSimpleLinearExpr(Value *Val, unsigned &Scale,
26 uint64_t &Offset) {
27 if (ConstantInt *CI = dyn_cast<ConstantInt>(Val)) {
28 Offset = CI->getZExtValue();
29 Scale = 0;
30 return ConstantInt::get(Val->getType(), 0);
31 }
32
33 if (BinaryOperator *I = dyn_cast<BinaryOperator>(Val)) {
34 // Cannot look past anything that might overflow.
35 OverflowingBinaryOperator *OBI = dyn_cast<OverflowingBinaryOperator>(Val);
36 if (OBI && !OBI->hasNoUnsignedWrap()) {
37 Scale = 1;
38 Offset = 0;
39 return Val;
40 }
41
42 if (ConstantInt *RHS = dyn_cast<ConstantInt>(I->getOperand(1))) {
43 if (I->getOpcode() == Instruction::Shl) {
44 // This is a value scaled by '1 << the shift amt'.
45 Scale = UINT64_C(1) << RHS->getZExtValue();
46 Offset = 0;
47 return I->getOperand(0);
48 }
49
50 if (I->getOpcode() == Instruction::Mul) {
51 // This value is scaled by 'RHS'.
52 Scale = RHS->getZExtValue();
53 Offset = 0;
54 return I->getOperand(0);
55 }
56
57 if (I->getOpcode() == Instruction::Add) {
58 // We have X+C. Check to see if we really have (X*C2)+C1,
59 // where C1 is divisible by C2.
60 unsigned SubScale;
61 Value *SubVal =
62 DecomposeSimpleLinearExpr(I->getOperand(0), SubScale, Offset);
63 Offset += RHS->getZExtValue();
64 Scale = SubScale;
65 return SubVal;
66 }
67 }
68 }
69
70 // Otherwise, we can't look past this.
71 Scale = 1;
72 Offset = 0;
73 return Val;
74 }
75
76 /// PromoteCastOfAllocation - If we find a cast of an allocation instruction,
77 /// try to eliminate the cast by moving the type information into the alloc.
PromoteCastOfAllocation(BitCastInst & CI,AllocaInst & AI)78 Instruction *InstCombiner::PromoteCastOfAllocation(BitCastInst &CI,
79 AllocaInst &AI) {
80 // This requires TargetData to get the alloca alignment and size information.
81 if (!TD) return 0;
82
83 PointerType *PTy = cast<PointerType>(CI.getType());
84
85 BuilderTy AllocaBuilder(*Builder);
86 AllocaBuilder.SetInsertPoint(AI.getParent(), &AI);
87
88 // Get the type really allocated and the type casted to.
89 Type *AllocElTy = AI.getAllocatedType();
90 Type *CastElTy = PTy->getElementType();
91 if (!AllocElTy->isSized() || !CastElTy->isSized()) return 0;
92
93 unsigned AllocElTyAlign = TD->getABITypeAlignment(AllocElTy);
94 unsigned CastElTyAlign = TD->getABITypeAlignment(CastElTy);
95 if (CastElTyAlign < AllocElTyAlign) return 0;
96
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
99 // same, we open the door to infinite loops of various kinds.
100 if (!AI.hasOneUse() && CastElTyAlign == AllocElTyAlign) return 0;
101
102 uint64_t AllocElTySize = TD->getTypeAllocSize(AllocElTy);
103 uint64_t CastElTySize = TD->getTypeAllocSize(CastElTy);
104 if (CastElTySize == 0 || AllocElTySize == 0) return 0;
105
106 // See if we can satisfy the modulus by pulling a scale out of the array
107 // size argument.
108 unsigned ArraySizeScale;
109 uint64_t ArrayOffset;
110 Value *NumElements = // See if the array size is a decomposable linear expr.
111 DecomposeSimpleLinearExpr(AI.getOperand(0), ArraySizeScale, ArrayOffset);
112
113 // If we can now satisfy the modulus, by using a non-1 scale, we really can
114 // do the xform.
115 if ((AllocElTySize*ArraySizeScale) % CastElTySize != 0 ||
116 (AllocElTySize*ArrayOffset ) % CastElTySize != 0) return 0;
117
118 unsigned Scale = (AllocElTySize*ArraySizeScale)/CastElTySize;
119 Value *Amt = 0;
120 if (Scale == 1) {
121 Amt = NumElements;
122 } else {
123 Amt = ConstantInt::get(AI.getArraySize()->getType(), Scale);
124 // Insert before the alloca, not before the cast.
125 Amt = AllocaBuilder.CreateMul(Amt, NumElements);
126 }
127
128 if (uint64_t Offset = (AllocElTySize*ArrayOffset)/CastElTySize) {
129 Value *Off = ConstantInt::get(AI.getArraySize()->getType(),
130 Offset, true);
131 Amt = AllocaBuilder.CreateAdd(Amt, Off);
132 }
133
134 AllocaInst *New = AllocaBuilder.CreateAlloca(CastElTy, Amt);
135 New->setAlignment(AI.getAlignment());
136 New->takeName(&AI);
137
138 // If the allocation has multiple real uses, insert a cast and change all
139 // things that used it to use the new cast. This will also hack on CI, but it
140 // will die soon.
141 if (!AI.hasOneUse()) {
142 // New is the allocation instruction, pointer typed. AI is the original
143 // allocation instruction, also pointer typed. Thus, cast to use is BitCast.
144 Value *NewCast = AllocaBuilder.CreateBitCast(New, AI.getType(), "tmpcast");
145 ReplaceInstUsesWith(AI, NewCast);
146 }
147 return ReplaceInstUsesWith(CI, New);
148 }
149
150
151
152 /// EvaluateInDifferentType - Given an expression that
153 /// CanEvaluateTruncated or CanEvaluateSExtd returns true for, actually
154 /// insert the code to evaluate the expression.
EvaluateInDifferentType(Value * V,Type * Ty,bool isSigned)155 Value *InstCombiner::EvaluateInDifferentType(Value *V, Type *Ty,
156 bool isSigned) {
157 if (Constant *C = dyn_cast<Constant>(V)) {
158 C = ConstantExpr::getIntegerCast(C, Ty, isSigned /*Sext or ZExt*/);
159 // If we got a constantexpr back, try to simplify it with TD info.
160 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(C))
161 C = ConstantFoldConstantExpression(CE, TD);
162 return C;
163 }
164
165 // Otherwise, it must be an instruction.
166 Instruction *I = cast<Instruction>(V);
167 Instruction *Res = 0;
168 unsigned Opc = I->getOpcode();
169 switch (Opc) {
170 case Instruction::Add:
171 case Instruction::Sub:
172 case Instruction::Mul:
173 case Instruction::And:
174 case Instruction::Or:
175 case Instruction::Xor:
176 case Instruction::AShr:
177 case Instruction::LShr:
178 case Instruction::Shl:
179 case Instruction::UDiv:
180 case Instruction::URem: {
181 Value *LHS = EvaluateInDifferentType(I->getOperand(0), Ty, isSigned);
182 Value *RHS = EvaluateInDifferentType(I->getOperand(1), Ty, isSigned);
183 Res = BinaryOperator::Create((Instruction::BinaryOps)Opc, LHS, RHS);
184 break;
185 }
186 case Instruction::Trunc:
187 case Instruction::ZExt:
188 case Instruction::SExt:
189 // If the source type of the cast is the type we're trying for then we can
190 // just return the source. There's no need to insert it because it is not
191 // new.
192 if (I->getOperand(0)->getType() == Ty)
193 return I->getOperand(0);
194
195 // Otherwise, must be the same type of cast, so just reinsert a new one.
196 // This also handles the case of zext(trunc(x)) -> zext(x).
197 Res = CastInst::CreateIntegerCast(I->getOperand(0), Ty,
198 Opc == Instruction::SExt);
199 break;
200 case Instruction::Select: {
201 Value *True = EvaluateInDifferentType(I->getOperand(1), Ty, isSigned);
202 Value *False = EvaluateInDifferentType(I->getOperand(2), Ty, isSigned);
203 Res = SelectInst::Create(I->getOperand(0), True, False);
204 break;
205 }
206 case Instruction::PHI: {
207 PHINode *OPN = cast<PHINode>(I);
208 PHINode *NPN = PHINode::Create(Ty, OPN->getNumIncomingValues());
209 for (unsigned i = 0, e = OPN->getNumIncomingValues(); i != e; ++i) {
210 Value *V =EvaluateInDifferentType(OPN->getIncomingValue(i), Ty, isSigned);
211 NPN->addIncoming(V, OPN->getIncomingBlock(i));
212 }
213 Res = NPN;
214 break;
215 }
216 default:
217 // TODO: Can handle more cases here.
218 llvm_unreachable("Unreachable!");
219 break;
220 }
221
222 Res->takeName(I);
223 return InsertNewInstWith(Res, *I);
224 }
225
226
227 /// This function is a wrapper around CastInst::isEliminableCastPair. It
228 /// simply extracts arguments and returns what that function returns.
229 static Instruction::CastOps
isEliminableCastPair(const CastInst * CI,unsigned opcode,Type * DstTy,TargetData * TD)230 isEliminableCastPair(
231 const CastInst *CI, ///< The first cast instruction
232 unsigned opcode, ///< The opcode of the second cast instruction
233 Type *DstTy, ///< The target type for the second cast instruction
234 TargetData *TD ///< The target data for pointer size
235 ) {
236
237 Type *SrcTy = CI->getOperand(0)->getType(); // A from above
238 Type *MidTy = CI->getType(); // B from above
239
240 // Get the opcodes of the two Cast instructions
241 Instruction::CastOps firstOp = Instruction::CastOps(CI->getOpcode());
242 Instruction::CastOps secondOp = Instruction::CastOps(opcode);
243
244 unsigned Res = CastInst::isEliminableCastPair(firstOp, secondOp, SrcTy, MidTy,
245 DstTy,
246 TD ? TD->getIntPtrType(CI->getContext()) : 0);
247
248 // We don't want to form an inttoptr or ptrtoint that converts to an integer
249 // type that differs from the pointer size.
250 if ((Res == Instruction::IntToPtr &&
251 (!TD || SrcTy != TD->getIntPtrType(CI->getContext()))) ||
252 (Res == Instruction::PtrToInt &&
253 (!TD || DstTy != TD->getIntPtrType(CI->getContext()))))
254 Res = 0;
255
256 return Instruction::CastOps(Res);
257 }
258
259 /// ShouldOptimizeCast - Return true if the cast from "V to Ty" actually
260 /// results in any code being generated and is interesting to optimize out. If
261 /// the cast can be eliminated by some other simple transformation, we prefer
262 /// to do the simplification first.
ShouldOptimizeCast(Instruction::CastOps opc,const Value * V,Type * Ty)263 bool InstCombiner::ShouldOptimizeCast(Instruction::CastOps opc, const Value *V,
264 Type *Ty) {
265 // Noop casts and casts of constants should be eliminated trivially.
266 if (V->getType() == Ty || isa<Constant>(V)) return false;
267
268 // If this is another cast that can be eliminated, we prefer to have it
269 // eliminated.
270 if (const CastInst *CI = dyn_cast<CastInst>(V))
271 if (isEliminableCastPair(CI, opc, Ty, TD))
272 return false;
273
274 // If this is a vector sext from a compare, then we don't want to break the
275 // idiom where each element of the extended vector is either zero or all ones.
276 if (opc == Instruction::SExt && isa<CmpInst>(V) && Ty->isVectorTy())
277 return false;
278
279 return true;
280 }
281
282
283 /// @brief Implement the transforms common to all CastInst visitors.
commonCastTransforms(CastInst & CI)284 Instruction *InstCombiner::commonCastTransforms(CastInst &CI) {
285 Value *Src = CI.getOperand(0);
286
287 // Many cases of "cast of a cast" are eliminable. If it's eliminable we just
288 // eliminate it now.
289 if (CastInst *CSrc = dyn_cast<CastInst>(Src)) { // A->B->C cast
290 if (Instruction::CastOps opc =
291 isEliminableCastPair(CSrc, CI.getOpcode(), CI.getType(), TD)) {
292 // The first cast (CSrc) is eliminable so we need to fix up or replace
293 // the second cast (CI). CSrc will then have a good chance of being dead.
294 return CastInst::Create(opc, CSrc->getOperand(0), CI.getType());
295 }
296 }
297
298 // If we are casting a select then fold the cast into the select
299 if (SelectInst *SI = dyn_cast<SelectInst>(Src))
300 if (Instruction *NV = FoldOpIntoSelect(CI, SI))
301 return NV;
302
303 // If we are casting a PHI then fold the cast into the PHI
304 if (isa<PHINode>(Src)) {
305 // We don't do this if this would create a PHI node with an illegal type if
306 // it is currently legal.
307 if (!Src->getType()->isIntegerTy() ||
308 !CI.getType()->isIntegerTy() ||
309 ShouldChangeType(CI.getType(), Src->getType()))
310 if (Instruction *NV = FoldOpIntoPhi(CI))
311 return NV;
312 }
313
314 return 0;
315 }
316
317 /// CanEvaluateTruncated - Return true if we can evaluate the specified
318 /// expression tree as type Ty instead of its larger type, and arrive with the
319 /// same value. This is used by code that tries to eliminate truncates.
320 ///
321 /// Ty will always be a type smaller than V. We should return true if trunc(V)
322 /// can be computed by computing V in the smaller type. If V is an instruction,
323 /// then trunc(inst(x,y)) can be computed as inst(trunc(x),trunc(y)), which only
324 /// makes sense if x and y can be efficiently truncated.
325 ///
326 /// This function works on both vectors and scalars.
327 ///
CanEvaluateTruncated(Value * V,Type * Ty)328 static bool CanEvaluateTruncated(Value *V, Type *Ty) {
329 // We can always evaluate constants in another type.
330 if (isa<Constant>(V))
331 return true;
332
333 Instruction *I = dyn_cast<Instruction>(V);
334 if (!I) return false;
335
336 Type *OrigTy = V->getType();
337
338 // If this is an extension from the dest type, we can eliminate it, even if it
339 // has multiple uses.
340 if ((isa<ZExtInst>(I) || isa<SExtInst>(I)) &&
341 I->getOperand(0)->getType() == Ty)
342 return true;
343
344 // We can't extend or shrink something that has multiple uses: doing so would
345 // require duplicating the instruction in general, which isn't profitable.
346 if (!I->hasOneUse()) return false;
347
348 unsigned Opc = I->getOpcode();
349 switch (Opc) {
350 case Instruction::Add:
351 case Instruction::Sub:
352 case Instruction::Mul:
353 case Instruction::And:
354 case Instruction::Or:
355 case Instruction::Xor:
356 // These operators can all arbitrarily be extended or truncated.
357 return CanEvaluateTruncated(I->getOperand(0), Ty) &&
358 CanEvaluateTruncated(I->getOperand(1), Ty);
359
360 case Instruction::UDiv:
361 case Instruction::URem: {
362 // UDiv and URem can be truncated if all the truncated bits are zero.
363 uint32_t OrigBitWidth = OrigTy->getScalarSizeInBits();
364 uint32_t BitWidth = Ty->getScalarSizeInBits();
365 if (BitWidth < OrigBitWidth) {
366 APInt Mask = APInt::getHighBitsSet(OrigBitWidth, OrigBitWidth-BitWidth);
367 if (MaskedValueIsZero(I->getOperand(0), Mask) &&
368 MaskedValueIsZero(I->getOperand(1), Mask)) {
369 return CanEvaluateTruncated(I->getOperand(0), Ty) &&
370 CanEvaluateTruncated(I->getOperand(1), Ty);
371 }
372 }
373 break;
374 }
375 case Instruction::Shl:
376 // If we are truncating the result of this SHL, and if it's a shift of a
377 // constant amount, we can always perform a SHL in a smaller type.
378 if (ConstantInt *CI = dyn_cast<ConstantInt>(I->getOperand(1))) {
379 uint32_t BitWidth = Ty->getScalarSizeInBits();
380 if (CI->getLimitedValue(BitWidth) < BitWidth)
381 return CanEvaluateTruncated(I->getOperand(0), Ty);
382 }
383 break;
384 case Instruction::LShr:
385 // If this is a truncate of a logical shr, we can truncate it to a smaller
386 // lshr iff we know that the bits we would otherwise be shifting in are
387 // already zeros.
388 if (ConstantInt *CI = dyn_cast<ConstantInt>(I->getOperand(1))) {
389 uint32_t OrigBitWidth = OrigTy->getScalarSizeInBits();
390 uint32_t BitWidth = Ty->getScalarSizeInBits();
391 if (MaskedValueIsZero(I->getOperand(0),
392 APInt::getHighBitsSet(OrigBitWidth, OrigBitWidth-BitWidth)) &&
393 CI->getLimitedValue(BitWidth) < BitWidth) {
394 return CanEvaluateTruncated(I->getOperand(0), Ty);
395 }
396 }
397 break;
398 case Instruction::Trunc:
399 // trunc(trunc(x)) -> trunc(x)
400 return true;
401 case Instruction::ZExt:
402 case Instruction::SExt:
403 // trunc(ext(x)) -> ext(x) if the source type is smaller than the new dest
404 // trunc(ext(x)) -> trunc(x) if the source type is larger than the new dest
405 return true;
406 case Instruction::Select: {
407 SelectInst *SI = cast<SelectInst>(I);
408 return CanEvaluateTruncated(SI->getTrueValue(), Ty) &&
409 CanEvaluateTruncated(SI->getFalseValue(), Ty);
410 }
411 case Instruction::PHI: {
412 // We can change a phi if we can change all operands. Note that we never
413 // get into trouble with cyclic PHIs here because we only consider
414 // instructions with a single use.
415 PHINode *PN = cast<PHINode>(I);
416 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i)
417 if (!CanEvaluateTruncated(PN->getIncomingValue(i), Ty))
418 return false;
419 return true;
420 }
421 default:
422 // TODO: Can handle more cases here.
423 break;
424 }
425
426 return false;
427 }
428
visitTrunc(TruncInst & CI)429 Instruction *InstCombiner::visitTrunc(TruncInst &CI) {
430 if (Instruction *Result = commonCastTransforms(CI))
431 return Result;
432
433 // See if we can simplify any instructions used by the input whose sole
434 // purpose is to compute bits we don't care about.
435 if (SimplifyDemandedInstructionBits(CI))
436 return &CI;
437
438 Value *Src = CI.getOperand(0);
439 Type *DestTy = CI.getType(), *SrcTy = Src->getType();
440
441 // Attempt to truncate the entire input expression tree to the destination
442 // type. Only do this if the dest type is a simple type, don't convert the
443 // expression tree to something weird like i93 unless the source is also
444 // strange.
445 if ((DestTy->isVectorTy() || ShouldChangeType(SrcTy, DestTy)) &&
446 CanEvaluateTruncated(Src, DestTy)) {
447
448 // If this cast is a truncate, evaluting in a different type always
449 // eliminates the cast, so it is always a win.
450 DEBUG(dbgs() << "ICE: EvaluateInDifferentType converting expression type"
451 " to avoid cast: " << CI << '\n');
452 Value *Res = EvaluateInDifferentType(Src, DestTy, false);
453 assert(Res->getType() == DestTy);
454 return ReplaceInstUsesWith(CI, Res);
455 }
456
457 // Canonicalize trunc x to i1 -> (icmp ne (and x, 1), 0), likewise for vector.
458 if (DestTy->getScalarSizeInBits() == 1) {
459 Constant *One = ConstantInt::get(Src->getType(), 1);
460 Src = Builder->CreateAnd(Src, One);
461 Value *Zero = Constant::getNullValue(Src->getType());
462 return new ICmpInst(ICmpInst::ICMP_NE, Src, Zero);
463 }
464
465 // Transform trunc(lshr (zext A), Cst) to eliminate one type conversion.
466 Value *A = 0; ConstantInt *Cst = 0;
467 if (Src->hasOneUse() &&
468 match(Src, m_LShr(m_ZExt(m_Value(A)), m_ConstantInt(Cst)))) {
469 // We have three types to worry about here, the type of A, the source of
470 // the truncate (MidSize), and the destination of the truncate. We know that
471 // ASize < MidSize and MidSize > ResultSize, but don't know the relation
472 // between ASize and ResultSize.
473 unsigned ASize = A->getType()->getPrimitiveSizeInBits();
474
475 // If the shift amount is larger than the size of A, then the result is
476 // known to be zero because all the input bits got shifted out.
477 if (Cst->getZExtValue() >= ASize)
478 return ReplaceInstUsesWith(CI, Constant::getNullValue(CI.getType()));
479
480 // Since we're doing an lshr and a zero extend, and know that the shift
481 // amount is smaller than ASize, it is always safe to do the shift in A's
482 // type, then zero extend or truncate to the result.
483 Value *Shift = Builder->CreateLShr(A, Cst->getZExtValue());
484 Shift->takeName(Src);
485 return CastInst::CreateIntegerCast(Shift, CI.getType(), false);
486 }
487
488 // Transform "trunc (and X, cst)" -> "and (trunc X), cst" so long as the dest
489 // type isn't non-native.
490 if (Src->hasOneUse() && isa<IntegerType>(Src->getType()) &&
491 ShouldChangeType(Src->getType(), CI.getType()) &&
492 match(Src, m_And(m_Value(A), m_ConstantInt(Cst)))) {
493 Value *NewTrunc = Builder->CreateTrunc(A, CI.getType(), A->getName()+".tr");
494 return BinaryOperator::CreateAnd(NewTrunc,
495 ConstantExpr::getTrunc(Cst, CI.getType()));
496 }
497
498 return 0;
499 }
500
501 /// transformZExtICmp - Transform (zext icmp) to bitwise / integer operations
502 /// in order to eliminate the icmp.
transformZExtICmp(ICmpInst * ICI,Instruction & CI,bool DoXform)503 Instruction *InstCombiner::transformZExtICmp(ICmpInst *ICI, Instruction &CI,
504 bool DoXform) {
505 // If we are just checking for a icmp eq of a single bit and zext'ing it
506 // to an integer, then shift the bit to the appropriate place and then
507 // cast to integer to avoid the comparison.
508 if (ConstantInt *Op1C = dyn_cast<ConstantInt>(ICI->getOperand(1))) {
509 const APInt &Op1CV = Op1C->getValue();
510
511 // zext (x <s 0) to i32 --> x>>u31 true if signbit set.
512 // zext (x >s -1) to i32 --> (x>>u31)^1 true if signbit clear.
513 if ((ICI->getPredicate() == ICmpInst::ICMP_SLT && Op1CV == 0) ||
514 (ICI->getPredicate() == ICmpInst::ICMP_SGT &&Op1CV.isAllOnesValue())) {
515 if (!DoXform) return ICI;
516
517 Value *In = ICI->getOperand(0);
518 Value *Sh = ConstantInt::get(In->getType(),
519 In->getType()->getScalarSizeInBits()-1);
520 In = Builder->CreateLShr(In, Sh, In->getName()+".lobit");
521 if (In->getType() != CI.getType())
522 In = Builder->CreateIntCast(In, CI.getType(), false/*ZExt*/);
523
524 if (ICI->getPredicate() == ICmpInst::ICMP_SGT) {
525 Constant *One = ConstantInt::get(In->getType(), 1);
526 In = Builder->CreateXor(In, One, In->getName()+".not");
527 }
528
529 return ReplaceInstUsesWith(CI, In);
530 }
531
532
533
534 // zext (X == 0) to i32 --> X^1 iff X has only the low bit set.
535 // zext (X == 0) to i32 --> (X>>1)^1 iff X has only the 2nd bit set.
536 // zext (X == 1) to i32 --> X iff X has only the low bit set.
537 // zext (X == 2) to i32 --> X>>1 iff X has only the 2nd bit set.
538 // zext (X != 0) to i32 --> X iff X has only the low bit set.
539 // zext (X != 0) to i32 --> X>>1 iff X has only the 2nd bit set.
540 // zext (X != 1) to i32 --> X^1 iff X has only the low bit set.
541 // zext (X != 2) to i32 --> (X>>1)^1 iff X has only the 2nd bit set.
542 if ((Op1CV == 0 || Op1CV.isPowerOf2()) &&
543 // This only works for EQ and NE
544 ICI->isEquality()) {
545 // If Op1C some other power of two, convert:
546 uint32_t BitWidth = Op1C->getType()->getBitWidth();
547 APInt KnownZero(BitWidth, 0), KnownOne(BitWidth, 0);
548 APInt TypeMask(APInt::getAllOnesValue(BitWidth));
549 ComputeMaskedBits(ICI->getOperand(0), TypeMask, KnownZero, KnownOne);
550
551 APInt KnownZeroMask(~KnownZero);
552 if (KnownZeroMask.isPowerOf2()) { // Exactly 1 possible 1?
553 if (!DoXform) return ICI;
554
555 bool isNE = ICI->getPredicate() == ICmpInst::ICMP_NE;
556 if (Op1CV != 0 && (Op1CV != KnownZeroMask)) {
557 // (X&4) == 2 --> false
558 // (X&4) != 2 --> true
559 Constant *Res = ConstantInt::get(Type::getInt1Ty(CI.getContext()),
560 isNE);
561 Res = ConstantExpr::getZExt(Res, CI.getType());
562 return ReplaceInstUsesWith(CI, Res);
563 }
564
565 uint32_t ShiftAmt = KnownZeroMask.logBase2();
566 Value *In = ICI->getOperand(0);
567 if (ShiftAmt) {
568 // Perform a logical shr by shiftamt.
569 // Insert the shift to put the result in the low bit.
570 In = Builder->CreateLShr(In, ConstantInt::get(In->getType(),ShiftAmt),
571 In->getName()+".lobit");
572 }
573
574 if ((Op1CV != 0) == isNE) { // Toggle the low bit.
575 Constant *One = ConstantInt::get(In->getType(), 1);
576 In = Builder->CreateXor(In, One);
577 }
578
579 if (CI.getType() == In->getType())
580 return ReplaceInstUsesWith(CI, In);
581 return CastInst::CreateIntegerCast(In, CI.getType(), false/*ZExt*/);
582 }
583 }
584 }
585
586 // icmp ne A, B is equal to xor A, B when A and B only really have one bit.
587 // It is also profitable to transform icmp eq into not(xor(A, B)) because that
588 // may lead to additional simplifications.
589 if (ICI->isEquality() && CI.getType() == ICI->getOperand(0)->getType()) {
590 if (IntegerType *ITy = dyn_cast<IntegerType>(CI.getType())) {
591 uint32_t BitWidth = ITy->getBitWidth();
592 Value *LHS = ICI->getOperand(0);
593 Value *RHS = ICI->getOperand(1);
594
595 APInt KnownZeroLHS(BitWidth, 0), KnownOneLHS(BitWidth, 0);
596 APInt KnownZeroRHS(BitWidth, 0), KnownOneRHS(BitWidth, 0);
597 APInt TypeMask(APInt::getAllOnesValue(BitWidth));
598 ComputeMaskedBits(LHS, TypeMask, KnownZeroLHS, KnownOneLHS);
599 ComputeMaskedBits(RHS, TypeMask, KnownZeroRHS, KnownOneRHS);
600
601 if (KnownZeroLHS == KnownZeroRHS && KnownOneLHS == KnownOneRHS) {
602 APInt KnownBits = KnownZeroLHS | KnownOneLHS;
603 APInt UnknownBit = ~KnownBits;
604 if (UnknownBit.countPopulation() == 1) {
605 if (!DoXform) return ICI;
606
607 Value *Result = Builder->CreateXor(LHS, RHS);
608
609 // Mask off any bits that are set and won't be shifted away.
610 if (KnownOneLHS.uge(UnknownBit))
611 Result = Builder->CreateAnd(Result,
612 ConstantInt::get(ITy, UnknownBit));
613
614 // Shift the bit we're testing down to the lsb.
615 Result = Builder->CreateLShr(
616 Result, ConstantInt::get(ITy, UnknownBit.countTrailingZeros()));
617
618 if (ICI->getPredicate() == ICmpInst::ICMP_EQ)
619 Result = Builder->CreateXor(Result, ConstantInt::get(ITy, 1));
620 Result->takeName(ICI);
621 return ReplaceInstUsesWith(CI, Result);
622 }
623 }
624 }
625 }
626
627 return 0;
628 }
629
630 /// CanEvaluateZExtd - Determine if the specified value can be computed in the
631 /// specified wider type and produce the same low bits. If not, return false.
632 ///
633 /// If this function returns true, it can also return a non-zero number of bits
634 /// (in BitsToClear) which indicates that the value it computes is correct for
635 /// the zero extend, but that the additional BitsToClear bits need to be zero'd
636 /// out. For example, to promote something like:
637 ///
638 /// %B = trunc i64 %A to i32
639 /// %C = lshr i32 %B, 8
640 /// %E = zext i32 %C to i64
641 ///
642 /// CanEvaluateZExtd for the 'lshr' will return true, and BitsToClear will be
643 /// set to 8 to indicate that the promoted value needs to have bits 24-31
644 /// cleared in addition to bits 32-63. Since an 'and' will be generated to
645 /// clear the top bits anyway, doing this has no extra cost.
646 ///
647 /// This function works on both vectors and scalars.
CanEvaluateZExtd(Value * V,Type * Ty,unsigned & BitsToClear)648 static bool CanEvaluateZExtd(Value *V, Type *Ty, unsigned &BitsToClear) {
649 BitsToClear = 0;
650 if (isa<Constant>(V))
651 return true;
652
653 Instruction *I = dyn_cast<Instruction>(V);
654 if (!I) return false;
655
656 // If the input is a truncate from the destination type, we can trivially
657 // eliminate it, even if it has multiple uses.
658 // FIXME: This is currently disabled until codegen can handle this without
659 // pessimizing code, PR5997.
660 if (0 && isa<TruncInst>(I) && I->getOperand(0)->getType() == Ty)
661 return true;
662
663 // We can't extend or shrink something that has multiple uses: doing so would
664 // require duplicating the instruction in general, which isn't profitable.
665 if (!I->hasOneUse()) return false;
666
667 unsigned Opc = I->getOpcode(), Tmp;
668 switch (Opc) {
669 case Instruction::ZExt: // zext(zext(x)) -> zext(x).
670 case Instruction::SExt: // zext(sext(x)) -> sext(x).
671 case Instruction::Trunc: // zext(trunc(x)) -> trunc(x) or zext(x)
672 return true;
673 case Instruction::And:
674 case Instruction::Or:
675 case Instruction::Xor:
676 case Instruction::Add:
677 case Instruction::Sub:
678 case Instruction::Mul:
679 case Instruction::Shl:
680 if (!CanEvaluateZExtd(I->getOperand(0), Ty, BitsToClear) ||
681 !CanEvaluateZExtd(I->getOperand(1), Ty, Tmp))
682 return false;
683 // These can all be promoted if neither operand has 'bits to clear'.
684 if (BitsToClear == 0 && Tmp == 0)
685 return true;
686
687 // If the operation is an AND/OR/XOR and the bits to clear are zero in the
688 // other side, BitsToClear is ok.
689 if (Tmp == 0 &&
690 (Opc == Instruction::And || Opc == Instruction::Or ||
691 Opc == Instruction::Xor)) {
692 // We use MaskedValueIsZero here for generality, but the case we care
693 // about the most is constant RHS.
694 unsigned VSize = V->getType()->getScalarSizeInBits();
695 if (MaskedValueIsZero(I->getOperand(1),
696 APInt::getHighBitsSet(VSize, BitsToClear)))
697 return true;
698 }
699
700 // Otherwise, we don't know how to analyze this BitsToClear case yet.
701 return false;
702
703 case Instruction::LShr:
704 // We can promote lshr(x, cst) if we can promote x. This requires the
705 // ultimate 'and' to clear out the high zero bits we're clearing out though.
706 if (ConstantInt *Amt = dyn_cast<ConstantInt>(I->getOperand(1))) {
707 if (!CanEvaluateZExtd(I->getOperand(0), Ty, BitsToClear))
708 return false;
709 BitsToClear += Amt->getZExtValue();
710 if (BitsToClear > V->getType()->getScalarSizeInBits())
711 BitsToClear = V->getType()->getScalarSizeInBits();
712 return true;
713 }
714 // Cannot promote variable LSHR.
715 return false;
716 case Instruction::Select:
717 if (!CanEvaluateZExtd(I->getOperand(1), Ty, Tmp) ||
718 !CanEvaluateZExtd(I->getOperand(2), Ty, BitsToClear) ||
719 // TODO: If important, we could handle the case when the BitsToClear are
720 // known zero in the disagreeing side.
721 Tmp != BitsToClear)
722 return false;
723 return true;
724
725 case Instruction::PHI: {
726 // We can change a phi if we can change all operands. Note that we never
727 // get into trouble with cyclic PHIs here because we only consider
728 // instructions with a single use.
729 PHINode *PN = cast<PHINode>(I);
730 if (!CanEvaluateZExtd(PN->getIncomingValue(0), Ty, BitsToClear))
731 return false;
732 for (unsigned i = 1, e = PN->getNumIncomingValues(); i != e; ++i)
733 if (!CanEvaluateZExtd(PN->getIncomingValue(i), Ty, Tmp) ||
734 // TODO: If important, we could handle the case when the BitsToClear
735 // are known zero in the disagreeing input.
736 Tmp != BitsToClear)
737 return false;
738 return true;
739 }
740 default:
741 // TODO: Can handle more cases here.
742 return false;
743 }
744 }
745
visitZExt(ZExtInst & CI)746 Instruction *InstCombiner::visitZExt(ZExtInst &CI) {
747 // If this zero extend is only used by a truncate, let the truncate by
748 // eliminated before we try to optimize this zext.
749 if (CI.hasOneUse() && isa<TruncInst>(CI.use_back()))
750 return 0;
751
752 // If one of the common conversion will work, do it.
753 if (Instruction *Result = commonCastTransforms(CI))
754 return Result;
755
756 // See if we can simplify any instructions used by the input whose sole
757 // purpose is to compute bits we don't care about.
758 if (SimplifyDemandedInstructionBits(CI))
759 return &CI;
760
761 Value *Src = CI.getOperand(0);
762 Type *SrcTy = Src->getType(), *DestTy = CI.getType();
763
764 // Attempt to extend the entire input expression tree to the destination
765 // type. Only do this if the dest type is a simple type, don't convert the
766 // expression tree to something weird like i93 unless the source is also
767 // strange.
768 unsigned BitsToClear;
769 if ((DestTy->isVectorTy() || ShouldChangeType(SrcTy, DestTy)) &&
770 CanEvaluateZExtd(Src, DestTy, BitsToClear)) {
771 assert(BitsToClear < SrcTy->getScalarSizeInBits() &&
772 "Unreasonable BitsToClear");
773
774 // Okay, we can transform this! Insert the new expression now.
775 DEBUG(dbgs() << "ICE: EvaluateInDifferentType converting expression type"
776 " to avoid zero extend: " << CI);
777 Value *Res = EvaluateInDifferentType(Src, DestTy, false);
778 assert(Res->getType() == DestTy);
779
780 uint32_t SrcBitsKept = SrcTy->getScalarSizeInBits()-BitsToClear;
781 uint32_t DestBitSize = DestTy->getScalarSizeInBits();
782
783 // If the high bits are already filled with zeros, just replace this
784 // cast with the result.
785 if (MaskedValueIsZero(Res, APInt::getHighBitsSet(DestBitSize,
786 DestBitSize-SrcBitsKept)))
787 return ReplaceInstUsesWith(CI, Res);
788
789 // We need to emit an AND to clear the high bits.
790 Constant *C = ConstantInt::get(Res->getType(),
791 APInt::getLowBitsSet(DestBitSize, SrcBitsKept));
792 return BinaryOperator::CreateAnd(Res, C);
793 }
794
795 // If this is a TRUNC followed by a ZEXT then we are dealing with integral
796 // types and if the sizes are just right we can convert this into a logical
797 // 'and' which will be much cheaper than the pair of casts.
798 if (TruncInst *CSrc = dyn_cast<TruncInst>(Src)) { // A->B->C cast
799 // TODO: Subsume this into EvaluateInDifferentType.
800
801 // Get the sizes of the types involved. We know that the intermediate type
802 // will be smaller than A or C, but don't know the relation between A and C.
803 Value *A = CSrc->getOperand(0);
804 unsigned SrcSize = A->getType()->getScalarSizeInBits();
805 unsigned MidSize = CSrc->getType()->getScalarSizeInBits();
806 unsigned DstSize = CI.getType()->getScalarSizeInBits();
807 // If we're actually extending zero bits, then if
808 // SrcSize < DstSize: zext(a & mask)
809 // SrcSize == DstSize: a & mask
810 // SrcSize > DstSize: trunc(a) & mask
811 if (SrcSize < DstSize) {
812 APInt AndValue(APInt::getLowBitsSet(SrcSize, MidSize));
813 Constant *AndConst = ConstantInt::get(A->getType(), AndValue);
814 Value *And = Builder->CreateAnd(A, AndConst, CSrc->getName()+".mask");
815 return new ZExtInst(And, CI.getType());
816 }
817
818 if (SrcSize == DstSize) {
819 APInt AndValue(APInt::getLowBitsSet(SrcSize, MidSize));
820 return BinaryOperator::CreateAnd(A, ConstantInt::get(A->getType(),
821 AndValue));
822 }
823 if (SrcSize > DstSize) {
824 Value *Trunc = Builder->CreateTrunc(A, CI.getType());
825 APInt AndValue(APInt::getLowBitsSet(DstSize, MidSize));
826 return BinaryOperator::CreateAnd(Trunc,
827 ConstantInt::get(Trunc->getType(),
828 AndValue));
829 }
830 }
831
832 if (ICmpInst *ICI = dyn_cast<ICmpInst>(Src))
833 return transformZExtICmp(ICI, CI);
834
835 BinaryOperator *SrcI = dyn_cast<BinaryOperator>(Src);
836 if (SrcI && SrcI->getOpcode() == Instruction::Or) {
837 // zext (or icmp, icmp) --> or (zext icmp), (zext icmp) if at least one
838 // of the (zext icmp) will be transformed.
839 ICmpInst *LHS = dyn_cast<ICmpInst>(SrcI->getOperand(0));
840 ICmpInst *RHS = dyn_cast<ICmpInst>(SrcI->getOperand(1));
841 if (LHS && RHS && LHS->hasOneUse() && RHS->hasOneUse() &&
842 (transformZExtICmp(LHS, CI, false) ||
843 transformZExtICmp(RHS, CI, false))) {
844 Value *LCast = Builder->CreateZExt(LHS, CI.getType(), LHS->getName());
845 Value *RCast = Builder->CreateZExt(RHS, CI.getType(), RHS->getName());
846 return BinaryOperator::Create(Instruction::Or, LCast, RCast);
847 }
848 }
849
850 // zext(trunc(t) & C) -> (t & zext(C)).
851 if (SrcI && SrcI->getOpcode() == Instruction::And && SrcI->hasOneUse())
852 if (ConstantInt *C = dyn_cast<ConstantInt>(SrcI->getOperand(1)))
853 if (TruncInst *TI = dyn_cast<TruncInst>(SrcI->getOperand(0))) {
854 Value *TI0 = TI->getOperand(0);
855 if (TI0->getType() == CI.getType())
856 return
857 BinaryOperator::CreateAnd(TI0,
858 ConstantExpr::getZExt(C, CI.getType()));
859 }
860
861 // zext((trunc(t) & C) ^ C) -> ((t & zext(C)) ^ zext(C)).
862 if (SrcI && SrcI->getOpcode() == Instruction::Xor && SrcI->hasOneUse())
863 if (ConstantInt *C = dyn_cast<ConstantInt>(SrcI->getOperand(1)))
864 if (BinaryOperator *And = dyn_cast<BinaryOperator>(SrcI->getOperand(0)))
865 if (And->getOpcode() == Instruction::And && And->hasOneUse() &&
866 And->getOperand(1) == C)
867 if (TruncInst *TI = dyn_cast<TruncInst>(And->getOperand(0))) {
868 Value *TI0 = TI->getOperand(0);
869 if (TI0->getType() == CI.getType()) {
870 Constant *ZC = ConstantExpr::getZExt(C, CI.getType());
871 Value *NewAnd = Builder->CreateAnd(TI0, ZC);
872 return BinaryOperator::CreateXor(NewAnd, ZC);
873 }
874 }
875
876 // zext (xor i1 X, true) to i32 --> xor (zext i1 X to i32), 1
877 Value *X;
878 if (SrcI && SrcI->hasOneUse() && SrcI->getType()->isIntegerTy(1) &&
879 match(SrcI, m_Not(m_Value(X))) &&
880 (!X->hasOneUse() || !isa<CmpInst>(X))) {
881 Value *New = Builder->CreateZExt(X, CI.getType());
882 return BinaryOperator::CreateXor(New, ConstantInt::get(CI.getType(), 1));
883 }
884
885 return 0;
886 }
887
888 /// transformSExtICmp - Transform (sext icmp) to bitwise / integer operations
889 /// in order to eliminate the icmp.
transformSExtICmp(ICmpInst * ICI,Instruction & CI)890 Instruction *InstCombiner::transformSExtICmp(ICmpInst *ICI, Instruction &CI) {
891 Value *Op0 = ICI->getOperand(0), *Op1 = ICI->getOperand(1);
892 ICmpInst::Predicate Pred = ICI->getPredicate();
893
894 if (ConstantInt *Op1C = dyn_cast<ConstantInt>(Op1)) {
895 // (x <s 0) ? -1 : 0 -> ashr x, 31 -> all ones if negative
896 // (x >s -1) ? -1 : 0 -> not (ashr x, 31) -> all ones if positive
897 if ((Pred == ICmpInst::ICMP_SLT && Op1C->isZero()) ||
898 (Pred == ICmpInst::ICMP_SGT && Op1C->isAllOnesValue())) {
899
900 Value *Sh = ConstantInt::get(Op0->getType(),
901 Op0->getType()->getScalarSizeInBits()-1);
902 Value *In = Builder->CreateAShr(Op0, Sh, Op0->getName()+".lobit");
903 if (In->getType() != CI.getType())
904 In = Builder->CreateIntCast(In, CI.getType(), true/*SExt*/);
905
906 if (Pred == ICmpInst::ICMP_SGT)
907 In = Builder->CreateNot(In, In->getName()+".not");
908 return ReplaceInstUsesWith(CI, In);
909 }
910
911 // If we know that only one bit of the LHS of the icmp can be set and we
912 // have an equality comparison with zero or a power of 2, we can transform
913 // the icmp and sext into bitwise/integer operations.
914 if (ICI->hasOneUse() &&
915 ICI->isEquality() && (Op1C->isZero() || Op1C->getValue().isPowerOf2())){
916 unsigned BitWidth = Op1C->getType()->getBitWidth();
917 APInt KnownZero(BitWidth, 0), KnownOne(BitWidth, 0);
918 APInt TypeMask(APInt::getAllOnesValue(BitWidth));
919 ComputeMaskedBits(Op0, TypeMask, KnownZero, KnownOne);
920
921 APInt KnownZeroMask(~KnownZero);
922 if (KnownZeroMask.isPowerOf2()) {
923 Value *In = ICI->getOperand(0);
924
925 // If the icmp tests for a known zero bit we can constant fold it.
926 if (!Op1C->isZero() && Op1C->getValue() != KnownZeroMask) {
927 Value *V = Pred == ICmpInst::ICMP_NE ?
928 ConstantInt::getAllOnesValue(CI.getType()) :
929 ConstantInt::getNullValue(CI.getType());
930 return ReplaceInstUsesWith(CI, V);
931 }
932
933 if (!Op1C->isZero() == (Pred == ICmpInst::ICMP_NE)) {
934 // sext ((x & 2^n) == 0) -> (x >> n) - 1
935 // sext ((x & 2^n) != 2^n) -> (x >> n) - 1
936 unsigned ShiftAmt = KnownZeroMask.countTrailingZeros();
937 // Perform a right shift to place the desired bit in the LSB.
938 if (ShiftAmt)
939 In = Builder->CreateLShr(In,
940 ConstantInt::get(In->getType(), ShiftAmt));
941
942 // At this point "In" is either 1 or 0. Subtract 1 to turn
943 // {1, 0} -> {0, -1}.
944 In = Builder->CreateAdd(In,
945 ConstantInt::getAllOnesValue(In->getType()),
946 "sext");
947 } else {
948 // sext ((x & 2^n) != 0) -> (x << bitwidth-n) a>> bitwidth-1
949 // sext ((x & 2^n) == 2^n) -> (x << bitwidth-n) a>> bitwidth-1
950 unsigned ShiftAmt = KnownZeroMask.countLeadingZeros();
951 // Perform a left shift to place the desired bit in the MSB.
952 if (ShiftAmt)
953 In = Builder->CreateShl(In,
954 ConstantInt::get(In->getType(), ShiftAmt));
955
956 // Distribute the bit over the whole bit width.
957 In = Builder->CreateAShr(In, ConstantInt::get(In->getType(),
958 BitWidth - 1), "sext");
959 }
960
961 if (CI.getType() == In->getType())
962 return ReplaceInstUsesWith(CI, In);
963 return CastInst::CreateIntegerCast(In, CI.getType(), true/*SExt*/);
964 }
965 }
966 }
967
968 // vector (x <s 0) ? -1 : 0 -> ashr x, 31 -> all ones if signed.
969 if (VectorType *VTy = dyn_cast<VectorType>(CI.getType())) {
970 if (Pred == ICmpInst::ICMP_SLT && match(Op1, m_Zero()) &&
971 Op0->getType() == CI.getType()) {
972 Type *EltTy = VTy->getElementType();
973
974 // splat the shift constant to a constant vector.
975 Constant *VSh = ConstantInt::get(VTy, EltTy->getScalarSizeInBits()-1);
976 Value *In = Builder->CreateAShr(Op0, VSh, Op0->getName()+".lobit");
977 return ReplaceInstUsesWith(CI, In);
978 }
979 }
980
981 return 0;
982 }
983
984 /// CanEvaluateSExtd - Return true if we can take the specified value
985 /// and return it as type Ty without inserting any new casts and without
986 /// changing the value of the common low bits. This is used by code that tries
987 /// to promote integer operations to a wider types will allow us to eliminate
988 /// the extension.
989 ///
990 /// This function works on both vectors and scalars.
991 ///
CanEvaluateSExtd(Value * V,Type * Ty)992 static bool CanEvaluateSExtd(Value *V, Type *Ty) {
993 assert(V->getType()->getScalarSizeInBits() < Ty->getScalarSizeInBits() &&
994 "Can't sign extend type to a smaller type");
995 // If this is a constant, it can be trivially promoted.
996 if (isa<Constant>(V))
997 return true;
998
999 Instruction *I = dyn_cast<Instruction>(V);
1000 if (!I) return false;
1001
1002 // If this is a truncate from the dest type, we can trivially eliminate it,
1003 // even if it has multiple uses.
1004 // FIXME: This is currently disabled until codegen can handle this without
1005 // pessimizing code, PR5997.
1006 if (0 && isa<TruncInst>(I) && I->getOperand(0)->getType() == Ty)
1007 return true;
1008
1009 // We can't extend or shrink something that has multiple uses: doing so would
1010 // require duplicating the instruction in general, which isn't profitable.
1011 if (!I->hasOneUse()) return false;
1012
1013 switch (I->getOpcode()) {
1014 case Instruction::SExt: // sext(sext(x)) -> sext(x)
1015 case Instruction::ZExt: // sext(zext(x)) -> zext(x)
1016 case Instruction::Trunc: // sext(trunc(x)) -> trunc(x) or sext(x)
1017 return true;
1018 case Instruction::And:
1019 case Instruction::Or:
1020 case Instruction::Xor:
1021 case Instruction::Add:
1022 case Instruction::Sub:
1023 case Instruction::Mul:
1024 // These operators can all arbitrarily be extended if their inputs can.
1025 return CanEvaluateSExtd(I->getOperand(0), Ty) &&
1026 CanEvaluateSExtd(I->getOperand(1), Ty);
1027
1028 //case Instruction::Shl: TODO
1029 //case Instruction::LShr: TODO
1030
1031 case Instruction::Select:
1032 return CanEvaluateSExtd(I->getOperand(1), Ty) &&
1033 CanEvaluateSExtd(I->getOperand(2), Ty);
1034
1035 case Instruction::PHI: {
1036 // We can change a phi if we can change all operands. Note that we never
1037 // get into trouble with cyclic PHIs here because we only consider
1038 // instructions with a single use.
1039 PHINode *PN = cast<PHINode>(I);
1040 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i)
1041 if (!CanEvaluateSExtd(PN->getIncomingValue(i), Ty)) return false;
1042 return true;
1043 }
1044 default:
1045 // TODO: Can handle more cases here.
1046 break;
1047 }
1048
1049 return false;
1050 }
1051
visitSExt(SExtInst & CI)1052 Instruction *InstCombiner::visitSExt(SExtInst &CI) {
1053 // If this sign extend is only used by a truncate, let the truncate by
1054 // eliminated before we try to optimize this zext.
1055 if (CI.hasOneUse() && isa<TruncInst>(CI.use_back()))
1056 return 0;
1057
1058 if (Instruction *I = commonCastTransforms(CI))
1059 return I;
1060
1061 // See if we can simplify any instructions used by the input whose sole
1062 // purpose is to compute bits we don't care about.
1063 if (SimplifyDemandedInstructionBits(CI))
1064 return &CI;
1065
1066 Value *Src = CI.getOperand(0);
1067 Type *SrcTy = Src->getType(), *DestTy = CI.getType();
1068
1069 // Attempt to extend the entire input expression tree to the destination
1070 // type. Only do this if the dest type is a simple type, don't convert the
1071 // expression tree to something weird like i93 unless the source is also
1072 // strange.
1073 if ((DestTy->isVectorTy() || ShouldChangeType(SrcTy, DestTy)) &&
1074 CanEvaluateSExtd(Src, DestTy)) {
1075 // Okay, we can transform this! Insert the new expression now.
1076 DEBUG(dbgs() << "ICE: EvaluateInDifferentType converting expression type"
1077 " to avoid sign extend: " << CI);
1078 Value *Res = EvaluateInDifferentType(Src, DestTy, true);
1079 assert(Res->getType() == DestTy);
1080
1081 uint32_t SrcBitSize = SrcTy->getScalarSizeInBits();
1082 uint32_t DestBitSize = DestTy->getScalarSizeInBits();
1083
1084 // If the high bits are already filled with sign bit, just replace this
1085 // cast with the result.
1086 if (ComputeNumSignBits(Res) > DestBitSize - SrcBitSize)
1087 return ReplaceInstUsesWith(CI, Res);
1088
1089 // We need to emit a shl + ashr to do the sign extend.
1090 Value *ShAmt = ConstantInt::get(DestTy, DestBitSize-SrcBitSize);
1091 return BinaryOperator::CreateAShr(Builder->CreateShl(Res, ShAmt, "sext"),
1092 ShAmt);
1093 }
1094
1095 // If this input is a trunc from our destination, then turn sext(trunc(x))
1096 // into shifts.
1097 if (TruncInst *TI = dyn_cast<TruncInst>(Src))
1098 if (TI->hasOneUse() && TI->getOperand(0)->getType() == DestTy) {
1099 uint32_t SrcBitSize = SrcTy->getScalarSizeInBits();
1100 uint32_t DestBitSize = DestTy->getScalarSizeInBits();
1101
1102 // We need to emit a shl + ashr to do the sign extend.
1103 Value *ShAmt = ConstantInt::get(DestTy, DestBitSize-SrcBitSize);
1104 Value *Res = Builder->CreateShl(TI->getOperand(0), ShAmt, "sext");
1105 return BinaryOperator::CreateAShr(Res, ShAmt);
1106 }
1107
1108 if (ICmpInst *ICI = dyn_cast<ICmpInst>(Src))
1109 return transformSExtICmp(ICI, CI);
1110
1111 // If the input is a shl/ashr pair of a same constant, then this is a sign
1112 // extension from a smaller value. If we could trust arbitrary bitwidth
1113 // integers, we could turn this into a truncate to the smaller bit and then
1114 // use a sext for the whole extension. Since we don't, look deeper and check
1115 // for a truncate. If the source and dest are the same type, eliminate the
1116 // trunc and extend and just do shifts. For example, turn:
1117 // %a = trunc i32 %i to i8
1118 // %b = shl i8 %a, 6
1119 // %c = ashr i8 %b, 6
1120 // %d = sext i8 %c to i32
1121 // into:
1122 // %a = shl i32 %i, 30
1123 // %d = ashr i32 %a, 30
1124 Value *A = 0;
1125 // TODO: Eventually this could be subsumed by EvaluateInDifferentType.
1126 ConstantInt *BA = 0, *CA = 0;
1127 if (match(Src, m_AShr(m_Shl(m_Trunc(m_Value(A)), m_ConstantInt(BA)),
1128 m_ConstantInt(CA))) &&
1129 BA == CA && A->getType() == CI.getType()) {
1130 unsigned MidSize = Src->getType()->getScalarSizeInBits();
1131 unsigned SrcDstSize = CI.getType()->getScalarSizeInBits();
1132 unsigned ShAmt = CA->getZExtValue()+SrcDstSize-MidSize;
1133 Constant *ShAmtV = ConstantInt::get(CI.getType(), ShAmt);
1134 A = Builder->CreateShl(A, ShAmtV, CI.getName());
1135 return BinaryOperator::CreateAShr(A, ShAmtV);
1136 }
1137
1138 return 0;
1139 }
1140
1141
1142 /// FitsInFPType - Return a Constant* for the specified FP constant if it fits
1143 /// in the specified FP type without changing its value.
FitsInFPType(ConstantFP * CFP,const fltSemantics & Sem)1144 static Constant *FitsInFPType(ConstantFP *CFP, const fltSemantics &Sem) {
1145 bool losesInfo;
1146 APFloat F = CFP->getValueAPF();
1147 (void)F.convert(Sem, APFloat::rmNearestTiesToEven, &losesInfo);
1148 if (!losesInfo)
1149 return ConstantFP::get(CFP->getContext(), F);
1150 return 0;
1151 }
1152
1153 /// LookThroughFPExtensions - If this is an fp extension instruction, look
1154 /// through it until we get the source value.
LookThroughFPExtensions(Value * V)1155 static Value *LookThroughFPExtensions(Value *V) {
1156 if (Instruction *I = dyn_cast<Instruction>(V))
1157 if (I->getOpcode() == Instruction::FPExt)
1158 return LookThroughFPExtensions(I->getOperand(0));
1159
1160 // If this value is a constant, return the constant in the smallest FP type
1161 // that can accurately represent it. This allows us to turn
1162 // (float)((double)X+2.0) into x+2.0f.
1163 if (ConstantFP *CFP = dyn_cast<ConstantFP>(V)) {
1164 if (CFP->getType() == Type::getPPC_FP128Ty(V->getContext()))
1165 return V; // No constant folding of this.
1166 // See if the value can be truncated to float and then reextended.
1167 if (Value *V = FitsInFPType(CFP, APFloat::IEEEsingle))
1168 return V;
1169 if (CFP->getType()->isDoubleTy())
1170 return V; // Won't shrink.
1171 if (Value *V = FitsInFPType(CFP, APFloat::IEEEdouble))
1172 return V;
1173 // Don't try to shrink to various long double types.
1174 }
1175
1176 return V;
1177 }
1178
visitFPTrunc(FPTruncInst & CI)1179 Instruction *InstCombiner::visitFPTrunc(FPTruncInst &CI) {
1180 if (Instruction *I = commonCastTransforms(CI))
1181 return I;
1182
1183 // If we have fptrunc(fadd (fpextend x), (fpextend y)), where x and y are
1184 // smaller than the destination type, we can eliminate the truncate by doing
1185 // the add as the smaller type. This applies to fadd/fsub/fmul/fdiv as well
1186 // as many builtins (sqrt, etc).
1187 BinaryOperator *OpI = dyn_cast<BinaryOperator>(CI.getOperand(0));
1188 if (OpI && OpI->hasOneUse()) {
1189 switch (OpI->getOpcode()) {
1190 default: break;
1191 case Instruction::FAdd:
1192 case Instruction::FSub:
1193 case Instruction::FMul:
1194 case Instruction::FDiv:
1195 case Instruction::FRem:
1196 Type *SrcTy = OpI->getType();
1197 Value *LHSTrunc = LookThroughFPExtensions(OpI->getOperand(0));
1198 Value *RHSTrunc = LookThroughFPExtensions(OpI->getOperand(1));
1199 if (LHSTrunc->getType() != SrcTy &&
1200 RHSTrunc->getType() != SrcTy) {
1201 unsigned DstSize = CI.getType()->getScalarSizeInBits();
1202 // If the source types were both smaller than the destination type of
1203 // the cast, do this xform.
1204 if (LHSTrunc->getType()->getScalarSizeInBits() <= DstSize &&
1205 RHSTrunc->getType()->getScalarSizeInBits() <= DstSize) {
1206 LHSTrunc = Builder->CreateFPExt(LHSTrunc, CI.getType());
1207 RHSTrunc = Builder->CreateFPExt(RHSTrunc, CI.getType());
1208 return BinaryOperator::Create(OpI->getOpcode(), LHSTrunc, RHSTrunc);
1209 }
1210 }
1211 break;
1212 }
1213 }
1214
1215 // Fold (fptrunc (sqrt (fpext x))) -> (sqrtf x)
1216 // NOTE: This should be disabled by -fno-builtin-sqrt if we ever support it.
1217 CallInst *Call = dyn_cast<CallInst>(CI.getOperand(0));
1218 if (Call && Call->getCalledFunction() &&
1219 Call->getCalledFunction()->getName() == "sqrt" &&
1220 Call->getNumArgOperands() == 1 &&
1221 Call->hasOneUse()) {
1222 CastInst *Arg = dyn_cast<CastInst>(Call->getArgOperand(0));
1223 if (Arg && Arg->getOpcode() == Instruction::FPExt &&
1224 CI.getType()->isFloatTy() &&
1225 Call->getType()->isDoubleTy() &&
1226 Arg->getType()->isDoubleTy() &&
1227 Arg->getOperand(0)->getType()->isFloatTy()) {
1228 Function *Callee = Call->getCalledFunction();
1229 Module *M = CI.getParent()->getParent()->getParent();
1230 Constant *SqrtfFunc = M->getOrInsertFunction("sqrtf",
1231 Callee->getAttributes(),
1232 Builder->getFloatTy(),
1233 Builder->getFloatTy(),
1234 NULL);
1235 CallInst *ret = CallInst::Create(SqrtfFunc, Arg->getOperand(0),
1236 "sqrtfcall");
1237 ret->setAttributes(Callee->getAttributes());
1238
1239
1240 // Remove the old Call. With -fmath-errno, it won't get marked readnone.
1241 ReplaceInstUsesWith(*Call, UndefValue::get(Call->getType()));
1242 EraseInstFromFunction(*Call);
1243 return ret;
1244 }
1245 }
1246
1247 return 0;
1248 }
1249
visitFPExt(CastInst & CI)1250 Instruction *InstCombiner::visitFPExt(CastInst &CI) {
1251 return commonCastTransforms(CI);
1252 }
1253
visitFPToUI(FPToUIInst & FI)1254 Instruction *InstCombiner::visitFPToUI(FPToUIInst &FI) {
1255 Instruction *OpI = dyn_cast<Instruction>(FI.getOperand(0));
1256 if (OpI == 0)
1257 return commonCastTransforms(FI);
1258
1259 // fptoui(uitofp(X)) --> X
1260 // fptoui(sitofp(X)) --> X
1261 // This is safe if the intermediate type has enough bits in its mantissa to
1262 // accurately represent all values of X. For example, do not do this with
1263 // i64->float->i64. This is also safe for sitofp case, because any negative
1264 // 'X' value would cause an undefined result for the fptoui.
1265 if ((isa<UIToFPInst>(OpI) || isa<SIToFPInst>(OpI)) &&
1266 OpI->getOperand(0)->getType() == FI.getType() &&
1267 (int)FI.getType()->getScalarSizeInBits() < /*extra bit for sign */
1268 OpI->getType()->getFPMantissaWidth())
1269 return ReplaceInstUsesWith(FI, OpI->getOperand(0));
1270
1271 return commonCastTransforms(FI);
1272 }
1273
visitFPToSI(FPToSIInst & FI)1274 Instruction *InstCombiner::visitFPToSI(FPToSIInst &FI) {
1275 Instruction *OpI = dyn_cast<Instruction>(FI.getOperand(0));
1276 if (OpI == 0)
1277 return commonCastTransforms(FI);
1278
1279 // fptosi(sitofp(X)) --> X
1280 // fptosi(uitofp(X)) --> X
1281 // This is safe if the intermediate type has enough bits in its mantissa to
1282 // accurately represent all values of X. For example, do not do this with
1283 // i64->float->i64. This is also safe for sitofp case, because any negative
1284 // 'X' value would cause an undefined result for the fptoui.
1285 if ((isa<UIToFPInst>(OpI) || isa<SIToFPInst>(OpI)) &&
1286 OpI->getOperand(0)->getType() == FI.getType() &&
1287 (int)FI.getType()->getScalarSizeInBits() <=
1288 OpI->getType()->getFPMantissaWidth())
1289 return ReplaceInstUsesWith(FI, OpI->getOperand(0));
1290
1291 return commonCastTransforms(FI);
1292 }
1293
visitUIToFP(CastInst & CI)1294 Instruction *InstCombiner::visitUIToFP(CastInst &CI) {
1295 return commonCastTransforms(CI);
1296 }
1297
visitSIToFP(CastInst & CI)1298 Instruction *InstCombiner::visitSIToFP(CastInst &CI) {
1299 return commonCastTransforms(CI);
1300 }
1301
visitIntToPtr(IntToPtrInst & CI)1302 Instruction *InstCombiner::visitIntToPtr(IntToPtrInst &CI) {
1303 // If the source integer type is not the intptr_t type for this target, do a
1304 // trunc or zext to the intptr_t type, then inttoptr of it. This allows the
1305 // cast to be exposed to other transforms.
1306 if (TD) {
1307 if (CI.getOperand(0)->getType()->getScalarSizeInBits() >
1308 TD->getPointerSizeInBits()) {
1309 Value *P = Builder->CreateTrunc(CI.getOperand(0),
1310 TD->getIntPtrType(CI.getContext()));
1311 return new IntToPtrInst(P, CI.getType());
1312 }
1313 if (CI.getOperand(0)->getType()->getScalarSizeInBits() <
1314 TD->getPointerSizeInBits()) {
1315 Value *P = Builder->CreateZExt(CI.getOperand(0),
1316 TD->getIntPtrType(CI.getContext()));
1317 return new IntToPtrInst(P, CI.getType());
1318 }
1319 }
1320
1321 if (Instruction *I = commonCastTransforms(CI))
1322 return I;
1323
1324 return 0;
1325 }
1326
1327 /// @brief Implement the transforms for cast of pointer (bitcast/ptrtoint)
commonPointerCastTransforms(CastInst & CI)1328 Instruction *InstCombiner::commonPointerCastTransforms(CastInst &CI) {
1329 Value *Src = CI.getOperand(0);
1330
1331 if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(Src)) {
1332 // If casting the result of a getelementptr instruction with no offset, turn
1333 // this into a cast of the original pointer!
1334 if (GEP->hasAllZeroIndices()) {
1335 // Changing the cast operand is usually not a good idea but it is safe
1336 // here because the pointer operand is being replaced with another
1337 // pointer operand so the opcode doesn't need to change.
1338 Worklist.Add(GEP);
1339 CI.setOperand(0, GEP->getOperand(0));
1340 return &CI;
1341 }
1342
1343 // If the GEP has a single use, and the base pointer is a bitcast, and the
1344 // GEP computes a constant offset, see if we can convert these three
1345 // instructions into fewer. This typically happens with unions and other
1346 // non-type-safe code.
1347 if (TD && GEP->hasOneUse() && isa<BitCastInst>(GEP->getOperand(0)) &&
1348 GEP->hasAllConstantIndices()) {
1349 // We are guaranteed to get a constant from EmitGEPOffset.
1350 ConstantInt *OffsetV = cast<ConstantInt>(EmitGEPOffset(GEP));
1351 int64_t Offset = OffsetV->getSExtValue();
1352
1353 // Get the base pointer input of the bitcast, and the type it points to.
1354 Value *OrigBase = cast<BitCastInst>(GEP->getOperand(0))->getOperand(0);
1355 Type *GEPIdxTy =
1356 cast<PointerType>(OrigBase->getType())->getElementType();
1357 SmallVector<Value*, 8> NewIndices;
1358 if (FindElementAtOffset(GEPIdxTy, Offset, NewIndices)) {
1359 // If we were able to index down into an element, create the GEP
1360 // and bitcast the result. This eliminates one bitcast, potentially
1361 // two.
1362 Value *NGEP = cast<GEPOperator>(GEP)->isInBounds() ?
1363 Builder->CreateInBoundsGEP(OrigBase, NewIndices) :
1364 Builder->CreateGEP(OrigBase, NewIndices);
1365 NGEP->takeName(GEP);
1366
1367 if (isa<BitCastInst>(CI))
1368 return new BitCastInst(NGEP, CI.getType());
1369 assert(isa<PtrToIntInst>(CI));
1370 return new PtrToIntInst(NGEP, CI.getType());
1371 }
1372 }
1373 }
1374
1375 return commonCastTransforms(CI);
1376 }
1377
visitPtrToInt(PtrToIntInst & CI)1378 Instruction *InstCombiner::visitPtrToInt(PtrToIntInst &CI) {
1379 // If the destination integer type is not the intptr_t type for this target,
1380 // do a ptrtoint to intptr_t then do a trunc or zext. This allows the cast
1381 // to be exposed to other transforms.
1382 if (TD) {
1383 if (CI.getType()->getScalarSizeInBits() < TD->getPointerSizeInBits()) {
1384 Value *P = Builder->CreatePtrToInt(CI.getOperand(0),
1385 TD->getIntPtrType(CI.getContext()));
1386 return new TruncInst(P, CI.getType());
1387 }
1388 if (CI.getType()->getScalarSizeInBits() > TD->getPointerSizeInBits()) {
1389 Value *P = Builder->CreatePtrToInt(CI.getOperand(0),
1390 TD->getIntPtrType(CI.getContext()));
1391 return new ZExtInst(P, CI.getType());
1392 }
1393 }
1394
1395 return commonPointerCastTransforms(CI);
1396 }
1397
1398 /// OptimizeVectorResize - This input value (which is known to have vector type)
1399 /// is being zero extended or truncated to the specified vector type. Try to
1400 /// replace it with a shuffle (and vector/vector bitcast) if possible.
1401 ///
1402 /// The source and destination vector types may have different element types.
OptimizeVectorResize(Value * InVal,VectorType * DestTy,InstCombiner & IC)1403 static Instruction *OptimizeVectorResize(Value *InVal, VectorType *DestTy,
1404 InstCombiner &IC) {
1405 // We can only do this optimization if the output is a multiple of the input
1406 // element size, or the input is a multiple of the output element size.
1407 // Convert the input type to have the same element type as the output.
1408 VectorType *SrcTy = cast<VectorType>(InVal->getType());
1409
1410 if (SrcTy->getElementType() != DestTy->getElementType()) {
1411 // The input types don't need to be identical, but for now they must be the
1412 // same size. There is no specific reason we couldn't handle things like
1413 // <4 x i16> -> <4 x i32> by bitcasting to <2 x i32> but haven't gotten
1414 // there yet.
1415 if (SrcTy->getElementType()->getPrimitiveSizeInBits() !=
1416 DestTy->getElementType()->getPrimitiveSizeInBits())
1417 return 0;
1418
1419 SrcTy = VectorType::get(DestTy->getElementType(), SrcTy->getNumElements());
1420 InVal = IC.Builder->CreateBitCast(InVal, SrcTy);
1421 }
1422
1423 // Now that the element types match, get the shuffle mask and RHS of the
1424 // shuffle to use, which depends on whether we're increasing or decreasing the
1425 // size of the input.
1426 SmallVector<Constant*, 16> ShuffleMask;
1427 Value *V2;
1428 IntegerType *Int32Ty = Type::getInt32Ty(SrcTy->getContext());
1429
1430 if (SrcTy->getNumElements() > DestTy->getNumElements()) {
1431 // If we're shrinking the number of elements, just shuffle in the low
1432 // elements from the input and use undef as the second shuffle input.
1433 V2 = UndefValue::get(SrcTy);
1434 for (unsigned i = 0, e = DestTy->getNumElements(); i != e; ++i)
1435 ShuffleMask.push_back(ConstantInt::get(Int32Ty, i));
1436
1437 } else {
1438 // If we're increasing the number of elements, shuffle in all of the
1439 // elements from InVal and fill the rest of the result elements with zeros
1440 // from a constant zero.
1441 V2 = Constant::getNullValue(SrcTy);
1442 unsigned SrcElts = SrcTy->getNumElements();
1443 for (unsigned i = 0, e = SrcElts; i != e; ++i)
1444 ShuffleMask.push_back(ConstantInt::get(Int32Ty, i));
1445
1446 // The excess elements reference the first element of the zero input.
1447 ShuffleMask.append(DestTy->getNumElements()-SrcElts,
1448 ConstantInt::get(Int32Ty, SrcElts));
1449 }
1450
1451 return new ShuffleVectorInst(InVal, V2, ConstantVector::get(ShuffleMask));
1452 }
1453
isMultipleOfTypeSize(unsigned Value,Type * Ty)1454 static bool isMultipleOfTypeSize(unsigned Value, Type *Ty) {
1455 return Value % Ty->getPrimitiveSizeInBits() == 0;
1456 }
1457
getTypeSizeIndex(unsigned Value,Type * Ty)1458 static unsigned getTypeSizeIndex(unsigned Value, Type *Ty) {
1459 return Value / Ty->getPrimitiveSizeInBits();
1460 }
1461
1462 /// CollectInsertionElements - V is a value which is inserted into a vector of
1463 /// VecEltTy. Look through the value to see if we can decompose it into
1464 /// insertions into the vector. See the example in the comment for
1465 /// OptimizeIntegerToVectorInsertions for the pattern this handles.
1466 /// The type of V is always a non-zero multiple of VecEltTy's size.
1467 ///
1468 /// This returns false if the pattern can't be matched or true if it can,
1469 /// filling in Elements with the elements found here.
CollectInsertionElements(Value * V,unsigned ElementIndex,SmallVectorImpl<Value * > & Elements,Type * VecEltTy)1470 static bool CollectInsertionElements(Value *V, unsigned ElementIndex,
1471 SmallVectorImpl<Value*> &Elements,
1472 Type *VecEltTy) {
1473 // Undef values never contribute useful bits to the result.
1474 if (isa<UndefValue>(V)) return true;
1475
1476 // If we got down to a value of the right type, we win, try inserting into the
1477 // right element.
1478 if (V->getType() == VecEltTy) {
1479 // Inserting null doesn't actually insert any elements.
1480 if (Constant *C = dyn_cast<Constant>(V))
1481 if (C->isNullValue())
1482 return true;
1483
1484 // Fail if multiple elements are inserted into this slot.
1485 if (ElementIndex >= Elements.size() || Elements[ElementIndex] != 0)
1486 return false;
1487
1488 Elements[ElementIndex] = V;
1489 return true;
1490 }
1491
1492 if (Constant *C = dyn_cast<Constant>(V)) {
1493 // Figure out the # elements this provides, and bitcast it or slice it up
1494 // as required.
1495 unsigned NumElts = getTypeSizeIndex(C->getType()->getPrimitiveSizeInBits(),
1496 VecEltTy);
1497 // If the constant is the size of a vector element, we just need to bitcast
1498 // it to the right type so it gets properly inserted.
1499 if (NumElts == 1)
1500 return CollectInsertionElements(ConstantExpr::getBitCast(C, VecEltTy),
1501 ElementIndex, Elements, VecEltTy);
1502
1503 // Okay, this is a constant that covers multiple elements. Slice it up into
1504 // pieces and insert each element-sized piece into the vector.
1505 if (!isa<IntegerType>(C->getType()))
1506 C = ConstantExpr::getBitCast(C, IntegerType::get(V->getContext(),
1507 C->getType()->getPrimitiveSizeInBits()));
1508 unsigned ElementSize = VecEltTy->getPrimitiveSizeInBits();
1509 Type *ElementIntTy = IntegerType::get(C->getContext(), ElementSize);
1510
1511 for (unsigned i = 0; i != NumElts; ++i) {
1512 Constant *Piece = ConstantExpr::getLShr(C, ConstantInt::get(C->getType(),
1513 i*ElementSize));
1514 Piece = ConstantExpr::getTrunc(Piece, ElementIntTy);
1515 if (!CollectInsertionElements(Piece, ElementIndex+i, Elements, VecEltTy))
1516 return false;
1517 }
1518 return true;
1519 }
1520
1521 if (!V->hasOneUse()) return false;
1522
1523 Instruction *I = dyn_cast<Instruction>(V);
1524 if (I == 0) return false;
1525 switch (I->getOpcode()) {
1526 default: return false; // Unhandled case.
1527 case Instruction::BitCast:
1528 return CollectInsertionElements(I->getOperand(0), ElementIndex,
1529 Elements, VecEltTy);
1530 case Instruction::ZExt:
1531 if (!isMultipleOfTypeSize(
1532 I->getOperand(0)->getType()->getPrimitiveSizeInBits(),
1533 VecEltTy))
1534 return false;
1535 return CollectInsertionElements(I->getOperand(0), ElementIndex,
1536 Elements, VecEltTy);
1537 case Instruction::Or:
1538 return CollectInsertionElements(I->getOperand(0), ElementIndex,
1539 Elements, VecEltTy) &&
1540 CollectInsertionElements(I->getOperand(1), ElementIndex,
1541 Elements, VecEltTy);
1542 case Instruction::Shl: {
1543 // Must be shifting by a constant that is a multiple of the element size.
1544 ConstantInt *CI = dyn_cast<ConstantInt>(I->getOperand(1));
1545 if (CI == 0) return false;
1546 if (!isMultipleOfTypeSize(CI->getZExtValue(), VecEltTy)) return false;
1547 unsigned IndexShift = getTypeSizeIndex(CI->getZExtValue(), VecEltTy);
1548
1549 return CollectInsertionElements(I->getOperand(0), ElementIndex+IndexShift,
1550 Elements, VecEltTy);
1551 }
1552
1553 }
1554 }
1555
1556
1557 /// OptimizeIntegerToVectorInsertions - If the input is an 'or' instruction, we
1558 /// may be doing shifts and ors to assemble the elements of the vector manually.
1559 /// Try to rip the code out and replace it with insertelements. This is to
1560 /// optimize code like this:
1561 ///
1562 /// %tmp37 = bitcast float %inc to i32
1563 /// %tmp38 = zext i32 %tmp37 to i64
1564 /// %tmp31 = bitcast float %inc5 to i32
1565 /// %tmp32 = zext i32 %tmp31 to i64
1566 /// %tmp33 = shl i64 %tmp32, 32
1567 /// %ins35 = or i64 %tmp33, %tmp38
1568 /// %tmp43 = bitcast i64 %ins35 to <2 x float>
1569 ///
1570 /// Into two insertelements that do "buildvector{%inc, %inc5}".
OptimizeIntegerToVectorInsertions(BitCastInst & CI,InstCombiner & IC)1571 static Value *OptimizeIntegerToVectorInsertions(BitCastInst &CI,
1572 InstCombiner &IC) {
1573 VectorType *DestVecTy = cast<VectorType>(CI.getType());
1574 Value *IntInput = CI.getOperand(0);
1575
1576 SmallVector<Value*, 8> Elements(DestVecTy->getNumElements());
1577 if (!CollectInsertionElements(IntInput, 0, Elements,
1578 DestVecTy->getElementType()))
1579 return 0;
1580
1581 // If we succeeded, we know that all of the element are specified by Elements
1582 // or are zero if Elements has a null entry. Recast this as a set of
1583 // insertions.
1584 Value *Result = Constant::getNullValue(CI.getType());
1585 for (unsigned i = 0, e = Elements.size(); i != e; ++i) {
1586 if (Elements[i] == 0) continue; // Unset element.
1587
1588 Result = IC.Builder->CreateInsertElement(Result, Elements[i],
1589 IC.Builder->getInt32(i));
1590 }
1591
1592 return Result;
1593 }
1594
1595
1596 /// OptimizeIntToFloatBitCast - See if we can optimize an integer->float/double
1597 /// bitcast. The various long double bitcasts can't get in here.
OptimizeIntToFloatBitCast(BitCastInst & CI,InstCombiner & IC)1598 static Instruction *OptimizeIntToFloatBitCast(BitCastInst &CI,InstCombiner &IC){
1599 Value *Src = CI.getOperand(0);
1600 Type *DestTy = CI.getType();
1601
1602 // If this is a bitcast from int to float, check to see if the int is an
1603 // extraction from a vector.
1604 Value *VecInput = 0;
1605 // bitcast(trunc(bitcast(somevector)))
1606 if (match(Src, m_Trunc(m_BitCast(m_Value(VecInput)))) &&
1607 isa<VectorType>(VecInput->getType())) {
1608 VectorType *VecTy = cast<VectorType>(VecInput->getType());
1609 unsigned DestWidth = DestTy->getPrimitiveSizeInBits();
1610
1611 if (VecTy->getPrimitiveSizeInBits() % DestWidth == 0) {
1612 // If the element type of the vector doesn't match the result type,
1613 // bitcast it to be a vector type we can extract from.
1614 if (VecTy->getElementType() != DestTy) {
1615 VecTy = VectorType::get(DestTy,
1616 VecTy->getPrimitiveSizeInBits() / DestWidth);
1617 VecInput = IC.Builder->CreateBitCast(VecInput, VecTy);
1618 }
1619
1620 return ExtractElementInst::Create(VecInput, IC.Builder->getInt32(0));
1621 }
1622 }
1623
1624 // bitcast(trunc(lshr(bitcast(somevector), cst))
1625 ConstantInt *ShAmt = 0;
1626 if (match(Src, m_Trunc(m_LShr(m_BitCast(m_Value(VecInput)),
1627 m_ConstantInt(ShAmt)))) &&
1628 isa<VectorType>(VecInput->getType())) {
1629 VectorType *VecTy = cast<VectorType>(VecInput->getType());
1630 unsigned DestWidth = DestTy->getPrimitiveSizeInBits();
1631 if (VecTy->getPrimitiveSizeInBits() % DestWidth == 0 &&
1632 ShAmt->getZExtValue() % DestWidth == 0) {
1633 // If the element type of the vector doesn't match the result type,
1634 // bitcast it to be a vector type we can extract from.
1635 if (VecTy->getElementType() != DestTy) {
1636 VecTy = VectorType::get(DestTy,
1637 VecTy->getPrimitiveSizeInBits() / DestWidth);
1638 VecInput = IC.Builder->CreateBitCast(VecInput, VecTy);
1639 }
1640
1641 unsigned Elt = ShAmt->getZExtValue() / DestWidth;
1642 return ExtractElementInst::Create(VecInput, IC.Builder->getInt32(Elt));
1643 }
1644 }
1645 return 0;
1646 }
1647
visitBitCast(BitCastInst & CI)1648 Instruction *InstCombiner::visitBitCast(BitCastInst &CI) {
1649 // If the operands are integer typed then apply the integer transforms,
1650 // otherwise just apply the common ones.
1651 Value *Src = CI.getOperand(0);
1652 Type *SrcTy = Src->getType();
1653 Type *DestTy = CI.getType();
1654
1655 // Get rid of casts from one type to the same type. These are useless and can
1656 // be replaced by the operand.
1657 if (DestTy == Src->getType())
1658 return ReplaceInstUsesWith(CI, Src);
1659
1660 if (PointerType *DstPTy = dyn_cast<PointerType>(DestTy)) {
1661 PointerType *SrcPTy = cast<PointerType>(SrcTy);
1662 Type *DstElTy = DstPTy->getElementType();
1663 Type *SrcElTy = SrcPTy->getElementType();
1664
1665 // If the address spaces don't match, don't eliminate the bitcast, which is
1666 // required for changing types.
1667 if (SrcPTy->getAddressSpace() != DstPTy->getAddressSpace())
1668 return 0;
1669
1670 // If we are casting a alloca to a pointer to a type of the same
1671 // size, rewrite the allocation instruction to allocate the "right" type.
1672 // There is no need to modify malloc calls because it is their bitcast that
1673 // needs to be cleaned up.
1674 if (AllocaInst *AI = dyn_cast<AllocaInst>(Src))
1675 if (Instruction *V = PromoteCastOfAllocation(CI, *AI))
1676 return V;
1677
1678 // If the source and destination are pointers, and this cast is equivalent
1679 // to a getelementptr X, 0, 0, 0... turn it into the appropriate gep.
1680 // This can enhance SROA and other transforms that want type-safe pointers.
1681 Constant *ZeroUInt =
1682 Constant::getNullValue(Type::getInt32Ty(CI.getContext()));
1683 unsigned NumZeros = 0;
1684 while (SrcElTy != DstElTy &&
1685 isa<CompositeType>(SrcElTy) && !SrcElTy->isPointerTy() &&
1686 SrcElTy->getNumContainedTypes() /* not "{}" */) {
1687 SrcElTy = cast<CompositeType>(SrcElTy)->getTypeAtIndex(ZeroUInt);
1688 ++NumZeros;
1689 }
1690
1691 // If we found a path from the src to dest, create the getelementptr now.
1692 if (SrcElTy == DstElTy) {
1693 SmallVector<Value*, 8> Idxs(NumZeros+1, ZeroUInt);
1694 return GetElementPtrInst::CreateInBounds(Src, Idxs);
1695 }
1696 }
1697
1698 // Try to optimize int -> float bitcasts.
1699 if ((DestTy->isFloatTy() || DestTy->isDoubleTy()) && isa<IntegerType>(SrcTy))
1700 if (Instruction *I = OptimizeIntToFloatBitCast(CI, *this))
1701 return I;
1702
1703 if (VectorType *DestVTy = dyn_cast<VectorType>(DestTy)) {
1704 if (DestVTy->getNumElements() == 1 && !SrcTy->isVectorTy()) {
1705 Value *Elem = Builder->CreateBitCast(Src, DestVTy->getElementType());
1706 return InsertElementInst::Create(UndefValue::get(DestTy), Elem,
1707 Constant::getNullValue(Type::getInt32Ty(CI.getContext())));
1708 // FIXME: Canonicalize bitcast(insertelement) -> insertelement(bitcast)
1709 }
1710
1711 if (isa<IntegerType>(SrcTy)) {
1712 // If this is a cast from an integer to vector, check to see if the input
1713 // is a trunc or zext of a bitcast from vector. If so, we can replace all
1714 // the casts with a shuffle and (potentially) a bitcast.
1715 if (isa<TruncInst>(Src) || isa<ZExtInst>(Src)) {
1716 CastInst *SrcCast = cast<CastInst>(Src);
1717 if (BitCastInst *BCIn = dyn_cast<BitCastInst>(SrcCast->getOperand(0)))
1718 if (isa<VectorType>(BCIn->getOperand(0)->getType()))
1719 if (Instruction *I = OptimizeVectorResize(BCIn->getOperand(0),
1720 cast<VectorType>(DestTy), *this))
1721 return I;
1722 }
1723
1724 // If the input is an 'or' instruction, we may be doing shifts and ors to
1725 // assemble the elements of the vector manually. Try to rip the code out
1726 // and replace it with insertelements.
1727 if (Value *V = OptimizeIntegerToVectorInsertions(CI, *this))
1728 return ReplaceInstUsesWith(CI, V);
1729 }
1730 }
1731
1732 if (VectorType *SrcVTy = dyn_cast<VectorType>(SrcTy)) {
1733 if (SrcVTy->getNumElements() == 1 && !DestTy->isVectorTy()) {
1734 Value *Elem =
1735 Builder->CreateExtractElement(Src,
1736 Constant::getNullValue(Type::getInt32Ty(CI.getContext())));
1737 return CastInst::Create(Instruction::BitCast, Elem, DestTy);
1738 }
1739 }
1740
1741 if (ShuffleVectorInst *SVI = dyn_cast<ShuffleVectorInst>(Src)) {
1742 // Okay, we have (bitcast (shuffle ..)). Check to see if this is
1743 // a bitcast to a vector with the same # elts.
1744 if (SVI->hasOneUse() && DestTy->isVectorTy() &&
1745 cast<VectorType>(DestTy)->getNumElements() ==
1746 SVI->getType()->getNumElements() &&
1747 SVI->getType()->getNumElements() ==
1748 cast<VectorType>(SVI->getOperand(0)->getType())->getNumElements()) {
1749 BitCastInst *Tmp;
1750 // If either of the operands is a cast from CI.getType(), then
1751 // evaluating the shuffle in the casted destination's type will allow
1752 // us to eliminate at least one cast.
1753 if (((Tmp = dyn_cast<BitCastInst>(SVI->getOperand(0))) &&
1754 Tmp->getOperand(0)->getType() == DestTy) ||
1755 ((Tmp = dyn_cast<BitCastInst>(SVI->getOperand(1))) &&
1756 Tmp->getOperand(0)->getType() == DestTy)) {
1757 Value *LHS = Builder->CreateBitCast(SVI->getOperand(0), DestTy);
1758 Value *RHS = Builder->CreateBitCast(SVI->getOperand(1), DestTy);
1759 // Return a new shuffle vector. Use the same element ID's, as we
1760 // know the vector types match #elts.
1761 return new ShuffleVectorInst(LHS, RHS, SVI->getOperand(2));
1762 }
1763 }
1764 }
1765
1766 if (SrcTy->isPointerTy())
1767 return commonPointerCastTransforms(CI);
1768 return commonCastTransforms(CI);
1769 }
1770