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