1 //===- InstCombineCasts.cpp -----------------------------------------------===// 2 // 3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions. 4 // See https://llvm.org/LICENSE.txt for license information. 5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception 6 // 7 //===----------------------------------------------------------------------===// 8 // 9 // This file implements the visit functions for cast operations. 10 // 11 //===----------------------------------------------------------------------===// 12 13 #include "InstCombineInternal.h" 14 #include "llvm/ADT/SetVector.h" 15 #include "llvm/Analysis/ConstantFolding.h" 16 #include "llvm/Analysis/TargetLibraryInfo.h" 17 #include "llvm/IR/DataLayout.h" 18 #include "llvm/IR/DIBuilder.h" 19 #include "llvm/IR/PatternMatch.h" 20 #include "llvm/Support/KnownBits.h" 21 #include <numeric> 22 using namespace llvm; 23 using namespace PatternMatch; 24 25 #define DEBUG_TYPE "instcombine" 26 27 /// Analyze 'Val', seeing if it is a simple linear expression. 28 /// If so, decompose it, returning some value X, such that Val is 29 /// X*Scale+Offset. 30 /// 31 static Value *decomposeSimpleLinearExpr(Value *Val, unsigned &Scale, 32 uint64_t &Offset) { 33 if (ConstantInt *CI = dyn_cast<ConstantInt>(Val)) { 34 Offset = CI->getZExtValue(); 35 Scale = 0; 36 return ConstantInt::get(Val->getType(), 0); 37 } 38 39 if (BinaryOperator *I = dyn_cast<BinaryOperator>(Val)) { 40 // Cannot look past anything that might overflow. 41 OverflowingBinaryOperator *OBI = dyn_cast<OverflowingBinaryOperator>(Val); 42 if (OBI && !OBI->hasNoUnsignedWrap() && !OBI->hasNoSignedWrap()) { 43 Scale = 1; 44 Offset = 0; 45 return Val; 46 } 47 48 if (ConstantInt *RHS = dyn_cast<ConstantInt>(I->getOperand(1))) { 49 if (I->getOpcode() == Instruction::Shl) { 50 // This is a value scaled by '1 << the shift amt'. 51 Scale = UINT64_C(1) << RHS->getZExtValue(); 52 Offset = 0; 53 return I->getOperand(0); 54 } 55 56 if (I->getOpcode() == Instruction::Mul) { 57 // This value is scaled by 'RHS'. 58 Scale = RHS->getZExtValue(); 59 Offset = 0; 60 return I->getOperand(0); 61 } 62 63 if (I->getOpcode() == Instruction::Add) { 64 // We have X+C. Check to see if we really have (X*C2)+C1, 65 // where C1 is divisible by C2. 66 unsigned SubScale; 67 Value *SubVal = 68 decomposeSimpleLinearExpr(I->getOperand(0), SubScale, Offset); 69 Offset += RHS->getZExtValue(); 70 Scale = SubScale; 71 return SubVal; 72 } 73 } 74 } 75 76 // Otherwise, we can't look past this. 77 Scale = 1; 78 Offset = 0; 79 return Val; 80 } 81 82 /// If we find a cast of an allocation instruction, try to eliminate the cast by 83 /// moving the type information into the alloc. 84 Instruction *InstCombiner::PromoteCastOfAllocation(BitCastInst &CI, 85 AllocaInst &AI) { 86 PointerType *PTy = cast<PointerType>(CI.getType()); 87 88 IRBuilderBase::InsertPointGuard Guard(Builder); 89 Builder.SetInsertPoint(&AI); 90 91 // Get the type really allocated and the type casted to. 92 Type *AllocElTy = AI.getAllocatedType(); 93 Type *CastElTy = PTy->getElementType(); 94 if (!AllocElTy->isSized() || !CastElTy->isSized()) return nullptr; 95 96 Align AllocElTyAlign = DL.getABITypeAlign(AllocElTy); 97 Align CastElTyAlign = DL.getABITypeAlign(CastElTy); 98 if (CastElTyAlign < AllocElTyAlign) return nullptr; 99 100 // If the allocation has multiple uses, only promote it if we are strictly 101 // increasing the alignment of the resultant allocation. If we keep it the 102 // same, we open the door to infinite loops of various kinds. 103 if (!AI.hasOneUse() && CastElTyAlign == AllocElTyAlign) return nullptr; 104 105 uint64_t AllocElTySize = DL.getTypeAllocSize(AllocElTy); 106 uint64_t CastElTySize = DL.getTypeAllocSize(CastElTy); 107 if (CastElTySize == 0 || AllocElTySize == 0) return nullptr; 108 109 // If the allocation has multiple uses, only promote it if we're not 110 // shrinking the amount of memory being allocated. 111 uint64_t AllocElTyStoreSize = DL.getTypeStoreSize(AllocElTy); 112 uint64_t CastElTyStoreSize = DL.getTypeStoreSize(CastElTy); 113 if (!AI.hasOneUse() && CastElTyStoreSize < AllocElTyStoreSize) return nullptr; 114 115 // See if we can satisfy the modulus by pulling a scale out of the array 116 // size argument. 117 unsigned ArraySizeScale; 118 uint64_t ArrayOffset; 119 Value *NumElements = // See if the array size is a decomposable linear expr. 120 decomposeSimpleLinearExpr(AI.getOperand(0), ArraySizeScale, ArrayOffset); 121 122 // If we can now satisfy the modulus, by using a non-1 scale, we really can 123 // do the xform. 124 if ((AllocElTySize*ArraySizeScale) % CastElTySize != 0 || 125 (AllocElTySize*ArrayOffset ) % CastElTySize != 0) return nullptr; 126 127 unsigned Scale = (AllocElTySize*ArraySizeScale)/CastElTySize; 128 Value *Amt = nullptr; 129 if (Scale == 1) { 130 Amt = NumElements; 131 } else { 132 Amt = ConstantInt::get(AI.getArraySize()->getType(), Scale); 133 // Insert before the alloca, not before the cast. 134 Amt = Builder.CreateMul(Amt, NumElements); 135 } 136 137 if (uint64_t Offset = (AllocElTySize*ArrayOffset)/CastElTySize) { 138 Value *Off = ConstantInt::get(AI.getArraySize()->getType(), 139 Offset, true); 140 Amt = Builder.CreateAdd(Amt, Off); 141 } 142 143 AllocaInst *New = Builder.CreateAlloca(CastElTy, Amt); 144 New->setAlignment(AI.getAlign()); 145 New->takeName(&AI); 146 New->setUsedWithInAlloca(AI.isUsedWithInAlloca()); 147 148 // If the allocation has multiple real uses, insert a cast and change all 149 // things that used it to use the new cast. This will also hack on CI, but it 150 // will die soon. 151 if (!AI.hasOneUse()) { 152 // New is the allocation instruction, pointer typed. AI is the original 153 // allocation instruction, also pointer typed. Thus, cast to use is BitCast. 154 Value *NewCast = Builder.CreateBitCast(New, AI.getType(), "tmpcast"); 155 replaceInstUsesWith(AI, NewCast); 156 eraseInstFromFunction(AI); 157 } 158 return replaceInstUsesWith(CI, New); 159 } 160 161 /// Given an expression that CanEvaluateTruncated or CanEvaluateSExtd returns 162 /// true for, actually insert the code to evaluate the expression. 163 Value *InstCombiner::EvaluateInDifferentType(Value *V, Type *Ty, 164 bool isSigned) { 165 if (Constant *C = dyn_cast<Constant>(V)) { 166 C = ConstantExpr::getIntegerCast(C, Ty, isSigned /*Sext or ZExt*/); 167 // If we got a constantexpr back, try to simplify it with DL info. 168 return ConstantFoldConstant(C, DL, &TLI); 169 } 170 171 // Otherwise, it must be an instruction. 172 Instruction *I = cast<Instruction>(V); 173 Instruction *Res = nullptr; 174 unsigned Opc = I->getOpcode(); 175 switch (Opc) { 176 case Instruction::Add: 177 case Instruction::Sub: 178 case Instruction::Mul: 179 case Instruction::And: 180 case Instruction::Or: 181 case Instruction::Xor: 182 case Instruction::AShr: 183 case Instruction::LShr: 184 case Instruction::Shl: 185 case Instruction::UDiv: 186 case Instruction::URem: { 187 Value *LHS = EvaluateInDifferentType(I->getOperand(0), Ty, isSigned); 188 Value *RHS = EvaluateInDifferentType(I->getOperand(1), Ty, isSigned); 189 Res = BinaryOperator::Create((Instruction::BinaryOps)Opc, LHS, RHS); 190 break; 191 } 192 case Instruction::Trunc: 193 case Instruction::ZExt: 194 case Instruction::SExt: 195 // If the source type of the cast is the type we're trying for then we can 196 // just return the source. There's no need to insert it because it is not 197 // new. 198 if (I->getOperand(0)->getType() == Ty) 199 return I->getOperand(0); 200 201 // Otherwise, must be the same type of cast, so just reinsert a new one. 202 // This also handles the case of zext(trunc(x)) -> zext(x). 203 Res = CastInst::CreateIntegerCast(I->getOperand(0), Ty, 204 Opc == Instruction::SExt); 205 break; 206 case Instruction::Select: { 207 Value *True = EvaluateInDifferentType(I->getOperand(1), Ty, isSigned); 208 Value *False = EvaluateInDifferentType(I->getOperand(2), Ty, isSigned); 209 Res = SelectInst::Create(I->getOperand(0), True, False); 210 break; 211 } 212 case Instruction::PHI: { 213 PHINode *OPN = cast<PHINode>(I); 214 PHINode *NPN = PHINode::Create(Ty, OPN->getNumIncomingValues()); 215 for (unsigned i = 0, e = OPN->getNumIncomingValues(); i != e; ++i) { 216 Value *V = 217 EvaluateInDifferentType(OPN->getIncomingValue(i), Ty, isSigned); 218 NPN->addIncoming(V, OPN->getIncomingBlock(i)); 219 } 220 Res = NPN; 221 break; 222 } 223 default: 224 // TODO: Can handle more cases here. 225 llvm_unreachable("Unreachable!"); 226 } 227 228 Res->takeName(I); 229 return InsertNewInstWith(Res, *I); 230 } 231 232 Instruction::CastOps InstCombiner::isEliminableCastPair(const CastInst *CI1, 233 const CastInst *CI2) { 234 Type *SrcTy = CI1->getSrcTy(); 235 Type *MidTy = CI1->getDestTy(); 236 Type *DstTy = CI2->getDestTy(); 237 238 Instruction::CastOps firstOp = CI1->getOpcode(); 239 Instruction::CastOps secondOp = CI2->getOpcode(); 240 Type *SrcIntPtrTy = 241 SrcTy->isPtrOrPtrVectorTy() ? DL.getIntPtrType(SrcTy) : nullptr; 242 Type *MidIntPtrTy = 243 MidTy->isPtrOrPtrVectorTy() ? DL.getIntPtrType(MidTy) : nullptr; 244 Type *DstIntPtrTy = 245 DstTy->isPtrOrPtrVectorTy() ? DL.getIntPtrType(DstTy) : nullptr; 246 unsigned Res = CastInst::isEliminableCastPair(firstOp, secondOp, SrcTy, MidTy, 247 DstTy, SrcIntPtrTy, MidIntPtrTy, 248 DstIntPtrTy); 249 250 // We don't want to form an inttoptr or ptrtoint that converts to an integer 251 // type that differs from the pointer size. 252 if ((Res == Instruction::IntToPtr && SrcTy != DstIntPtrTy) || 253 (Res == Instruction::PtrToInt && DstTy != SrcIntPtrTy)) 254 Res = 0; 255 256 return Instruction::CastOps(Res); 257 } 258 259 /// Implement the transforms common to all CastInst visitors. 260 Instruction *InstCombiner::commonCastTransforms(CastInst &CI) { 261 Value *Src = CI.getOperand(0); 262 263 // Try to eliminate a cast of a cast. 264 if (auto *CSrc = dyn_cast<CastInst>(Src)) { // A->B->C cast 265 if (Instruction::CastOps NewOpc = isEliminableCastPair(CSrc, &CI)) { 266 // The first cast (CSrc) is eliminable so we need to fix up or replace 267 // the second cast (CI). CSrc will then have a good chance of being dead. 268 auto *Ty = CI.getType(); 269 auto *Res = CastInst::Create(NewOpc, CSrc->getOperand(0), Ty); 270 // Point debug users of the dying cast to the new one. 271 if (CSrc->hasOneUse()) 272 replaceAllDbgUsesWith(*CSrc, *Res, CI, DT); 273 return Res; 274 } 275 } 276 277 if (auto *Sel = dyn_cast<SelectInst>(Src)) { 278 // We are casting a select. Try to fold the cast into the select if the 279 // select does not have a compare instruction with matching operand types 280 // or the select is likely better done in a narrow type. 281 // Creating a select with operands that are different sizes than its 282 // condition may inhibit other folds and lead to worse codegen. 283 auto *Cmp = dyn_cast<CmpInst>(Sel->getCondition()); 284 if (!Cmp || Cmp->getOperand(0)->getType() != Sel->getType() || 285 (CI.getOpcode() == Instruction::Trunc && 286 shouldChangeType(CI.getSrcTy(), CI.getType()))) { 287 if (Instruction *NV = FoldOpIntoSelect(CI, Sel)) { 288 replaceAllDbgUsesWith(*Sel, *NV, CI, DT); 289 return NV; 290 } 291 } 292 } 293 294 // If we are casting a PHI, then fold the cast into the PHI. 295 if (auto *PN = dyn_cast<PHINode>(Src)) { 296 // Don't do this if it would create a PHI node with an illegal type from a 297 // legal type. 298 if (!Src->getType()->isIntegerTy() || !CI.getType()->isIntegerTy() || 299 shouldChangeType(CI.getSrcTy(), CI.getType())) 300 if (Instruction *NV = foldOpIntoPhi(CI, PN)) 301 return NV; 302 } 303 304 return nullptr; 305 } 306 307 /// Constants and extensions/truncates from the destination type are always 308 /// free to be evaluated in that type. This is a helper for canEvaluate*. 309 static bool canAlwaysEvaluateInType(Value *V, Type *Ty) { 310 if (isa<Constant>(V)) 311 return true; 312 Value *X; 313 if ((match(V, m_ZExtOrSExt(m_Value(X))) || match(V, m_Trunc(m_Value(X)))) && 314 X->getType() == Ty) 315 return true; 316 317 return false; 318 } 319 320 /// Filter out values that we can not evaluate in the destination type for free. 321 /// This is a helper for canEvaluate*. 322 static bool canNotEvaluateInType(Value *V, Type *Ty) { 323 assert(!isa<Constant>(V) && "Constant should already be handled."); 324 if (!isa<Instruction>(V)) 325 return true; 326 // We don't extend or shrink something that has multiple uses -- doing so 327 // would require duplicating the instruction which isn't profitable. 328 if (!V->hasOneUse()) 329 return true; 330 331 return false; 332 } 333 334 /// Return true if we can evaluate the specified expression tree as type Ty 335 /// instead of its larger type, and arrive with the same value. 336 /// This is used by code that tries to eliminate truncates. 337 /// 338 /// Ty will always be a type smaller than V. We should return true if trunc(V) 339 /// can be computed by computing V in the smaller type. If V is an instruction, 340 /// then trunc(inst(x,y)) can be computed as inst(trunc(x),trunc(y)), which only 341 /// makes sense if x and y can be efficiently truncated. 342 /// 343 /// This function works on both vectors and scalars. 344 /// 345 static bool canEvaluateTruncated(Value *V, Type *Ty, InstCombiner &IC, 346 Instruction *CxtI) { 347 if (canAlwaysEvaluateInType(V, Ty)) 348 return true; 349 if (canNotEvaluateInType(V, Ty)) 350 return false; 351 352 auto *I = cast<Instruction>(V); 353 Type *OrigTy = V->getType(); 354 switch (I->getOpcode()) { 355 case Instruction::Add: 356 case Instruction::Sub: 357 case Instruction::Mul: 358 case Instruction::And: 359 case Instruction::Or: 360 case Instruction::Xor: 361 // These operators can all arbitrarily be extended or truncated. 362 return canEvaluateTruncated(I->getOperand(0), Ty, IC, CxtI) && 363 canEvaluateTruncated(I->getOperand(1), Ty, IC, CxtI); 364 365 case Instruction::UDiv: 366 case Instruction::URem: { 367 // UDiv and URem can be truncated if all the truncated bits are zero. 368 uint32_t OrigBitWidth = OrigTy->getScalarSizeInBits(); 369 uint32_t BitWidth = Ty->getScalarSizeInBits(); 370 assert(BitWidth < OrigBitWidth && "Unexpected bitwidths!"); 371 APInt Mask = APInt::getBitsSetFrom(OrigBitWidth, BitWidth); 372 if (IC.MaskedValueIsZero(I->getOperand(0), Mask, 0, CxtI) && 373 IC.MaskedValueIsZero(I->getOperand(1), Mask, 0, CxtI)) { 374 return canEvaluateTruncated(I->getOperand(0), Ty, IC, CxtI) && 375 canEvaluateTruncated(I->getOperand(1), Ty, IC, CxtI); 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 an 381 // inrange amount, we can always perform a SHL in a smaller type. 382 uint32_t BitWidth = Ty->getScalarSizeInBits(); 383 KnownBits AmtKnownBits = 384 llvm::computeKnownBits(I->getOperand(1), IC.getDataLayout()); 385 if (AmtKnownBits.getMaxValue().ult(BitWidth)) 386 return canEvaluateTruncated(I->getOperand(0), Ty, IC, CxtI) && 387 canEvaluateTruncated(I->getOperand(1), Ty, IC, CxtI); 388 break; 389 } 390 case Instruction::LShr: { 391 // If this is a truncate of a logical shr, we can truncate it to a smaller 392 // lshr iff we know that the bits we would otherwise be shifting in are 393 // already zeros. 394 // TODO: It is enough to check that the bits we would be shifting in are 395 // zero - use AmtKnownBits.getMaxValue(). 396 uint32_t OrigBitWidth = OrigTy->getScalarSizeInBits(); 397 uint32_t BitWidth = Ty->getScalarSizeInBits(); 398 KnownBits AmtKnownBits = 399 llvm::computeKnownBits(I->getOperand(1), IC.getDataLayout()); 400 APInt ShiftedBits = APInt::getBitsSetFrom(OrigBitWidth, BitWidth); 401 if (AmtKnownBits.getMaxValue().ult(BitWidth) && 402 IC.MaskedValueIsZero(I->getOperand(0), ShiftedBits, 0, CxtI)) { 403 return canEvaluateTruncated(I->getOperand(0), Ty, IC, CxtI) && 404 canEvaluateTruncated(I->getOperand(1), Ty, IC, CxtI); 405 } 406 break; 407 } 408 case Instruction::AShr: { 409 // If this is a truncate of an arithmetic shr, we can truncate it to a 410 // smaller ashr iff we know that all the bits from the sign bit of the 411 // original type and the sign bit of the truncate type are similar. 412 // TODO: It is enough to check that the bits we would be shifting in are 413 // similar to sign bit of the truncate type. 414 uint32_t OrigBitWidth = OrigTy->getScalarSizeInBits(); 415 uint32_t BitWidth = Ty->getScalarSizeInBits(); 416 KnownBits AmtKnownBits = 417 llvm::computeKnownBits(I->getOperand(1), IC.getDataLayout()); 418 unsigned ShiftedBits = OrigBitWidth - BitWidth; 419 if (AmtKnownBits.getMaxValue().ult(BitWidth) && 420 ShiftedBits < IC.ComputeNumSignBits(I->getOperand(0), 0, CxtI)) 421 return canEvaluateTruncated(I->getOperand(0), Ty, IC, CxtI) && 422 canEvaluateTruncated(I->getOperand(1), Ty, IC, CxtI); 423 break; 424 } 425 case Instruction::Trunc: 426 // trunc(trunc(x)) -> trunc(x) 427 return true; 428 case Instruction::ZExt: 429 case Instruction::SExt: 430 // trunc(ext(x)) -> ext(x) if the source type is smaller than the new dest 431 // trunc(ext(x)) -> trunc(x) if the source type is larger than the new dest 432 return true; 433 case Instruction::Select: { 434 SelectInst *SI = cast<SelectInst>(I); 435 return canEvaluateTruncated(SI->getTrueValue(), Ty, IC, CxtI) && 436 canEvaluateTruncated(SI->getFalseValue(), Ty, IC, CxtI); 437 } 438 case Instruction::PHI: { 439 // We can change a phi if we can change all operands. Note that we never 440 // get into trouble with cyclic PHIs here because we only consider 441 // instructions with a single use. 442 PHINode *PN = cast<PHINode>(I); 443 for (Value *IncValue : PN->incoming_values()) 444 if (!canEvaluateTruncated(IncValue, Ty, IC, CxtI)) 445 return false; 446 return true; 447 } 448 default: 449 // TODO: Can handle more cases here. 450 break; 451 } 452 453 return false; 454 } 455 456 /// Given a vector that is bitcast to an integer, optionally logically 457 /// right-shifted, and truncated, convert it to an extractelement. 458 /// Example (big endian): 459 /// trunc (lshr (bitcast <4 x i32> %X to i128), 32) to i32 460 /// ---> 461 /// extractelement <4 x i32> %X, 1 462 static Instruction *foldVecTruncToExtElt(TruncInst &Trunc, InstCombiner &IC) { 463 Value *TruncOp = Trunc.getOperand(0); 464 Type *DestType = Trunc.getType(); 465 if (!TruncOp->hasOneUse() || !isa<IntegerType>(DestType)) 466 return nullptr; 467 468 Value *VecInput = nullptr; 469 ConstantInt *ShiftVal = nullptr; 470 if (!match(TruncOp, m_CombineOr(m_BitCast(m_Value(VecInput)), 471 m_LShr(m_BitCast(m_Value(VecInput)), 472 m_ConstantInt(ShiftVal)))) || 473 !isa<VectorType>(VecInput->getType())) 474 return nullptr; 475 476 VectorType *VecType = cast<VectorType>(VecInput->getType()); 477 unsigned VecWidth = VecType->getPrimitiveSizeInBits(); 478 unsigned DestWidth = DestType->getPrimitiveSizeInBits(); 479 unsigned ShiftAmount = ShiftVal ? ShiftVal->getZExtValue() : 0; 480 481 if ((VecWidth % DestWidth != 0) || (ShiftAmount % DestWidth != 0)) 482 return nullptr; 483 484 // If the element type of the vector doesn't match the result type, 485 // bitcast it to a vector type that we can extract from. 486 unsigned NumVecElts = VecWidth / DestWidth; 487 if (VecType->getElementType() != DestType) { 488 VecType = FixedVectorType::get(DestType, NumVecElts); 489 VecInput = IC.Builder.CreateBitCast(VecInput, VecType, "bc"); 490 } 491 492 unsigned Elt = ShiftAmount / DestWidth; 493 if (IC.getDataLayout().isBigEndian()) 494 Elt = NumVecElts - 1 - Elt; 495 496 return ExtractElementInst::Create(VecInput, IC.Builder.getInt32(Elt)); 497 } 498 499 /// Rotate left/right may occur in a wider type than necessary because of type 500 /// promotion rules. Try to narrow the inputs and convert to funnel shift. 501 Instruction *InstCombiner::narrowRotate(TruncInst &Trunc) { 502 assert((isa<VectorType>(Trunc.getSrcTy()) || 503 shouldChangeType(Trunc.getSrcTy(), Trunc.getType())) && 504 "Don't narrow to an illegal scalar type"); 505 506 // Bail out on strange types. It is possible to handle some of these patterns 507 // even with non-power-of-2 sizes, but it is not a likely scenario. 508 Type *DestTy = Trunc.getType(); 509 unsigned NarrowWidth = DestTy->getScalarSizeInBits(); 510 if (!isPowerOf2_32(NarrowWidth)) 511 return nullptr; 512 513 // First, find an or'd pair of opposite shifts with the same shifted operand: 514 // trunc (or (lshr ShVal, ShAmt0), (shl ShVal, ShAmt1)) 515 Value *Or0, *Or1; 516 if (!match(Trunc.getOperand(0), m_OneUse(m_Or(m_Value(Or0), m_Value(Or1))))) 517 return nullptr; 518 519 Value *ShVal, *ShAmt0, *ShAmt1; 520 if (!match(Or0, m_OneUse(m_LogicalShift(m_Value(ShVal), m_Value(ShAmt0)))) || 521 !match(Or1, m_OneUse(m_LogicalShift(m_Specific(ShVal), m_Value(ShAmt1))))) 522 return nullptr; 523 524 auto ShiftOpcode0 = cast<BinaryOperator>(Or0)->getOpcode(); 525 auto ShiftOpcode1 = cast<BinaryOperator>(Or1)->getOpcode(); 526 if (ShiftOpcode0 == ShiftOpcode1) 527 return nullptr; 528 529 // Match the shift amount operands for a rotate pattern. This always matches 530 // a subtraction on the R operand. 531 auto matchShiftAmount = [](Value *L, Value *R, unsigned Width) -> Value * { 532 // The shift amounts may add up to the narrow bit width: 533 // (shl ShVal, L) | (lshr ShVal, Width - L) 534 if (match(R, m_OneUse(m_Sub(m_SpecificInt(Width), m_Specific(L))))) 535 return L; 536 537 // The shift amount may be masked with negation: 538 // (shl ShVal, (X & (Width - 1))) | (lshr ShVal, ((-X) & (Width - 1))) 539 Value *X; 540 unsigned Mask = Width - 1; 541 if (match(L, m_And(m_Value(X), m_SpecificInt(Mask))) && 542 match(R, m_And(m_Neg(m_Specific(X)), m_SpecificInt(Mask)))) 543 return X; 544 545 // Same as above, but the shift amount may be extended after masking: 546 if (match(L, m_ZExt(m_And(m_Value(X), m_SpecificInt(Mask)))) && 547 match(R, m_ZExt(m_And(m_Neg(m_Specific(X)), m_SpecificInt(Mask))))) 548 return X; 549 550 return nullptr; 551 }; 552 553 Value *ShAmt = matchShiftAmount(ShAmt0, ShAmt1, NarrowWidth); 554 bool SubIsOnLHS = false; 555 if (!ShAmt) { 556 ShAmt = matchShiftAmount(ShAmt1, ShAmt0, NarrowWidth); 557 SubIsOnLHS = true; 558 } 559 if (!ShAmt) 560 return nullptr; 561 562 // The shifted value must have high zeros in the wide type. Typically, this 563 // will be a zext, but it could also be the result of an 'and' or 'shift'. 564 unsigned WideWidth = Trunc.getSrcTy()->getScalarSizeInBits(); 565 APInt HiBitMask = APInt::getHighBitsSet(WideWidth, WideWidth - NarrowWidth); 566 if (!MaskedValueIsZero(ShVal, HiBitMask, 0, &Trunc)) 567 return nullptr; 568 569 // We have an unnecessarily wide rotate! 570 // trunc (or (lshr ShVal, ShAmt), (shl ShVal, BitWidth - ShAmt)) 571 // Narrow the inputs and convert to funnel shift intrinsic: 572 // llvm.fshl.i8(trunc(ShVal), trunc(ShVal), trunc(ShAmt)) 573 Value *NarrowShAmt = Builder.CreateTrunc(ShAmt, DestTy); 574 Value *X = Builder.CreateTrunc(ShVal, DestTy); 575 bool IsFshl = (!SubIsOnLHS && ShiftOpcode0 == BinaryOperator::Shl) || 576 (SubIsOnLHS && ShiftOpcode1 == BinaryOperator::Shl); 577 Intrinsic::ID IID = IsFshl ? Intrinsic::fshl : Intrinsic::fshr; 578 Function *F = Intrinsic::getDeclaration(Trunc.getModule(), IID, DestTy); 579 return IntrinsicInst::Create(F, { X, X, NarrowShAmt }); 580 } 581 582 /// Try to narrow the width of math or bitwise logic instructions by pulling a 583 /// truncate ahead of binary operators. 584 /// TODO: Transforms for truncated shifts should be moved into here. 585 Instruction *InstCombiner::narrowBinOp(TruncInst &Trunc) { 586 Type *SrcTy = Trunc.getSrcTy(); 587 Type *DestTy = Trunc.getType(); 588 if (!isa<VectorType>(SrcTy) && !shouldChangeType(SrcTy, DestTy)) 589 return nullptr; 590 591 BinaryOperator *BinOp; 592 if (!match(Trunc.getOperand(0), m_OneUse(m_BinOp(BinOp)))) 593 return nullptr; 594 595 Value *BinOp0 = BinOp->getOperand(0); 596 Value *BinOp1 = BinOp->getOperand(1); 597 switch (BinOp->getOpcode()) { 598 case Instruction::And: 599 case Instruction::Or: 600 case Instruction::Xor: 601 case Instruction::Add: 602 case Instruction::Sub: 603 case Instruction::Mul: { 604 Constant *C; 605 if (match(BinOp0, m_Constant(C))) { 606 // trunc (binop C, X) --> binop (trunc C', X) 607 Constant *NarrowC = ConstantExpr::getTrunc(C, DestTy); 608 Value *TruncX = Builder.CreateTrunc(BinOp1, DestTy); 609 return BinaryOperator::Create(BinOp->getOpcode(), NarrowC, TruncX); 610 } 611 if (match(BinOp1, m_Constant(C))) { 612 // trunc (binop X, C) --> binop (trunc X, C') 613 Constant *NarrowC = ConstantExpr::getTrunc(C, DestTy); 614 Value *TruncX = Builder.CreateTrunc(BinOp0, DestTy); 615 return BinaryOperator::Create(BinOp->getOpcode(), TruncX, NarrowC); 616 } 617 Value *X; 618 if (match(BinOp0, m_ZExtOrSExt(m_Value(X))) && X->getType() == DestTy) { 619 // trunc (binop (ext X), Y) --> binop X, (trunc Y) 620 Value *NarrowOp1 = Builder.CreateTrunc(BinOp1, DestTy); 621 return BinaryOperator::Create(BinOp->getOpcode(), X, NarrowOp1); 622 } 623 if (match(BinOp1, m_ZExtOrSExt(m_Value(X))) && X->getType() == DestTy) { 624 // trunc (binop Y, (ext X)) --> binop (trunc Y), X 625 Value *NarrowOp0 = Builder.CreateTrunc(BinOp0, DestTy); 626 return BinaryOperator::Create(BinOp->getOpcode(), NarrowOp0, X); 627 } 628 break; 629 } 630 631 default: break; 632 } 633 634 if (Instruction *NarrowOr = narrowRotate(Trunc)) 635 return NarrowOr; 636 637 return nullptr; 638 } 639 640 /// Try to narrow the width of a splat shuffle. This could be generalized to any 641 /// shuffle with a constant operand, but we limit the transform to avoid 642 /// creating a shuffle type that targets may not be able to lower effectively. 643 static Instruction *shrinkSplatShuffle(TruncInst &Trunc, 644 InstCombiner::BuilderTy &Builder) { 645 auto *Shuf = dyn_cast<ShuffleVectorInst>(Trunc.getOperand(0)); 646 if (Shuf && Shuf->hasOneUse() && isa<UndefValue>(Shuf->getOperand(1)) && 647 is_splat(Shuf->getShuffleMask()) && 648 Shuf->getType() == Shuf->getOperand(0)->getType()) { 649 // trunc (shuf X, Undef, SplatMask) --> shuf (trunc X), Undef, SplatMask 650 Constant *NarrowUndef = UndefValue::get(Trunc.getType()); 651 Value *NarrowOp = Builder.CreateTrunc(Shuf->getOperand(0), Trunc.getType()); 652 return new ShuffleVectorInst(NarrowOp, NarrowUndef, Shuf->getShuffleMask()); 653 } 654 655 return nullptr; 656 } 657 658 /// Try to narrow the width of an insert element. This could be generalized for 659 /// any vector constant, but we limit the transform to insertion into undef to 660 /// avoid potential backend problems from unsupported insertion widths. This 661 /// could also be extended to handle the case of inserting a scalar constant 662 /// into a vector variable. 663 static Instruction *shrinkInsertElt(CastInst &Trunc, 664 InstCombiner::BuilderTy &Builder) { 665 Instruction::CastOps Opcode = Trunc.getOpcode(); 666 assert((Opcode == Instruction::Trunc || Opcode == Instruction::FPTrunc) && 667 "Unexpected instruction for shrinking"); 668 669 auto *InsElt = dyn_cast<InsertElementInst>(Trunc.getOperand(0)); 670 if (!InsElt || !InsElt->hasOneUse()) 671 return nullptr; 672 673 Type *DestTy = Trunc.getType(); 674 Type *DestScalarTy = DestTy->getScalarType(); 675 Value *VecOp = InsElt->getOperand(0); 676 Value *ScalarOp = InsElt->getOperand(1); 677 Value *Index = InsElt->getOperand(2); 678 679 if (isa<UndefValue>(VecOp)) { 680 // trunc (inselt undef, X, Index) --> inselt undef, (trunc X), Index 681 // fptrunc (inselt undef, X, Index) --> inselt undef, (fptrunc X), Index 682 UndefValue *NarrowUndef = UndefValue::get(DestTy); 683 Value *NarrowOp = Builder.CreateCast(Opcode, ScalarOp, DestScalarTy); 684 return InsertElementInst::Create(NarrowUndef, NarrowOp, Index); 685 } 686 687 return nullptr; 688 } 689 690 Instruction *InstCombiner::visitTrunc(TruncInst &Trunc) { 691 if (Instruction *Result = commonCastTransforms(Trunc)) 692 return Result; 693 694 Value *Src = Trunc.getOperand(0); 695 Type *DestTy = Trunc.getType(), *SrcTy = Src->getType(); 696 unsigned DestWidth = DestTy->getScalarSizeInBits(); 697 unsigned SrcWidth = SrcTy->getScalarSizeInBits(); 698 ConstantInt *Cst; 699 700 // Attempt to truncate the entire input expression tree to the destination 701 // type. Only do this if the dest type is a simple type, don't convert the 702 // expression tree to something weird like i93 unless the source is also 703 // strange. 704 if ((DestTy->isVectorTy() || shouldChangeType(SrcTy, DestTy)) && 705 canEvaluateTruncated(Src, DestTy, *this, &Trunc)) { 706 707 // If this cast is a truncate, evaluting in a different type always 708 // eliminates the cast, so it is always a win. 709 LLVM_DEBUG( 710 dbgs() << "ICE: EvaluateInDifferentType converting expression type" 711 " to avoid cast: " 712 << Trunc << '\n'); 713 Value *Res = EvaluateInDifferentType(Src, DestTy, false); 714 assert(Res->getType() == DestTy); 715 return replaceInstUsesWith(Trunc, Res); 716 } 717 718 // For integer types, check if we can shorten the entire input expression to 719 // DestWidth * 2, which won't allow removing the truncate, but reducing the 720 // width may enable further optimizations, e.g. allowing for larger 721 // vectorization factors. 722 if (auto *DestITy = dyn_cast<IntegerType>(DestTy)) { 723 if (DestWidth * 2 < SrcWidth) { 724 auto *NewDestTy = DestITy->getExtendedType(); 725 if (shouldChangeType(SrcTy, NewDestTy) && 726 canEvaluateTruncated(Src, NewDestTy, *this, &Trunc)) { 727 LLVM_DEBUG( 728 dbgs() << "ICE: EvaluateInDifferentType converting expression type" 729 " to reduce the width of operand of" 730 << Trunc << '\n'); 731 Value *Res = EvaluateInDifferentType(Src, NewDestTy, false); 732 return new TruncInst(Res, DestTy); 733 } 734 } 735 } 736 737 // Test if the trunc is the user of a select which is part of a 738 // minimum or maximum operation. If so, don't do any more simplification. 739 // Even simplifying demanded bits can break the canonical form of a 740 // min/max. 741 Value *LHS, *RHS; 742 if (SelectInst *Sel = dyn_cast<SelectInst>(Src)) 743 if (matchSelectPattern(Sel, LHS, RHS).Flavor != SPF_UNKNOWN) 744 return nullptr; 745 746 // See if we can simplify any instructions used by the input whose sole 747 // purpose is to compute bits we don't care about. 748 if (SimplifyDemandedInstructionBits(Trunc)) 749 return &Trunc; 750 751 if (DestWidth == 1) { 752 Value *Zero = Constant::getNullValue(SrcTy); 753 if (DestTy->isIntegerTy()) { 754 // Canonicalize trunc x to i1 -> icmp ne (and x, 1), 0 (scalar only). 755 // TODO: We canonicalize to more instructions here because we are probably 756 // lacking equivalent analysis for trunc relative to icmp. There may also 757 // be codegen concerns. If those trunc limitations were removed, we could 758 // remove this transform. 759 Value *And = Builder.CreateAnd(Src, ConstantInt::get(SrcTy, 1)); 760 return new ICmpInst(ICmpInst::ICMP_NE, And, Zero); 761 } 762 763 // For vectors, we do not canonicalize all truncs to icmp, so optimize 764 // patterns that would be covered within visitICmpInst. 765 Value *X; 766 Constant *C; 767 if (match(Src, m_OneUse(m_LShr(m_Value(X), m_Constant(C))))) { 768 // trunc (lshr X, C) to i1 --> icmp ne (and X, C'), 0 769 Constant *One = ConstantInt::get(SrcTy, APInt(SrcWidth, 1)); 770 Constant *MaskC = ConstantExpr::getShl(One, C); 771 Value *And = Builder.CreateAnd(X, MaskC); 772 return new ICmpInst(ICmpInst::ICMP_NE, And, Zero); 773 } 774 if (match(Src, m_OneUse(m_c_Or(m_LShr(m_Value(X), m_Constant(C)), 775 m_Deferred(X))))) { 776 // trunc (or (lshr X, C), X) to i1 --> icmp ne (and X, C'), 0 777 Constant *One = ConstantInt::get(SrcTy, APInt(SrcWidth, 1)); 778 Constant *MaskC = ConstantExpr::getShl(One, C); 779 MaskC = ConstantExpr::getOr(MaskC, One); 780 Value *And = Builder.CreateAnd(X, MaskC); 781 return new ICmpInst(ICmpInst::ICMP_NE, And, Zero); 782 } 783 } 784 785 // FIXME: Maybe combine the next two transforms to handle the no cast case 786 // more efficiently. Support vector types. Cleanup code by using m_OneUse. 787 788 // Transform trunc(lshr (zext A), Cst) to eliminate one type conversion. 789 Value *A = nullptr; 790 if (Src->hasOneUse() && 791 match(Src, m_LShr(m_ZExt(m_Value(A)), m_ConstantInt(Cst)))) { 792 // We have three types to worry about here, the type of A, the source of 793 // the truncate (MidSize), and the destination of the truncate. We know that 794 // ASize < MidSize and MidSize > ResultSize, but don't know the relation 795 // between ASize and ResultSize. 796 unsigned ASize = A->getType()->getPrimitiveSizeInBits(); 797 798 // If the shift amount is larger than the size of A, then the result is 799 // known to be zero because all the input bits got shifted out. 800 if (Cst->getZExtValue() >= ASize) 801 return replaceInstUsesWith(Trunc, Constant::getNullValue(DestTy)); 802 803 // Since we're doing an lshr and a zero extend, and know that the shift 804 // amount is smaller than ASize, it is always safe to do the shift in A's 805 // type, then zero extend or truncate to the result. 806 Value *Shift = Builder.CreateLShr(A, Cst->getZExtValue()); 807 Shift->takeName(Src); 808 return CastInst::CreateIntegerCast(Shift, DestTy, false); 809 } 810 811 const APInt *C; 812 if (match(Src, m_LShr(m_SExt(m_Value(A)), m_APInt(C)))) { 813 unsigned AWidth = A->getType()->getScalarSizeInBits(); 814 unsigned MaxShiftAmt = SrcWidth - std::max(DestWidth, AWidth); 815 816 // If the shift is small enough, all zero bits created by the shift are 817 // removed by the trunc. 818 if (C->getZExtValue() <= MaxShiftAmt) { 819 // trunc (lshr (sext A), C) --> ashr A, C 820 if (A->getType() == DestTy) { 821 unsigned ShAmt = std::min((unsigned)C->getZExtValue(), DestWidth - 1); 822 return BinaryOperator::CreateAShr(A, ConstantInt::get(DestTy, ShAmt)); 823 } 824 // The types are mismatched, so create a cast after shifting: 825 // trunc (lshr (sext A), C) --> sext/trunc (ashr A, C) 826 if (Src->hasOneUse()) { 827 unsigned ShAmt = std::min((unsigned)C->getZExtValue(), AWidth - 1); 828 Value *Shift = Builder.CreateAShr(A, ShAmt); 829 return CastInst::CreateIntegerCast(Shift, DestTy, true); 830 } 831 } 832 // TODO: Mask high bits with 'and'. 833 } 834 835 if (Instruction *I = narrowBinOp(Trunc)) 836 return I; 837 838 if (Instruction *I = shrinkSplatShuffle(Trunc, Builder)) 839 return I; 840 841 if (Instruction *I = shrinkInsertElt(Trunc, Builder)) 842 return I; 843 844 if (Src->hasOneUse() && isa<IntegerType>(SrcTy) && 845 shouldChangeType(SrcTy, DestTy)) { 846 // Transform "trunc (shl X, cst)" -> "shl (trunc X), cst" so long as the 847 // dest type is native and cst < dest size. 848 if (match(Src, m_Shl(m_Value(A), m_ConstantInt(Cst))) && 849 !match(A, m_Shr(m_Value(), m_Constant()))) { 850 // Skip shifts of shift by constants. It undoes a combine in 851 // FoldShiftByConstant and is the extend in reg pattern. 852 if (Cst->getValue().ult(DestWidth)) { 853 Value *NewTrunc = Builder.CreateTrunc(A, DestTy, A->getName() + ".tr"); 854 855 return BinaryOperator::Create( 856 Instruction::Shl, NewTrunc, 857 ConstantInt::get(DestTy, Cst->getValue().trunc(DestWidth))); 858 } 859 } 860 } 861 862 if (Instruction *I = foldVecTruncToExtElt(Trunc, *this)) 863 return I; 864 865 // Whenever an element is extracted from a vector, and then truncated, 866 // canonicalize by converting it to a bitcast followed by an 867 // extractelement. 868 // 869 // Example (little endian): 870 // trunc (extractelement <4 x i64> %X, 0) to i32 871 // ---> 872 // extractelement <8 x i32> (bitcast <4 x i64> %X to <8 x i32>), i32 0 873 Value *VecOp; 874 if (match(Src, m_OneUse(m_ExtractElt(m_Value(VecOp), m_ConstantInt(Cst))))) { 875 auto *VecOpTy = cast<VectorType>(VecOp->getType()); 876 unsigned VecNumElts = VecOpTy->getNumElements(); 877 878 // A badly fit destination size would result in an invalid cast. 879 if (SrcWidth % DestWidth == 0) { 880 uint64_t TruncRatio = SrcWidth / DestWidth; 881 uint64_t BitCastNumElts = VecNumElts * TruncRatio; 882 uint64_t VecOpIdx = Cst->getZExtValue(); 883 uint64_t NewIdx = DL.isBigEndian() ? (VecOpIdx + 1) * TruncRatio - 1 884 : VecOpIdx * TruncRatio; 885 assert(BitCastNumElts <= std::numeric_limits<uint32_t>::max() && 886 "overflow 32-bits"); 887 888 auto *BitCastTo = FixedVectorType::get(DestTy, BitCastNumElts); 889 Value *BitCast = Builder.CreateBitCast(VecOp, BitCastTo); 890 return ExtractElementInst::Create(BitCast, Builder.getInt32(NewIdx)); 891 } 892 } 893 894 return nullptr; 895 } 896 897 Instruction *InstCombiner::transformZExtICmp(ICmpInst *Cmp, ZExtInst &Zext, 898 bool DoTransform) { 899 // If we are just checking for a icmp eq of a single bit and zext'ing it 900 // to an integer, then shift the bit to the appropriate place and then 901 // cast to integer to avoid the comparison. 902 const APInt *Op1CV; 903 if (match(Cmp->getOperand(1), m_APInt(Op1CV))) { 904 905 // zext (x <s 0) to i32 --> x>>u31 true if signbit set. 906 // zext (x >s -1) to i32 --> (x>>u31)^1 true if signbit clear. 907 if ((Cmp->getPredicate() == ICmpInst::ICMP_SLT && Op1CV->isNullValue()) || 908 (Cmp->getPredicate() == ICmpInst::ICMP_SGT && Op1CV->isAllOnesValue())) { 909 if (!DoTransform) return Cmp; 910 911 Value *In = Cmp->getOperand(0); 912 Value *Sh = ConstantInt::get(In->getType(), 913 In->getType()->getScalarSizeInBits() - 1); 914 In = Builder.CreateLShr(In, Sh, In->getName() + ".lobit"); 915 if (In->getType() != Zext.getType()) 916 In = Builder.CreateIntCast(In, Zext.getType(), false /*ZExt*/); 917 918 if (Cmp->getPredicate() == ICmpInst::ICMP_SGT) { 919 Constant *One = ConstantInt::get(In->getType(), 1); 920 In = Builder.CreateXor(In, One, In->getName() + ".not"); 921 } 922 923 return replaceInstUsesWith(Zext, In); 924 } 925 926 // zext (X == 0) to i32 --> X^1 iff X has only the low bit set. 927 // zext (X == 0) to i32 --> (X>>1)^1 iff X has only the 2nd bit set. 928 // zext (X == 1) to i32 --> X iff X has only the low bit set. 929 // zext (X == 2) to i32 --> X>>1 iff X has only the 2nd bit set. 930 // zext (X != 0) to i32 --> X iff X has only the low bit set. 931 // zext (X != 0) to i32 --> X>>1 iff X has only the 2nd bit set. 932 // zext (X != 1) to i32 --> X^1 iff X has only the low bit set. 933 // zext (X != 2) to i32 --> (X>>1)^1 iff X has only the 2nd bit set. 934 if ((Op1CV->isNullValue() || Op1CV->isPowerOf2()) && 935 // This only works for EQ and NE 936 Cmp->isEquality()) { 937 // If Op1C some other power of two, convert: 938 KnownBits Known = computeKnownBits(Cmp->getOperand(0), 0, &Zext); 939 940 APInt KnownZeroMask(~Known.Zero); 941 if (KnownZeroMask.isPowerOf2()) { // Exactly 1 possible 1? 942 if (!DoTransform) return Cmp; 943 944 bool isNE = Cmp->getPredicate() == ICmpInst::ICMP_NE; 945 if (!Op1CV->isNullValue() && (*Op1CV != KnownZeroMask)) { 946 // (X&4) == 2 --> false 947 // (X&4) != 2 --> true 948 Constant *Res = ConstantInt::get(Zext.getType(), isNE); 949 return replaceInstUsesWith(Zext, Res); 950 } 951 952 uint32_t ShAmt = KnownZeroMask.logBase2(); 953 Value *In = Cmp->getOperand(0); 954 if (ShAmt) { 955 // Perform a logical shr by shiftamt. 956 // Insert the shift to put the result in the low bit. 957 In = Builder.CreateLShr(In, ConstantInt::get(In->getType(), ShAmt), 958 In->getName() + ".lobit"); 959 } 960 961 if (!Op1CV->isNullValue() == isNE) { // Toggle the low bit. 962 Constant *One = ConstantInt::get(In->getType(), 1); 963 In = Builder.CreateXor(In, One); 964 } 965 966 if (Zext.getType() == In->getType()) 967 return replaceInstUsesWith(Zext, In); 968 969 Value *IntCast = Builder.CreateIntCast(In, Zext.getType(), false); 970 return replaceInstUsesWith(Zext, IntCast); 971 } 972 } 973 } 974 975 // icmp ne A, B is equal to xor A, B when A and B only really have one bit. 976 // It is also profitable to transform icmp eq into not(xor(A, B)) because that 977 // may lead to additional simplifications. 978 if (Cmp->isEquality() && Zext.getType() == Cmp->getOperand(0)->getType()) { 979 if (IntegerType *ITy = dyn_cast<IntegerType>(Zext.getType())) { 980 Value *LHS = Cmp->getOperand(0); 981 Value *RHS = Cmp->getOperand(1); 982 983 KnownBits KnownLHS = computeKnownBits(LHS, 0, &Zext); 984 KnownBits KnownRHS = computeKnownBits(RHS, 0, &Zext); 985 986 if (KnownLHS.Zero == KnownRHS.Zero && KnownLHS.One == KnownRHS.One) { 987 APInt KnownBits = KnownLHS.Zero | KnownLHS.One; 988 APInt UnknownBit = ~KnownBits; 989 if (UnknownBit.countPopulation() == 1) { 990 if (!DoTransform) return Cmp; 991 992 Value *Result = Builder.CreateXor(LHS, RHS); 993 994 // Mask off any bits that are set and won't be shifted away. 995 if (KnownLHS.One.uge(UnknownBit)) 996 Result = Builder.CreateAnd(Result, 997 ConstantInt::get(ITy, UnknownBit)); 998 999 // Shift the bit we're testing down to the lsb. 1000 Result = Builder.CreateLShr( 1001 Result, ConstantInt::get(ITy, UnknownBit.countTrailingZeros())); 1002 1003 if (Cmp->getPredicate() == ICmpInst::ICMP_EQ) 1004 Result = Builder.CreateXor(Result, ConstantInt::get(ITy, 1)); 1005 Result->takeName(Cmp); 1006 return replaceInstUsesWith(Zext, Result); 1007 } 1008 } 1009 } 1010 } 1011 1012 return nullptr; 1013 } 1014 1015 /// Determine if the specified value can be computed in the specified wider type 1016 /// and produce the same low bits. If not, return false. 1017 /// 1018 /// If this function returns true, it can also return a non-zero number of bits 1019 /// (in BitsToClear) which indicates that the value it computes is correct for 1020 /// the zero extend, but that the additional BitsToClear bits need to be zero'd 1021 /// out. For example, to promote something like: 1022 /// 1023 /// %B = trunc i64 %A to i32 1024 /// %C = lshr i32 %B, 8 1025 /// %E = zext i32 %C to i64 1026 /// 1027 /// CanEvaluateZExtd for the 'lshr' will return true, and BitsToClear will be 1028 /// set to 8 to indicate that the promoted value needs to have bits 24-31 1029 /// cleared in addition to bits 32-63. Since an 'and' will be generated to 1030 /// clear the top bits anyway, doing this has no extra cost. 1031 /// 1032 /// This function works on both vectors and scalars. 1033 static bool canEvaluateZExtd(Value *V, Type *Ty, unsigned &BitsToClear, 1034 InstCombiner &IC, Instruction *CxtI) { 1035 BitsToClear = 0; 1036 if (canAlwaysEvaluateInType(V, Ty)) 1037 return true; 1038 if (canNotEvaluateInType(V, Ty)) 1039 return false; 1040 1041 auto *I = cast<Instruction>(V); 1042 unsigned Tmp; 1043 switch (I->getOpcode()) { 1044 case Instruction::ZExt: // zext(zext(x)) -> zext(x). 1045 case Instruction::SExt: // zext(sext(x)) -> sext(x). 1046 case Instruction::Trunc: // zext(trunc(x)) -> trunc(x) or zext(x) 1047 return true; 1048 case Instruction::And: 1049 case Instruction::Or: 1050 case Instruction::Xor: 1051 case Instruction::Add: 1052 case Instruction::Sub: 1053 case Instruction::Mul: 1054 if (!canEvaluateZExtd(I->getOperand(0), Ty, BitsToClear, IC, CxtI) || 1055 !canEvaluateZExtd(I->getOperand(1), Ty, Tmp, IC, CxtI)) 1056 return false; 1057 // These can all be promoted if neither operand has 'bits to clear'. 1058 if (BitsToClear == 0 && Tmp == 0) 1059 return true; 1060 1061 // If the operation is an AND/OR/XOR and the bits to clear are zero in the 1062 // other side, BitsToClear is ok. 1063 if (Tmp == 0 && I->isBitwiseLogicOp()) { 1064 // We use MaskedValueIsZero here for generality, but the case we care 1065 // about the most is constant RHS. 1066 unsigned VSize = V->getType()->getScalarSizeInBits(); 1067 if (IC.MaskedValueIsZero(I->getOperand(1), 1068 APInt::getHighBitsSet(VSize, BitsToClear), 1069 0, CxtI)) { 1070 // If this is an And instruction and all of the BitsToClear are 1071 // known to be zero we can reset BitsToClear. 1072 if (I->getOpcode() == Instruction::And) 1073 BitsToClear = 0; 1074 return true; 1075 } 1076 } 1077 1078 // Otherwise, we don't know how to analyze this BitsToClear case yet. 1079 return false; 1080 1081 case Instruction::Shl: { 1082 // We can promote shl(x, cst) if we can promote x. Since shl overwrites the 1083 // upper bits we can reduce BitsToClear by the shift amount. 1084 const APInt *Amt; 1085 if (match(I->getOperand(1), m_APInt(Amt))) { 1086 if (!canEvaluateZExtd(I->getOperand(0), Ty, BitsToClear, IC, CxtI)) 1087 return false; 1088 uint64_t ShiftAmt = Amt->getZExtValue(); 1089 BitsToClear = ShiftAmt < BitsToClear ? BitsToClear - ShiftAmt : 0; 1090 return true; 1091 } 1092 return false; 1093 } 1094 case Instruction::LShr: { 1095 // We can promote lshr(x, cst) if we can promote x. This requires the 1096 // ultimate 'and' to clear out the high zero bits we're clearing out though. 1097 const APInt *Amt; 1098 if (match(I->getOperand(1), m_APInt(Amt))) { 1099 if (!canEvaluateZExtd(I->getOperand(0), Ty, BitsToClear, IC, CxtI)) 1100 return false; 1101 BitsToClear += Amt->getZExtValue(); 1102 if (BitsToClear > V->getType()->getScalarSizeInBits()) 1103 BitsToClear = V->getType()->getScalarSizeInBits(); 1104 return true; 1105 } 1106 // Cannot promote variable LSHR. 1107 return false; 1108 } 1109 case Instruction::Select: 1110 if (!canEvaluateZExtd(I->getOperand(1), Ty, Tmp, IC, CxtI) || 1111 !canEvaluateZExtd(I->getOperand(2), Ty, BitsToClear, IC, CxtI) || 1112 // TODO: If important, we could handle the case when the BitsToClear are 1113 // known zero in the disagreeing side. 1114 Tmp != BitsToClear) 1115 return false; 1116 return true; 1117 1118 case Instruction::PHI: { 1119 // We can change a phi if we can change all operands. Note that we never 1120 // get into trouble with cyclic PHIs here because we only consider 1121 // instructions with a single use. 1122 PHINode *PN = cast<PHINode>(I); 1123 if (!canEvaluateZExtd(PN->getIncomingValue(0), Ty, BitsToClear, IC, CxtI)) 1124 return false; 1125 for (unsigned i = 1, e = PN->getNumIncomingValues(); i != e; ++i) 1126 if (!canEvaluateZExtd(PN->getIncomingValue(i), Ty, Tmp, IC, CxtI) || 1127 // TODO: If important, we could handle the case when the BitsToClear 1128 // are known zero in the disagreeing input. 1129 Tmp != BitsToClear) 1130 return false; 1131 return true; 1132 } 1133 default: 1134 // TODO: Can handle more cases here. 1135 return false; 1136 } 1137 } 1138 1139 Instruction *InstCombiner::visitZExt(ZExtInst &CI) { 1140 // If this zero extend is only used by a truncate, let the truncate be 1141 // eliminated before we try to optimize this zext. 1142 if (CI.hasOneUse() && isa<TruncInst>(CI.user_back())) 1143 return nullptr; 1144 1145 // If one of the common conversion will work, do it. 1146 if (Instruction *Result = commonCastTransforms(CI)) 1147 return Result; 1148 1149 Value *Src = CI.getOperand(0); 1150 Type *SrcTy = Src->getType(), *DestTy = CI.getType(); 1151 1152 // Try to extend the entire expression tree to the wide destination type. 1153 unsigned BitsToClear; 1154 if (shouldChangeType(SrcTy, DestTy) && 1155 canEvaluateZExtd(Src, DestTy, BitsToClear, *this, &CI)) { 1156 assert(BitsToClear <= SrcTy->getScalarSizeInBits() && 1157 "Can't clear more bits than in SrcTy"); 1158 1159 // Okay, we can transform this! Insert the new expression now. 1160 LLVM_DEBUG( 1161 dbgs() << "ICE: EvaluateInDifferentType converting expression type" 1162 " to avoid zero extend: " 1163 << CI << '\n'); 1164 Value *Res = EvaluateInDifferentType(Src, DestTy, false); 1165 assert(Res->getType() == DestTy); 1166 1167 // Preserve debug values referring to Src if the zext is its last use. 1168 if (auto *SrcOp = dyn_cast<Instruction>(Src)) 1169 if (SrcOp->hasOneUse()) 1170 replaceAllDbgUsesWith(*SrcOp, *Res, CI, DT); 1171 1172 uint32_t SrcBitsKept = SrcTy->getScalarSizeInBits()-BitsToClear; 1173 uint32_t DestBitSize = DestTy->getScalarSizeInBits(); 1174 1175 // If the high bits are already filled with zeros, just replace this 1176 // cast with the result. 1177 if (MaskedValueIsZero(Res, 1178 APInt::getHighBitsSet(DestBitSize, 1179 DestBitSize-SrcBitsKept), 1180 0, &CI)) 1181 return replaceInstUsesWith(CI, Res); 1182 1183 // We need to emit an AND to clear the high bits. 1184 Constant *C = ConstantInt::get(Res->getType(), 1185 APInt::getLowBitsSet(DestBitSize, SrcBitsKept)); 1186 return BinaryOperator::CreateAnd(Res, C); 1187 } 1188 1189 // If this is a TRUNC followed by a ZEXT then we are dealing with integral 1190 // types and if the sizes are just right we can convert this into a logical 1191 // 'and' which will be much cheaper than the pair of casts. 1192 if (TruncInst *CSrc = dyn_cast<TruncInst>(Src)) { // A->B->C cast 1193 // TODO: Subsume this into EvaluateInDifferentType. 1194 1195 // Get the sizes of the types involved. We know that the intermediate type 1196 // will be smaller than A or C, but don't know the relation between A and C. 1197 Value *A = CSrc->getOperand(0); 1198 unsigned SrcSize = A->getType()->getScalarSizeInBits(); 1199 unsigned MidSize = CSrc->getType()->getScalarSizeInBits(); 1200 unsigned DstSize = CI.getType()->getScalarSizeInBits(); 1201 // If we're actually extending zero bits, then if 1202 // SrcSize < DstSize: zext(a & mask) 1203 // SrcSize == DstSize: a & mask 1204 // SrcSize > DstSize: trunc(a) & mask 1205 if (SrcSize < DstSize) { 1206 APInt AndValue(APInt::getLowBitsSet(SrcSize, MidSize)); 1207 Constant *AndConst = ConstantInt::get(A->getType(), AndValue); 1208 Value *And = Builder.CreateAnd(A, AndConst, CSrc->getName() + ".mask"); 1209 return new ZExtInst(And, CI.getType()); 1210 } 1211 1212 if (SrcSize == DstSize) { 1213 APInt AndValue(APInt::getLowBitsSet(SrcSize, MidSize)); 1214 return BinaryOperator::CreateAnd(A, ConstantInt::get(A->getType(), 1215 AndValue)); 1216 } 1217 if (SrcSize > DstSize) { 1218 Value *Trunc = Builder.CreateTrunc(A, CI.getType()); 1219 APInt AndValue(APInt::getLowBitsSet(DstSize, MidSize)); 1220 return BinaryOperator::CreateAnd(Trunc, 1221 ConstantInt::get(Trunc->getType(), 1222 AndValue)); 1223 } 1224 } 1225 1226 if (ICmpInst *Cmp = dyn_cast<ICmpInst>(Src)) 1227 return transformZExtICmp(Cmp, CI); 1228 1229 BinaryOperator *SrcI = dyn_cast<BinaryOperator>(Src); 1230 if (SrcI && SrcI->getOpcode() == Instruction::Or) { 1231 // zext (or icmp, icmp) -> or (zext icmp), (zext icmp) if at least one 1232 // of the (zext icmp) can be eliminated. If so, immediately perform the 1233 // according elimination. 1234 ICmpInst *LHS = dyn_cast<ICmpInst>(SrcI->getOperand(0)); 1235 ICmpInst *RHS = dyn_cast<ICmpInst>(SrcI->getOperand(1)); 1236 if (LHS && RHS && LHS->hasOneUse() && RHS->hasOneUse() && 1237 (transformZExtICmp(LHS, CI, false) || 1238 transformZExtICmp(RHS, CI, false))) { 1239 // zext (or icmp, icmp) -> or (zext icmp), (zext icmp) 1240 Value *LCast = Builder.CreateZExt(LHS, CI.getType(), LHS->getName()); 1241 Value *RCast = Builder.CreateZExt(RHS, CI.getType(), RHS->getName()); 1242 Value *Or = Builder.CreateOr(LCast, RCast, CI.getName()); 1243 if (auto *OrInst = dyn_cast<Instruction>(Or)) 1244 Builder.SetInsertPoint(OrInst); 1245 1246 // Perform the elimination. 1247 if (auto *LZExt = dyn_cast<ZExtInst>(LCast)) 1248 transformZExtICmp(LHS, *LZExt); 1249 if (auto *RZExt = dyn_cast<ZExtInst>(RCast)) 1250 transformZExtICmp(RHS, *RZExt); 1251 1252 return replaceInstUsesWith(CI, Or); 1253 } 1254 } 1255 1256 // zext(trunc(X) & C) -> (X & zext(C)). 1257 Constant *C; 1258 Value *X; 1259 if (SrcI && 1260 match(SrcI, m_OneUse(m_And(m_Trunc(m_Value(X)), m_Constant(C)))) && 1261 X->getType() == CI.getType()) 1262 return BinaryOperator::CreateAnd(X, ConstantExpr::getZExt(C, CI.getType())); 1263 1264 // zext((trunc(X) & C) ^ C) -> ((X & zext(C)) ^ zext(C)). 1265 Value *And; 1266 if (SrcI && match(SrcI, m_OneUse(m_Xor(m_Value(And), m_Constant(C)))) && 1267 match(And, m_OneUse(m_And(m_Trunc(m_Value(X)), m_Specific(C)))) && 1268 X->getType() == CI.getType()) { 1269 Constant *ZC = ConstantExpr::getZExt(C, CI.getType()); 1270 return BinaryOperator::CreateXor(Builder.CreateAnd(X, ZC), ZC); 1271 } 1272 1273 return nullptr; 1274 } 1275 1276 /// Transform (sext icmp) to bitwise / integer operations to eliminate the icmp. 1277 Instruction *InstCombiner::transformSExtICmp(ICmpInst *ICI, Instruction &CI) { 1278 Value *Op0 = ICI->getOperand(0), *Op1 = ICI->getOperand(1); 1279 ICmpInst::Predicate Pred = ICI->getPredicate(); 1280 1281 // Don't bother if Op1 isn't of vector or integer type. 1282 if (!Op1->getType()->isIntOrIntVectorTy()) 1283 return nullptr; 1284 1285 if ((Pred == ICmpInst::ICMP_SLT && match(Op1, m_ZeroInt())) || 1286 (Pred == ICmpInst::ICMP_SGT && match(Op1, m_AllOnes()))) { 1287 // (x <s 0) ? -1 : 0 -> ashr x, 31 -> all ones if negative 1288 // (x >s -1) ? -1 : 0 -> not (ashr x, 31) -> all ones if positive 1289 Value *Sh = ConstantInt::get(Op0->getType(), 1290 Op0->getType()->getScalarSizeInBits() - 1); 1291 Value *In = Builder.CreateAShr(Op0, Sh, Op0->getName() + ".lobit"); 1292 if (In->getType() != CI.getType()) 1293 In = Builder.CreateIntCast(In, CI.getType(), true /*SExt*/); 1294 1295 if (Pred == ICmpInst::ICMP_SGT) 1296 In = Builder.CreateNot(In, In->getName() + ".not"); 1297 return replaceInstUsesWith(CI, In); 1298 } 1299 1300 if (ConstantInt *Op1C = dyn_cast<ConstantInt>(Op1)) { 1301 // If we know that only one bit of the LHS of the icmp can be set and we 1302 // have an equality comparison with zero or a power of 2, we can transform 1303 // the icmp and sext into bitwise/integer operations. 1304 if (ICI->hasOneUse() && 1305 ICI->isEquality() && (Op1C->isZero() || Op1C->getValue().isPowerOf2())){ 1306 KnownBits Known = computeKnownBits(Op0, 0, &CI); 1307 1308 APInt KnownZeroMask(~Known.Zero); 1309 if (KnownZeroMask.isPowerOf2()) { 1310 Value *In = ICI->getOperand(0); 1311 1312 // If the icmp tests for a known zero bit we can constant fold it. 1313 if (!Op1C->isZero() && Op1C->getValue() != KnownZeroMask) { 1314 Value *V = Pred == ICmpInst::ICMP_NE ? 1315 ConstantInt::getAllOnesValue(CI.getType()) : 1316 ConstantInt::getNullValue(CI.getType()); 1317 return replaceInstUsesWith(CI, V); 1318 } 1319 1320 if (!Op1C->isZero() == (Pred == ICmpInst::ICMP_NE)) { 1321 // sext ((x & 2^n) == 0) -> (x >> n) - 1 1322 // sext ((x & 2^n) != 2^n) -> (x >> n) - 1 1323 unsigned ShiftAmt = KnownZeroMask.countTrailingZeros(); 1324 // Perform a right shift to place the desired bit in the LSB. 1325 if (ShiftAmt) 1326 In = Builder.CreateLShr(In, 1327 ConstantInt::get(In->getType(), ShiftAmt)); 1328 1329 // At this point "In" is either 1 or 0. Subtract 1 to turn 1330 // {1, 0} -> {0, -1}. 1331 In = Builder.CreateAdd(In, 1332 ConstantInt::getAllOnesValue(In->getType()), 1333 "sext"); 1334 } else { 1335 // sext ((x & 2^n) != 0) -> (x << bitwidth-n) a>> bitwidth-1 1336 // sext ((x & 2^n) == 2^n) -> (x << bitwidth-n) a>> bitwidth-1 1337 unsigned ShiftAmt = KnownZeroMask.countLeadingZeros(); 1338 // Perform a left shift to place the desired bit in the MSB. 1339 if (ShiftAmt) 1340 In = Builder.CreateShl(In, 1341 ConstantInt::get(In->getType(), ShiftAmt)); 1342 1343 // Distribute the bit over the whole bit width. 1344 In = Builder.CreateAShr(In, ConstantInt::get(In->getType(), 1345 KnownZeroMask.getBitWidth() - 1), "sext"); 1346 } 1347 1348 if (CI.getType() == In->getType()) 1349 return replaceInstUsesWith(CI, In); 1350 return CastInst::CreateIntegerCast(In, CI.getType(), true/*SExt*/); 1351 } 1352 } 1353 } 1354 1355 return nullptr; 1356 } 1357 1358 /// Return true if we can take the specified value and return it as type Ty 1359 /// without inserting any new casts and without changing the value of the common 1360 /// low bits. This is used by code that tries to promote integer operations to 1361 /// a wider types will allow us to eliminate the extension. 1362 /// 1363 /// This function works on both vectors and scalars. 1364 /// 1365 static bool canEvaluateSExtd(Value *V, Type *Ty) { 1366 assert(V->getType()->getScalarSizeInBits() < Ty->getScalarSizeInBits() && 1367 "Can't sign extend type to a smaller type"); 1368 if (canAlwaysEvaluateInType(V, Ty)) 1369 return true; 1370 if (canNotEvaluateInType(V, Ty)) 1371 return false; 1372 1373 auto *I = cast<Instruction>(V); 1374 switch (I->getOpcode()) { 1375 case Instruction::SExt: // sext(sext(x)) -> sext(x) 1376 case Instruction::ZExt: // sext(zext(x)) -> zext(x) 1377 case Instruction::Trunc: // sext(trunc(x)) -> trunc(x) or sext(x) 1378 return true; 1379 case Instruction::And: 1380 case Instruction::Or: 1381 case Instruction::Xor: 1382 case Instruction::Add: 1383 case Instruction::Sub: 1384 case Instruction::Mul: 1385 // These operators can all arbitrarily be extended if their inputs can. 1386 return canEvaluateSExtd(I->getOperand(0), Ty) && 1387 canEvaluateSExtd(I->getOperand(1), Ty); 1388 1389 //case Instruction::Shl: TODO 1390 //case Instruction::LShr: TODO 1391 1392 case Instruction::Select: 1393 return canEvaluateSExtd(I->getOperand(1), Ty) && 1394 canEvaluateSExtd(I->getOperand(2), Ty); 1395 1396 case Instruction::PHI: { 1397 // We can change a phi if we can change all operands. Note that we never 1398 // get into trouble with cyclic PHIs here because we only consider 1399 // instructions with a single use. 1400 PHINode *PN = cast<PHINode>(I); 1401 for (Value *IncValue : PN->incoming_values()) 1402 if (!canEvaluateSExtd(IncValue, Ty)) return false; 1403 return true; 1404 } 1405 default: 1406 // TODO: Can handle more cases here. 1407 break; 1408 } 1409 1410 return false; 1411 } 1412 1413 Instruction *InstCombiner::visitSExt(SExtInst &CI) { 1414 // If this sign extend is only used by a truncate, let the truncate be 1415 // eliminated before we try to optimize this sext. 1416 if (CI.hasOneUse() && isa<TruncInst>(CI.user_back())) 1417 return nullptr; 1418 1419 if (Instruction *I = commonCastTransforms(CI)) 1420 return I; 1421 1422 Value *Src = CI.getOperand(0); 1423 Type *SrcTy = Src->getType(), *DestTy = CI.getType(); 1424 1425 // If we know that the value being extended is positive, we can use a zext 1426 // instead. 1427 KnownBits Known = computeKnownBits(Src, 0, &CI); 1428 if (Known.isNonNegative()) 1429 return CastInst::Create(Instruction::ZExt, Src, DestTy); 1430 1431 // Try to extend the entire expression tree to the wide destination type. 1432 if (shouldChangeType(SrcTy, DestTy) && canEvaluateSExtd(Src, DestTy)) { 1433 // Okay, we can transform this! Insert the new expression now. 1434 LLVM_DEBUG( 1435 dbgs() << "ICE: EvaluateInDifferentType converting expression type" 1436 " to avoid sign extend: " 1437 << CI << '\n'); 1438 Value *Res = EvaluateInDifferentType(Src, DestTy, true); 1439 assert(Res->getType() == DestTy); 1440 1441 uint32_t SrcBitSize = SrcTy->getScalarSizeInBits(); 1442 uint32_t DestBitSize = DestTy->getScalarSizeInBits(); 1443 1444 // If the high bits are already filled with sign bit, just replace this 1445 // cast with the result. 1446 if (ComputeNumSignBits(Res, 0, &CI) > DestBitSize - SrcBitSize) 1447 return replaceInstUsesWith(CI, Res); 1448 1449 // We need to emit a shl + ashr to do the sign extend. 1450 Value *ShAmt = ConstantInt::get(DestTy, DestBitSize-SrcBitSize); 1451 return BinaryOperator::CreateAShr(Builder.CreateShl(Res, ShAmt, "sext"), 1452 ShAmt); 1453 } 1454 1455 // If the input is a trunc from the destination type, then turn sext(trunc(x)) 1456 // into shifts. 1457 Value *X; 1458 if (match(Src, m_OneUse(m_Trunc(m_Value(X)))) && X->getType() == DestTy) { 1459 // sext(trunc(X)) --> ashr(shl(X, C), C) 1460 unsigned SrcBitSize = SrcTy->getScalarSizeInBits(); 1461 unsigned DestBitSize = DestTy->getScalarSizeInBits(); 1462 Constant *ShAmt = ConstantInt::get(DestTy, DestBitSize - SrcBitSize); 1463 return BinaryOperator::CreateAShr(Builder.CreateShl(X, ShAmt), ShAmt); 1464 } 1465 1466 if (ICmpInst *ICI = dyn_cast<ICmpInst>(Src)) 1467 return transformSExtICmp(ICI, CI); 1468 1469 // If the input is a shl/ashr pair of a same constant, then this is a sign 1470 // extension from a smaller value. If we could trust arbitrary bitwidth 1471 // integers, we could turn this into a truncate to the smaller bit and then 1472 // use a sext for the whole extension. Since we don't, look deeper and check 1473 // for a truncate. If the source and dest are the same type, eliminate the 1474 // trunc and extend and just do shifts. For example, turn: 1475 // %a = trunc i32 %i to i8 1476 // %b = shl i8 %a, 6 1477 // %c = ashr i8 %b, 6 1478 // %d = sext i8 %c to i32 1479 // into: 1480 // %a = shl i32 %i, 30 1481 // %d = ashr i32 %a, 30 1482 Value *A = nullptr; 1483 // TODO: Eventually this could be subsumed by EvaluateInDifferentType. 1484 Constant *BA = nullptr, *CA = nullptr; 1485 if (match(Src, m_AShr(m_Shl(m_Trunc(m_Value(A)), m_Constant(BA)), 1486 m_Constant(CA))) && 1487 BA == CA && A->getType() == CI.getType()) { 1488 unsigned MidSize = Src->getType()->getScalarSizeInBits(); 1489 unsigned SrcDstSize = CI.getType()->getScalarSizeInBits(); 1490 Constant *SizeDiff = ConstantInt::get(CA->getType(), SrcDstSize - MidSize); 1491 Constant *ShAmt = ConstantExpr::getAdd(CA, SizeDiff); 1492 Constant *ShAmtExt = ConstantExpr::getSExt(ShAmt, CI.getType()); 1493 A = Builder.CreateShl(A, ShAmtExt, CI.getName()); 1494 return BinaryOperator::CreateAShr(A, ShAmtExt); 1495 } 1496 1497 return nullptr; 1498 } 1499 1500 1501 /// Return a Constant* for the specified floating-point constant if it fits 1502 /// in the specified FP type without changing its value. 1503 static bool fitsInFPType(ConstantFP *CFP, const fltSemantics &Sem) { 1504 bool losesInfo; 1505 APFloat F = CFP->getValueAPF(); 1506 (void)F.convert(Sem, APFloat::rmNearestTiesToEven, &losesInfo); 1507 return !losesInfo; 1508 } 1509 1510 static Type *shrinkFPConstant(ConstantFP *CFP) { 1511 if (CFP->getType() == Type::getPPC_FP128Ty(CFP->getContext())) 1512 return nullptr; // No constant folding of this. 1513 // See if the value can be truncated to half and then reextended. 1514 if (fitsInFPType(CFP, APFloat::IEEEhalf())) 1515 return Type::getHalfTy(CFP->getContext()); 1516 // See if the value can be truncated to float and then reextended. 1517 if (fitsInFPType(CFP, APFloat::IEEEsingle())) 1518 return Type::getFloatTy(CFP->getContext()); 1519 if (CFP->getType()->isDoubleTy()) 1520 return nullptr; // Won't shrink. 1521 if (fitsInFPType(CFP, APFloat::IEEEdouble())) 1522 return Type::getDoubleTy(CFP->getContext()); 1523 // Don't try to shrink to various long double types. 1524 return nullptr; 1525 } 1526 1527 // Determine if this is a vector of ConstantFPs and if so, return the minimal 1528 // type we can safely truncate all elements to. 1529 // TODO: Make these support undef elements. 1530 static Type *shrinkFPConstantVector(Value *V) { 1531 auto *CV = dyn_cast<Constant>(V); 1532 auto *CVVTy = dyn_cast<VectorType>(V->getType()); 1533 if (!CV || !CVVTy) 1534 return nullptr; 1535 1536 Type *MinType = nullptr; 1537 1538 unsigned NumElts = CVVTy->getNumElements(); 1539 for (unsigned i = 0; i != NumElts; ++i) { 1540 auto *CFP = dyn_cast_or_null<ConstantFP>(CV->getAggregateElement(i)); 1541 if (!CFP) 1542 return nullptr; 1543 1544 Type *T = shrinkFPConstant(CFP); 1545 if (!T) 1546 return nullptr; 1547 1548 // If we haven't found a type yet or this type has a larger mantissa than 1549 // our previous type, this is our new minimal type. 1550 if (!MinType || T->getFPMantissaWidth() > MinType->getFPMantissaWidth()) 1551 MinType = T; 1552 } 1553 1554 // Make a vector type from the minimal type. 1555 return FixedVectorType::get(MinType, NumElts); 1556 } 1557 1558 /// Find the minimum FP type we can safely truncate to. 1559 static Type *getMinimumFPType(Value *V) { 1560 if (auto *FPExt = dyn_cast<FPExtInst>(V)) 1561 return FPExt->getOperand(0)->getType(); 1562 1563 // If this value is a constant, return the constant in the smallest FP type 1564 // that can accurately represent it. This allows us to turn 1565 // (float)((double)X+2.0) into x+2.0f. 1566 if (auto *CFP = dyn_cast<ConstantFP>(V)) 1567 if (Type *T = shrinkFPConstant(CFP)) 1568 return T; 1569 1570 // Try to shrink a vector of FP constants. 1571 if (Type *T = shrinkFPConstantVector(V)) 1572 return T; 1573 1574 return V->getType(); 1575 } 1576 1577 /// Return true if the cast from integer to FP can be proven to be exact for all 1578 /// possible inputs (the conversion does not lose any precision). 1579 static bool isKnownExactCastIntToFP(CastInst &I) { 1580 CastInst::CastOps Opcode = I.getOpcode(); 1581 assert((Opcode == CastInst::SIToFP || Opcode == CastInst::UIToFP) && 1582 "Unexpected cast"); 1583 Value *Src = I.getOperand(0); 1584 Type *SrcTy = Src->getType(); 1585 Type *FPTy = I.getType(); 1586 bool IsSigned = Opcode == Instruction::SIToFP; 1587 int SrcSize = (int)SrcTy->getScalarSizeInBits() - IsSigned; 1588 1589 // Easy case - if the source integer type has less bits than the FP mantissa, 1590 // then the cast must be exact. 1591 int DestNumSigBits = FPTy->getFPMantissaWidth(); 1592 if (SrcSize <= DestNumSigBits) 1593 return true; 1594 1595 // Cast from FP to integer and back to FP is independent of the intermediate 1596 // integer width because of poison on overflow. 1597 Value *F; 1598 if (match(Src, m_FPToSI(m_Value(F))) || match(Src, m_FPToUI(m_Value(F)))) { 1599 // If this is uitofp (fptosi F), the source needs an extra bit to avoid 1600 // potential rounding of negative FP input values. 1601 int SrcNumSigBits = F->getType()->getFPMantissaWidth(); 1602 if (!IsSigned && match(Src, m_FPToSI(m_Value()))) 1603 SrcNumSigBits++; 1604 1605 // [su]itofp (fpto[su]i F) --> exact if the source type has less or equal 1606 // significant bits than the destination (and make sure neither type is 1607 // weird -- ppc_fp128). 1608 if (SrcNumSigBits > 0 && DestNumSigBits > 0 && 1609 SrcNumSigBits <= DestNumSigBits) 1610 return true; 1611 } 1612 1613 // TODO: 1614 // Try harder to find if the source integer type has less significant bits. 1615 // For example, compute number of sign bits or compute low bit mask. 1616 return false; 1617 } 1618 1619 Instruction *InstCombiner::visitFPTrunc(FPTruncInst &FPT) { 1620 if (Instruction *I = commonCastTransforms(FPT)) 1621 return I; 1622 1623 // If we have fptrunc(OpI (fpextend x), (fpextend y)), we would like to 1624 // simplify this expression to avoid one or more of the trunc/extend 1625 // operations if we can do so without changing the numerical results. 1626 // 1627 // The exact manner in which the widths of the operands interact to limit 1628 // what we can and cannot do safely varies from operation to operation, and 1629 // is explained below in the various case statements. 1630 Type *Ty = FPT.getType(); 1631 auto *BO = dyn_cast<BinaryOperator>(FPT.getOperand(0)); 1632 if (BO && BO->hasOneUse()) { 1633 Type *LHSMinType = getMinimumFPType(BO->getOperand(0)); 1634 Type *RHSMinType = getMinimumFPType(BO->getOperand(1)); 1635 unsigned OpWidth = BO->getType()->getFPMantissaWidth(); 1636 unsigned LHSWidth = LHSMinType->getFPMantissaWidth(); 1637 unsigned RHSWidth = RHSMinType->getFPMantissaWidth(); 1638 unsigned SrcWidth = std::max(LHSWidth, RHSWidth); 1639 unsigned DstWidth = Ty->getFPMantissaWidth(); 1640 switch (BO->getOpcode()) { 1641 default: break; 1642 case Instruction::FAdd: 1643 case Instruction::FSub: 1644 // For addition and subtraction, the infinitely precise result can 1645 // essentially be arbitrarily wide; proving that double rounding 1646 // will not occur because the result of OpI is exact (as we will for 1647 // FMul, for example) is hopeless. However, we *can* nonetheless 1648 // frequently know that double rounding cannot occur (or that it is 1649 // innocuous) by taking advantage of the specific structure of 1650 // infinitely-precise results that admit double rounding. 1651 // 1652 // Specifically, if OpWidth >= 2*DstWdith+1 and DstWidth is sufficient 1653 // to represent both sources, we can guarantee that the double 1654 // rounding is innocuous (See p50 of Figueroa's 2000 PhD thesis, 1655 // "A Rigorous Framework for Fully Supporting the IEEE Standard ..." 1656 // for proof of this fact). 1657 // 1658 // Note: Figueroa does not consider the case where DstFormat != 1659 // SrcFormat. It's possible (likely even!) that this analysis 1660 // could be tightened for those cases, but they are rare (the main 1661 // case of interest here is (float)((double)float + float)). 1662 if (OpWidth >= 2*DstWidth+1 && DstWidth >= SrcWidth) { 1663 Value *LHS = Builder.CreateFPTrunc(BO->getOperand(0), Ty); 1664 Value *RHS = Builder.CreateFPTrunc(BO->getOperand(1), Ty); 1665 Instruction *RI = BinaryOperator::Create(BO->getOpcode(), LHS, RHS); 1666 RI->copyFastMathFlags(BO); 1667 return RI; 1668 } 1669 break; 1670 case Instruction::FMul: 1671 // For multiplication, the infinitely precise result has at most 1672 // LHSWidth + RHSWidth significant bits; if OpWidth is sufficient 1673 // that such a value can be exactly represented, then no double 1674 // rounding can possibly occur; we can safely perform the operation 1675 // in the destination format if it can represent both sources. 1676 if (OpWidth >= LHSWidth + RHSWidth && DstWidth >= SrcWidth) { 1677 Value *LHS = Builder.CreateFPTrunc(BO->getOperand(0), Ty); 1678 Value *RHS = Builder.CreateFPTrunc(BO->getOperand(1), Ty); 1679 return BinaryOperator::CreateFMulFMF(LHS, RHS, BO); 1680 } 1681 break; 1682 case Instruction::FDiv: 1683 // For division, we use again use the bound from Figueroa's 1684 // dissertation. I am entirely certain that this bound can be 1685 // tightened in the unbalanced operand case by an analysis based on 1686 // the diophantine rational approximation bound, but the well-known 1687 // condition used here is a good conservative first pass. 1688 // TODO: Tighten bound via rigorous analysis of the unbalanced case. 1689 if (OpWidth >= 2*DstWidth && DstWidth >= SrcWidth) { 1690 Value *LHS = Builder.CreateFPTrunc(BO->getOperand(0), Ty); 1691 Value *RHS = Builder.CreateFPTrunc(BO->getOperand(1), Ty); 1692 return BinaryOperator::CreateFDivFMF(LHS, RHS, BO); 1693 } 1694 break; 1695 case Instruction::FRem: { 1696 // Remainder is straightforward. Remainder is always exact, so the 1697 // type of OpI doesn't enter into things at all. We simply evaluate 1698 // in whichever source type is larger, then convert to the 1699 // destination type. 1700 if (SrcWidth == OpWidth) 1701 break; 1702 Value *LHS, *RHS; 1703 if (LHSWidth == SrcWidth) { 1704 LHS = Builder.CreateFPTrunc(BO->getOperand(0), LHSMinType); 1705 RHS = Builder.CreateFPTrunc(BO->getOperand(1), LHSMinType); 1706 } else { 1707 LHS = Builder.CreateFPTrunc(BO->getOperand(0), RHSMinType); 1708 RHS = Builder.CreateFPTrunc(BO->getOperand(1), RHSMinType); 1709 } 1710 1711 Value *ExactResult = Builder.CreateFRemFMF(LHS, RHS, BO); 1712 return CastInst::CreateFPCast(ExactResult, Ty); 1713 } 1714 } 1715 } 1716 1717 // (fptrunc (fneg x)) -> (fneg (fptrunc x)) 1718 Value *X; 1719 Instruction *Op = dyn_cast<Instruction>(FPT.getOperand(0)); 1720 if (Op && Op->hasOneUse()) { 1721 // FIXME: The FMF should propagate from the fptrunc, not the source op. 1722 IRBuilder<>::FastMathFlagGuard FMFG(Builder); 1723 if (isa<FPMathOperator>(Op)) 1724 Builder.setFastMathFlags(Op->getFastMathFlags()); 1725 1726 if (match(Op, m_FNeg(m_Value(X)))) { 1727 Value *InnerTrunc = Builder.CreateFPTrunc(X, Ty); 1728 1729 return UnaryOperator::CreateFNegFMF(InnerTrunc, Op); 1730 } 1731 1732 // If we are truncating a select that has an extended operand, we can 1733 // narrow the other operand and do the select as a narrow op. 1734 Value *Cond, *X, *Y; 1735 if (match(Op, m_Select(m_Value(Cond), m_FPExt(m_Value(X)), m_Value(Y))) && 1736 X->getType() == Ty) { 1737 // fptrunc (select Cond, (fpext X), Y --> select Cond, X, (fptrunc Y) 1738 Value *NarrowY = Builder.CreateFPTrunc(Y, Ty); 1739 Value *Sel = Builder.CreateSelect(Cond, X, NarrowY, "narrow.sel", Op); 1740 return replaceInstUsesWith(FPT, Sel); 1741 } 1742 if (match(Op, m_Select(m_Value(Cond), m_Value(Y), m_FPExt(m_Value(X)))) && 1743 X->getType() == Ty) { 1744 // fptrunc (select Cond, Y, (fpext X) --> select Cond, (fptrunc Y), X 1745 Value *NarrowY = Builder.CreateFPTrunc(Y, Ty); 1746 Value *Sel = Builder.CreateSelect(Cond, NarrowY, X, "narrow.sel", Op); 1747 return replaceInstUsesWith(FPT, Sel); 1748 } 1749 } 1750 1751 if (auto *II = dyn_cast<IntrinsicInst>(FPT.getOperand(0))) { 1752 switch (II->getIntrinsicID()) { 1753 default: break; 1754 case Intrinsic::ceil: 1755 case Intrinsic::fabs: 1756 case Intrinsic::floor: 1757 case Intrinsic::nearbyint: 1758 case Intrinsic::rint: 1759 case Intrinsic::round: 1760 case Intrinsic::roundeven: 1761 case Intrinsic::trunc: { 1762 Value *Src = II->getArgOperand(0); 1763 if (!Src->hasOneUse()) 1764 break; 1765 1766 // Except for fabs, this transformation requires the input of the unary FP 1767 // operation to be itself an fpext from the type to which we're 1768 // truncating. 1769 if (II->getIntrinsicID() != Intrinsic::fabs) { 1770 FPExtInst *FPExtSrc = dyn_cast<FPExtInst>(Src); 1771 if (!FPExtSrc || FPExtSrc->getSrcTy() != Ty) 1772 break; 1773 } 1774 1775 // Do unary FP operation on smaller type. 1776 // (fptrunc (fabs x)) -> (fabs (fptrunc x)) 1777 Value *InnerTrunc = Builder.CreateFPTrunc(Src, Ty); 1778 Function *Overload = Intrinsic::getDeclaration(FPT.getModule(), 1779 II->getIntrinsicID(), Ty); 1780 SmallVector<OperandBundleDef, 1> OpBundles; 1781 II->getOperandBundlesAsDefs(OpBundles); 1782 CallInst *NewCI = 1783 CallInst::Create(Overload, {InnerTrunc}, OpBundles, II->getName()); 1784 NewCI->copyFastMathFlags(II); 1785 return NewCI; 1786 } 1787 } 1788 } 1789 1790 if (Instruction *I = shrinkInsertElt(FPT, Builder)) 1791 return I; 1792 1793 Value *Src = FPT.getOperand(0); 1794 if (isa<SIToFPInst>(Src) || isa<UIToFPInst>(Src)) { 1795 auto *FPCast = cast<CastInst>(Src); 1796 if (isKnownExactCastIntToFP(*FPCast)) 1797 return CastInst::Create(FPCast->getOpcode(), FPCast->getOperand(0), Ty); 1798 } 1799 1800 return nullptr; 1801 } 1802 1803 Instruction *InstCombiner::visitFPExt(CastInst &FPExt) { 1804 // If the source operand is a cast from integer to FP and known exact, then 1805 // cast the integer operand directly to the destination type. 1806 Type *Ty = FPExt.getType(); 1807 Value *Src = FPExt.getOperand(0); 1808 if (isa<SIToFPInst>(Src) || isa<UIToFPInst>(Src)) { 1809 auto *FPCast = cast<CastInst>(Src); 1810 if (isKnownExactCastIntToFP(*FPCast)) 1811 return CastInst::Create(FPCast->getOpcode(), FPCast->getOperand(0), Ty); 1812 } 1813 1814 return commonCastTransforms(FPExt); 1815 } 1816 1817 /// fpto{s/u}i({u/s}itofp(X)) --> X or zext(X) or sext(X) or trunc(X) 1818 /// This is safe if the intermediate type has enough bits in its mantissa to 1819 /// accurately represent all values of X. For example, this won't work with 1820 /// i64 -> float -> i64. 1821 Instruction *InstCombiner::foldItoFPtoI(CastInst &FI) { 1822 if (!isa<UIToFPInst>(FI.getOperand(0)) && !isa<SIToFPInst>(FI.getOperand(0))) 1823 return nullptr; 1824 1825 auto *OpI = cast<CastInst>(FI.getOperand(0)); 1826 Value *X = OpI->getOperand(0); 1827 Type *XType = X->getType(); 1828 Type *DestType = FI.getType(); 1829 bool IsOutputSigned = isa<FPToSIInst>(FI); 1830 1831 // Since we can assume the conversion won't overflow, our decision as to 1832 // whether the input will fit in the float should depend on the minimum 1833 // of the input range and output range. 1834 1835 // This means this is also safe for a signed input and unsigned output, since 1836 // a negative input would lead to undefined behavior. 1837 if (!isKnownExactCastIntToFP(*OpI)) { 1838 // The first cast may not round exactly based on the source integer width 1839 // and FP width, but the overflow UB rules can still allow this to fold. 1840 // If the destination type is narrow, that means the intermediate FP value 1841 // must be large enough to hold the source value exactly. 1842 // For example, (uint8_t)((float)(uint32_t 16777217) is undefined behavior. 1843 int OutputSize = (int)DestType->getScalarSizeInBits() - IsOutputSigned; 1844 if (OutputSize > OpI->getType()->getFPMantissaWidth()) 1845 return nullptr; 1846 } 1847 1848 if (DestType->getScalarSizeInBits() > XType->getScalarSizeInBits()) { 1849 bool IsInputSigned = isa<SIToFPInst>(OpI); 1850 if (IsInputSigned && IsOutputSigned) 1851 return new SExtInst(X, DestType); 1852 return new ZExtInst(X, DestType); 1853 } 1854 if (DestType->getScalarSizeInBits() < XType->getScalarSizeInBits()) 1855 return new TruncInst(X, DestType); 1856 1857 assert(XType == DestType && "Unexpected types for int to FP to int casts"); 1858 return replaceInstUsesWith(FI, X); 1859 } 1860 1861 Instruction *InstCombiner::visitFPToUI(FPToUIInst &FI) { 1862 if (Instruction *I = foldItoFPtoI(FI)) 1863 return I; 1864 1865 return commonCastTransforms(FI); 1866 } 1867 1868 Instruction *InstCombiner::visitFPToSI(FPToSIInst &FI) { 1869 if (Instruction *I = foldItoFPtoI(FI)) 1870 return I; 1871 1872 return commonCastTransforms(FI); 1873 } 1874 1875 Instruction *InstCombiner::visitUIToFP(CastInst &CI) { 1876 return commonCastTransforms(CI); 1877 } 1878 1879 Instruction *InstCombiner::visitSIToFP(CastInst &CI) { 1880 return commonCastTransforms(CI); 1881 } 1882 1883 Instruction *InstCombiner::visitIntToPtr(IntToPtrInst &CI) { 1884 // If the source integer type is not the intptr_t type for this target, do a 1885 // trunc or zext to the intptr_t type, then inttoptr of it. This allows the 1886 // cast to be exposed to other transforms. 1887 unsigned AS = CI.getAddressSpace(); 1888 if (CI.getOperand(0)->getType()->getScalarSizeInBits() != 1889 DL.getPointerSizeInBits(AS)) { 1890 Type *Ty = DL.getIntPtrType(CI.getContext(), AS); 1891 // Handle vectors of pointers. 1892 if (auto *CIVTy = dyn_cast<VectorType>(CI.getType())) 1893 Ty = VectorType::get(Ty, CIVTy->getElementCount()); 1894 1895 Value *P = Builder.CreateZExtOrTrunc(CI.getOperand(0), Ty); 1896 return new IntToPtrInst(P, CI.getType()); 1897 } 1898 1899 if (Instruction *I = commonCastTransforms(CI)) 1900 return I; 1901 1902 return nullptr; 1903 } 1904 1905 /// Implement the transforms for cast of pointer (bitcast/ptrtoint) 1906 Instruction *InstCombiner::commonPointerCastTransforms(CastInst &CI) { 1907 Value *Src = CI.getOperand(0); 1908 1909 if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(Src)) { 1910 // If casting the result of a getelementptr instruction with no offset, turn 1911 // this into a cast of the original pointer! 1912 if (GEP->hasAllZeroIndices() && 1913 // If CI is an addrspacecast and GEP changes the poiner type, merging 1914 // GEP into CI would undo canonicalizing addrspacecast with different 1915 // pointer types, causing infinite loops. 1916 (!isa<AddrSpaceCastInst>(CI) || 1917 GEP->getType() == GEP->getPointerOperandType())) { 1918 // Changing the cast operand is usually not a good idea but it is safe 1919 // here because the pointer operand is being replaced with another 1920 // pointer operand so the opcode doesn't need to change. 1921 return replaceOperand(CI, 0, GEP->getOperand(0)); 1922 } 1923 } 1924 1925 return commonCastTransforms(CI); 1926 } 1927 1928 Instruction *InstCombiner::visitPtrToInt(PtrToIntInst &CI) { 1929 // If the destination integer type is not the intptr_t type for this target, 1930 // do a ptrtoint to intptr_t then do a trunc or zext. This allows the cast 1931 // to be exposed to other transforms. 1932 1933 Type *Ty = CI.getType(); 1934 unsigned AS = CI.getPointerAddressSpace(); 1935 1936 if (Ty->getScalarSizeInBits() == DL.getPointerSizeInBits(AS)) 1937 return commonPointerCastTransforms(CI); 1938 1939 Type *PtrTy = DL.getIntPtrType(CI.getContext(), AS); 1940 if (auto *VTy = dyn_cast<VectorType>(Ty)) { 1941 // Handle vectors of pointers. 1942 // FIXME: what should happen for scalable vectors? 1943 PtrTy = FixedVectorType::get(PtrTy, VTy->getNumElements()); 1944 } 1945 1946 Value *P = Builder.CreatePtrToInt(CI.getOperand(0), PtrTy); 1947 return CastInst::CreateIntegerCast(P, Ty, /*isSigned=*/false); 1948 } 1949 1950 /// This input value (which is known to have vector type) is being zero extended 1951 /// or truncated to the specified vector type. Since the zext/trunc is done 1952 /// using an integer type, we have a (bitcast(cast(bitcast))) pattern, 1953 /// endianness will impact which end of the vector that is extended or 1954 /// truncated. 1955 /// 1956 /// A vector is always stored with index 0 at the lowest address, which 1957 /// corresponds to the most significant bits for a big endian stored integer and 1958 /// the least significant bits for little endian. A trunc/zext of an integer 1959 /// impacts the big end of the integer. Thus, we need to add/remove elements at 1960 /// the front of the vector for big endian targets, and the back of the vector 1961 /// for little endian targets. 1962 /// 1963 /// Try to replace it with a shuffle (and vector/vector bitcast) if possible. 1964 /// 1965 /// The source and destination vector types may have different element types. 1966 static Instruction *optimizeVectorResizeWithIntegerBitCasts(Value *InVal, 1967 VectorType *DestTy, 1968 InstCombiner &IC) { 1969 // We can only do this optimization if the output is a multiple of the input 1970 // element size, or the input is a multiple of the output element size. 1971 // Convert the input type to have the same element type as the output. 1972 VectorType *SrcTy = cast<VectorType>(InVal->getType()); 1973 1974 if (SrcTy->getElementType() != DestTy->getElementType()) { 1975 // The input types don't need to be identical, but for now they must be the 1976 // same size. There is no specific reason we couldn't handle things like 1977 // <4 x i16> -> <4 x i32> by bitcasting to <2 x i32> but haven't gotten 1978 // there yet. 1979 if (SrcTy->getElementType()->getPrimitiveSizeInBits() != 1980 DestTy->getElementType()->getPrimitiveSizeInBits()) 1981 return nullptr; 1982 1983 SrcTy = 1984 FixedVectorType::get(DestTy->getElementType(), SrcTy->getNumElements()); 1985 InVal = IC.Builder.CreateBitCast(InVal, SrcTy); 1986 } 1987 1988 bool IsBigEndian = IC.getDataLayout().isBigEndian(); 1989 unsigned SrcElts = SrcTy->getNumElements(); 1990 unsigned DestElts = DestTy->getNumElements(); 1991 1992 assert(SrcElts != DestElts && "Element counts should be different."); 1993 1994 // Now that the element types match, get the shuffle mask and RHS of the 1995 // shuffle to use, which depends on whether we're increasing or decreasing the 1996 // size of the input. 1997 SmallVector<int, 16> ShuffleMaskStorage; 1998 ArrayRef<int> ShuffleMask; 1999 Value *V2; 2000 2001 // Produce an identify shuffle mask for the src vector. 2002 ShuffleMaskStorage.resize(SrcElts); 2003 std::iota(ShuffleMaskStorage.begin(), ShuffleMaskStorage.end(), 0); 2004 2005 if (SrcElts > DestElts) { 2006 // If we're shrinking the number of elements (rewriting an integer 2007 // truncate), just shuffle in the elements corresponding to the least 2008 // significant bits from the input and use undef as the second shuffle 2009 // input. 2010 V2 = UndefValue::get(SrcTy); 2011 // Make sure the shuffle mask selects the "least significant bits" by 2012 // keeping elements from back of the src vector for big endian, and from the 2013 // front for little endian. 2014 ShuffleMask = ShuffleMaskStorage; 2015 if (IsBigEndian) 2016 ShuffleMask = ShuffleMask.take_back(DestElts); 2017 else 2018 ShuffleMask = ShuffleMask.take_front(DestElts); 2019 } else { 2020 // If we're increasing the number of elements (rewriting an integer zext), 2021 // shuffle in all of the elements from InVal. Fill the rest of the result 2022 // elements with zeros from a constant zero. 2023 V2 = Constant::getNullValue(SrcTy); 2024 // Use first elt from V2 when indicating zero in the shuffle mask. 2025 uint32_t NullElt = SrcElts; 2026 // Extend with null values in the "most significant bits" by adding elements 2027 // in front of the src vector for big endian, and at the back for little 2028 // endian. 2029 unsigned DeltaElts = DestElts - SrcElts; 2030 if (IsBigEndian) 2031 ShuffleMaskStorage.insert(ShuffleMaskStorage.begin(), DeltaElts, NullElt); 2032 else 2033 ShuffleMaskStorage.append(DeltaElts, NullElt); 2034 ShuffleMask = ShuffleMaskStorage; 2035 } 2036 2037 return new ShuffleVectorInst(InVal, V2, ShuffleMask); 2038 } 2039 2040 static bool isMultipleOfTypeSize(unsigned Value, Type *Ty) { 2041 return Value % Ty->getPrimitiveSizeInBits() == 0; 2042 } 2043 2044 static unsigned getTypeSizeIndex(unsigned Value, Type *Ty) { 2045 return Value / Ty->getPrimitiveSizeInBits(); 2046 } 2047 2048 /// V is a value which is inserted into a vector of VecEltTy. 2049 /// Look through the value to see if we can decompose it into 2050 /// insertions into the vector. See the example in the comment for 2051 /// OptimizeIntegerToVectorInsertions for the pattern this handles. 2052 /// The type of V is always a non-zero multiple of VecEltTy's size. 2053 /// Shift is the number of bits between the lsb of V and the lsb of 2054 /// the vector. 2055 /// 2056 /// This returns false if the pattern can't be matched or true if it can, 2057 /// filling in Elements with the elements found here. 2058 static bool collectInsertionElements(Value *V, unsigned Shift, 2059 SmallVectorImpl<Value *> &Elements, 2060 Type *VecEltTy, bool isBigEndian) { 2061 assert(isMultipleOfTypeSize(Shift, VecEltTy) && 2062 "Shift should be a multiple of the element type size"); 2063 2064 // Undef values never contribute useful bits to the result. 2065 if (isa<UndefValue>(V)) return true; 2066 2067 // If we got down to a value of the right type, we win, try inserting into the 2068 // right element. 2069 if (V->getType() == VecEltTy) { 2070 // Inserting null doesn't actually insert any elements. 2071 if (Constant *C = dyn_cast<Constant>(V)) 2072 if (C->isNullValue()) 2073 return true; 2074 2075 unsigned ElementIndex = getTypeSizeIndex(Shift, VecEltTy); 2076 if (isBigEndian) 2077 ElementIndex = Elements.size() - ElementIndex - 1; 2078 2079 // Fail if multiple elements are inserted into this slot. 2080 if (Elements[ElementIndex]) 2081 return false; 2082 2083 Elements[ElementIndex] = V; 2084 return true; 2085 } 2086 2087 if (Constant *C = dyn_cast<Constant>(V)) { 2088 // Figure out the # elements this provides, and bitcast it or slice it up 2089 // as required. 2090 unsigned NumElts = getTypeSizeIndex(C->getType()->getPrimitiveSizeInBits(), 2091 VecEltTy); 2092 // If the constant is the size of a vector element, we just need to bitcast 2093 // it to the right type so it gets properly inserted. 2094 if (NumElts == 1) 2095 return collectInsertionElements(ConstantExpr::getBitCast(C, VecEltTy), 2096 Shift, Elements, VecEltTy, isBigEndian); 2097 2098 // Okay, this is a constant that covers multiple elements. Slice it up into 2099 // pieces and insert each element-sized piece into the vector. 2100 if (!isa<IntegerType>(C->getType())) 2101 C = ConstantExpr::getBitCast(C, IntegerType::get(V->getContext(), 2102 C->getType()->getPrimitiveSizeInBits())); 2103 unsigned ElementSize = VecEltTy->getPrimitiveSizeInBits(); 2104 Type *ElementIntTy = IntegerType::get(C->getContext(), ElementSize); 2105 2106 for (unsigned i = 0; i != NumElts; ++i) { 2107 unsigned ShiftI = Shift+i*ElementSize; 2108 Constant *Piece = ConstantExpr::getLShr(C, ConstantInt::get(C->getType(), 2109 ShiftI)); 2110 Piece = ConstantExpr::getTrunc(Piece, ElementIntTy); 2111 if (!collectInsertionElements(Piece, ShiftI, Elements, VecEltTy, 2112 isBigEndian)) 2113 return false; 2114 } 2115 return true; 2116 } 2117 2118 if (!V->hasOneUse()) return false; 2119 2120 Instruction *I = dyn_cast<Instruction>(V); 2121 if (!I) return false; 2122 switch (I->getOpcode()) { 2123 default: return false; // Unhandled case. 2124 case Instruction::BitCast: 2125 return collectInsertionElements(I->getOperand(0), Shift, Elements, VecEltTy, 2126 isBigEndian); 2127 case Instruction::ZExt: 2128 if (!isMultipleOfTypeSize( 2129 I->getOperand(0)->getType()->getPrimitiveSizeInBits(), 2130 VecEltTy)) 2131 return false; 2132 return collectInsertionElements(I->getOperand(0), Shift, Elements, VecEltTy, 2133 isBigEndian); 2134 case Instruction::Or: 2135 return collectInsertionElements(I->getOperand(0), Shift, Elements, VecEltTy, 2136 isBigEndian) && 2137 collectInsertionElements(I->getOperand(1), Shift, Elements, VecEltTy, 2138 isBigEndian); 2139 case Instruction::Shl: { 2140 // Must be shifting by a constant that is a multiple of the element size. 2141 ConstantInt *CI = dyn_cast<ConstantInt>(I->getOperand(1)); 2142 if (!CI) return false; 2143 Shift += CI->getZExtValue(); 2144 if (!isMultipleOfTypeSize(Shift, VecEltTy)) return false; 2145 return collectInsertionElements(I->getOperand(0), Shift, Elements, VecEltTy, 2146 isBigEndian); 2147 } 2148 2149 } 2150 } 2151 2152 2153 /// If the input is an 'or' instruction, we may be doing shifts and ors to 2154 /// assemble the elements of the vector manually. 2155 /// Try to rip the code out and replace it with insertelements. This is to 2156 /// optimize code like this: 2157 /// 2158 /// %tmp37 = bitcast float %inc to i32 2159 /// %tmp38 = zext i32 %tmp37 to i64 2160 /// %tmp31 = bitcast float %inc5 to i32 2161 /// %tmp32 = zext i32 %tmp31 to i64 2162 /// %tmp33 = shl i64 %tmp32, 32 2163 /// %ins35 = or i64 %tmp33, %tmp38 2164 /// %tmp43 = bitcast i64 %ins35 to <2 x float> 2165 /// 2166 /// Into two insertelements that do "buildvector{%inc, %inc5}". 2167 static Value *optimizeIntegerToVectorInsertions(BitCastInst &CI, 2168 InstCombiner &IC) { 2169 VectorType *DestVecTy = cast<VectorType>(CI.getType()); 2170 Value *IntInput = CI.getOperand(0); 2171 2172 SmallVector<Value*, 8> Elements(DestVecTy->getNumElements()); 2173 if (!collectInsertionElements(IntInput, 0, Elements, 2174 DestVecTy->getElementType(), 2175 IC.getDataLayout().isBigEndian())) 2176 return nullptr; 2177 2178 // If we succeeded, we know that all of the element are specified by Elements 2179 // or are zero if Elements has a null entry. Recast this as a set of 2180 // insertions. 2181 Value *Result = Constant::getNullValue(CI.getType()); 2182 for (unsigned i = 0, e = Elements.size(); i != e; ++i) { 2183 if (!Elements[i]) continue; // Unset element. 2184 2185 Result = IC.Builder.CreateInsertElement(Result, Elements[i], 2186 IC.Builder.getInt32(i)); 2187 } 2188 2189 return Result; 2190 } 2191 2192 /// Canonicalize scalar bitcasts of extracted elements into a bitcast of the 2193 /// vector followed by extract element. The backend tends to handle bitcasts of 2194 /// vectors better than bitcasts of scalars because vector registers are 2195 /// usually not type-specific like scalar integer or scalar floating-point. 2196 static Instruction *canonicalizeBitCastExtElt(BitCastInst &BitCast, 2197 InstCombiner &IC) { 2198 // TODO: Create and use a pattern matcher for ExtractElementInst. 2199 auto *ExtElt = dyn_cast<ExtractElementInst>(BitCast.getOperand(0)); 2200 if (!ExtElt || !ExtElt->hasOneUse()) 2201 return nullptr; 2202 2203 // The bitcast must be to a vectorizable type, otherwise we can't make a new 2204 // type to extract from. 2205 Type *DestType = BitCast.getType(); 2206 if (!VectorType::isValidElementType(DestType)) 2207 return nullptr; 2208 2209 unsigned NumElts = ExtElt->getVectorOperandType()->getNumElements(); 2210 auto *NewVecType = FixedVectorType::get(DestType, NumElts); 2211 auto *NewBC = IC.Builder.CreateBitCast(ExtElt->getVectorOperand(), 2212 NewVecType, "bc"); 2213 return ExtractElementInst::Create(NewBC, ExtElt->getIndexOperand()); 2214 } 2215 2216 /// Change the type of a bitwise logic operation if we can eliminate a bitcast. 2217 static Instruction *foldBitCastBitwiseLogic(BitCastInst &BitCast, 2218 InstCombiner::BuilderTy &Builder) { 2219 Type *DestTy = BitCast.getType(); 2220 BinaryOperator *BO; 2221 if (!DestTy->isIntOrIntVectorTy() || 2222 !match(BitCast.getOperand(0), m_OneUse(m_BinOp(BO))) || 2223 !BO->isBitwiseLogicOp()) 2224 return nullptr; 2225 2226 // FIXME: This transform is restricted to vector types to avoid backend 2227 // problems caused by creating potentially illegal operations. If a fix-up is 2228 // added to handle that situation, we can remove this check. 2229 if (!DestTy->isVectorTy() || !BO->getType()->isVectorTy()) 2230 return nullptr; 2231 2232 Value *X; 2233 if (match(BO->getOperand(0), m_OneUse(m_BitCast(m_Value(X)))) && 2234 X->getType() == DestTy && !isa<Constant>(X)) { 2235 // bitcast(logic(bitcast(X), Y)) --> logic'(X, bitcast(Y)) 2236 Value *CastedOp1 = Builder.CreateBitCast(BO->getOperand(1), DestTy); 2237 return BinaryOperator::Create(BO->getOpcode(), X, CastedOp1); 2238 } 2239 2240 if (match(BO->getOperand(1), m_OneUse(m_BitCast(m_Value(X)))) && 2241 X->getType() == DestTy && !isa<Constant>(X)) { 2242 // bitcast(logic(Y, bitcast(X))) --> logic'(bitcast(Y), X) 2243 Value *CastedOp0 = Builder.CreateBitCast(BO->getOperand(0), DestTy); 2244 return BinaryOperator::Create(BO->getOpcode(), CastedOp0, X); 2245 } 2246 2247 // Canonicalize vector bitcasts to come before vector bitwise logic with a 2248 // constant. This eases recognition of special constants for later ops. 2249 // Example: 2250 // icmp u/s (a ^ signmask), (b ^ signmask) --> icmp s/u a, b 2251 Constant *C; 2252 if (match(BO->getOperand(1), m_Constant(C))) { 2253 // bitcast (logic X, C) --> logic (bitcast X, C') 2254 Value *CastedOp0 = Builder.CreateBitCast(BO->getOperand(0), DestTy); 2255 Value *CastedC = Builder.CreateBitCast(C, DestTy); 2256 return BinaryOperator::Create(BO->getOpcode(), CastedOp0, CastedC); 2257 } 2258 2259 return nullptr; 2260 } 2261 2262 /// Change the type of a select if we can eliminate a bitcast. 2263 static Instruction *foldBitCastSelect(BitCastInst &BitCast, 2264 InstCombiner::BuilderTy &Builder) { 2265 Value *Cond, *TVal, *FVal; 2266 if (!match(BitCast.getOperand(0), 2267 m_OneUse(m_Select(m_Value(Cond), m_Value(TVal), m_Value(FVal))))) 2268 return nullptr; 2269 2270 // A vector select must maintain the same number of elements in its operands. 2271 Type *CondTy = Cond->getType(); 2272 Type *DestTy = BitCast.getType(); 2273 if (auto *CondVTy = dyn_cast<VectorType>(CondTy)) { 2274 if (!DestTy->isVectorTy()) 2275 return nullptr; 2276 if (cast<VectorType>(DestTy)->getNumElements() != CondVTy->getNumElements()) 2277 return nullptr; 2278 } 2279 2280 // FIXME: This transform is restricted from changing the select between 2281 // scalars and vectors to avoid backend problems caused by creating 2282 // potentially illegal operations. If a fix-up is added to handle that 2283 // situation, we can remove this check. 2284 if (DestTy->isVectorTy() != TVal->getType()->isVectorTy()) 2285 return nullptr; 2286 2287 auto *Sel = cast<Instruction>(BitCast.getOperand(0)); 2288 Value *X; 2289 if (match(TVal, m_OneUse(m_BitCast(m_Value(X)))) && X->getType() == DestTy && 2290 !isa<Constant>(X)) { 2291 // bitcast(select(Cond, bitcast(X), Y)) --> select'(Cond, X, bitcast(Y)) 2292 Value *CastedVal = Builder.CreateBitCast(FVal, DestTy); 2293 return SelectInst::Create(Cond, X, CastedVal, "", nullptr, Sel); 2294 } 2295 2296 if (match(FVal, m_OneUse(m_BitCast(m_Value(X)))) && X->getType() == DestTy && 2297 !isa<Constant>(X)) { 2298 // bitcast(select(Cond, Y, bitcast(X))) --> select'(Cond, bitcast(Y), X) 2299 Value *CastedVal = Builder.CreateBitCast(TVal, DestTy); 2300 return SelectInst::Create(Cond, CastedVal, X, "", nullptr, Sel); 2301 } 2302 2303 return nullptr; 2304 } 2305 2306 /// Check if all users of CI are StoreInsts. 2307 static bool hasStoreUsersOnly(CastInst &CI) { 2308 for (User *U : CI.users()) { 2309 if (!isa<StoreInst>(U)) 2310 return false; 2311 } 2312 return true; 2313 } 2314 2315 /// This function handles following case 2316 /// 2317 /// A -> B cast 2318 /// PHI 2319 /// B -> A cast 2320 /// 2321 /// All the related PHI nodes can be replaced by new PHI nodes with type A. 2322 /// The uses of \p CI can be changed to the new PHI node corresponding to \p PN. 2323 Instruction *InstCombiner::optimizeBitCastFromPhi(CastInst &CI, PHINode *PN) { 2324 // BitCast used by Store can be handled in InstCombineLoadStoreAlloca.cpp. 2325 if (hasStoreUsersOnly(CI)) 2326 return nullptr; 2327 2328 Value *Src = CI.getOperand(0); 2329 Type *SrcTy = Src->getType(); // Type B 2330 Type *DestTy = CI.getType(); // Type A 2331 2332 SmallVector<PHINode *, 4> PhiWorklist; 2333 SmallSetVector<PHINode *, 4> OldPhiNodes; 2334 2335 // Find all of the A->B casts and PHI nodes. 2336 // We need to inspect all related PHI nodes, but PHIs can be cyclic, so 2337 // OldPhiNodes is used to track all known PHI nodes, before adding a new 2338 // PHI to PhiWorklist, it is checked against and added to OldPhiNodes first. 2339 PhiWorklist.push_back(PN); 2340 OldPhiNodes.insert(PN); 2341 while (!PhiWorklist.empty()) { 2342 auto *OldPN = PhiWorklist.pop_back_val(); 2343 for (Value *IncValue : OldPN->incoming_values()) { 2344 if (isa<Constant>(IncValue)) 2345 continue; 2346 2347 if (auto *LI = dyn_cast<LoadInst>(IncValue)) { 2348 // If there is a sequence of one or more load instructions, each loaded 2349 // value is used as address of later load instruction, bitcast is 2350 // necessary to change the value type, don't optimize it. For 2351 // simplicity we give up if the load address comes from another load. 2352 Value *Addr = LI->getOperand(0); 2353 if (Addr == &CI || isa<LoadInst>(Addr)) 2354 return nullptr; 2355 if (LI->hasOneUse() && LI->isSimple()) 2356 continue; 2357 // If a LoadInst has more than one use, changing the type of loaded 2358 // value may create another bitcast. 2359 return nullptr; 2360 } 2361 2362 if (auto *PNode = dyn_cast<PHINode>(IncValue)) { 2363 if (OldPhiNodes.insert(PNode)) 2364 PhiWorklist.push_back(PNode); 2365 continue; 2366 } 2367 2368 auto *BCI = dyn_cast<BitCastInst>(IncValue); 2369 // We can't handle other instructions. 2370 if (!BCI) 2371 return nullptr; 2372 2373 // Verify it's a A->B cast. 2374 Type *TyA = BCI->getOperand(0)->getType(); 2375 Type *TyB = BCI->getType(); 2376 if (TyA != DestTy || TyB != SrcTy) 2377 return nullptr; 2378 } 2379 } 2380 2381 // Check that each user of each old PHI node is something that we can 2382 // rewrite, so that all of the old PHI nodes can be cleaned up afterwards. 2383 for (auto *OldPN : OldPhiNodes) { 2384 for (User *V : OldPN->users()) { 2385 if (auto *SI = dyn_cast<StoreInst>(V)) { 2386 if (!SI->isSimple() || SI->getOperand(0) != OldPN) 2387 return nullptr; 2388 } else if (auto *BCI = dyn_cast<BitCastInst>(V)) { 2389 // Verify it's a B->A cast. 2390 Type *TyB = BCI->getOperand(0)->getType(); 2391 Type *TyA = BCI->getType(); 2392 if (TyA != DestTy || TyB != SrcTy) 2393 return nullptr; 2394 } else if (auto *PHI = dyn_cast<PHINode>(V)) { 2395 // As long as the user is another old PHI node, then even if we don't 2396 // rewrite it, the PHI web we're considering won't have any users 2397 // outside itself, so it'll be dead. 2398 if (OldPhiNodes.count(PHI) == 0) 2399 return nullptr; 2400 } else { 2401 return nullptr; 2402 } 2403 } 2404 } 2405 2406 // For each old PHI node, create a corresponding new PHI node with a type A. 2407 SmallDenseMap<PHINode *, PHINode *> NewPNodes; 2408 for (auto *OldPN : OldPhiNodes) { 2409 Builder.SetInsertPoint(OldPN); 2410 PHINode *NewPN = Builder.CreatePHI(DestTy, OldPN->getNumOperands()); 2411 NewPNodes[OldPN] = NewPN; 2412 } 2413 2414 // Fill in the operands of new PHI nodes. 2415 for (auto *OldPN : OldPhiNodes) { 2416 PHINode *NewPN = NewPNodes[OldPN]; 2417 for (unsigned j = 0, e = OldPN->getNumOperands(); j != e; ++j) { 2418 Value *V = OldPN->getOperand(j); 2419 Value *NewV = nullptr; 2420 if (auto *C = dyn_cast<Constant>(V)) { 2421 NewV = ConstantExpr::getBitCast(C, DestTy); 2422 } else if (auto *LI = dyn_cast<LoadInst>(V)) { 2423 // Explicitly perform load combine to make sure no opposing transform 2424 // can remove the bitcast in the meantime and trigger an infinite loop. 2425 Builder.SetInsertPoint(LI); 2426 NewV = combineLoadToNewType(*LI, DestTy); 2427 // Remove the old load and its use in the old phi, which itself becomes 2428 // dead once the whole transform finishes. 2429 replaceInstUsesWith(*LI, UndefValue::get(LI->getType())); 2430 eraseInstFromFunction(*LI); 2431 } else if (auto *BCI = dyn_cast<BitCastInst>(V)) { 2432 NewV = BCI->getOperand(0); 2433 } else if (auto *PrevPN = dyn_cast<PHINode>(V)) { 2434 NewV = NewPNodes[PrevPN]; 2435 } 2436 assert(NewV); 2437 NewPN->addIncoming(NewV, OldPN->getIncomingBlock(j)); 2438 } 2439 } 2440 2441 // Traverse all accumulated PHI nodes and process its users, 2442 // which are Stores and BitcCasts. Without this processing 2443 // NewPHI nodes could be replicated and could lead to extra 2444 // moves generated after DeSSA. 2445 // If there is a store with type B, change it to type A. 2446 2447 2448 // Replace users of BitCast B->A with NewPHI. These will help 2449 // later to get rid off a closure formed by OldPHI nodes. 2450 Instruction *RetVal = nullptr; 2451 for (auto *OldPN : OldPhiNodes) { 2452 PHINode *NewPN = NewPNodes[OldPN]; 2453 for (auto It = OldPN->user_begin(), End = OldPN->user_end(); It != End; ) { 2454 User *V = *It; 2455 // We may remove this user, advance to avoid iterator invalidation. 2456 ++It; 2457 if (auto *SI = dyn_cast<StoreInst>(V)) { 2458 assert(SI->isSimple() && SI->getOperand(0) == OldPN); 2459 Builder.SetInsertPoint(SI); 2460 auto *NewBC = 2461 cast<BitCastInst>(Builder.CreateBitCast(NewPN, SrcTy)); 2462 SI->setOperand(0, NewBC); 2463 Worklist.push(SI); 2464 assert(hasStoreUsersOnly(*NewBC)); 2465 } 2466 else if (auto *BCI = dyn_cast<BitCastInst>(V)) { 2467 Type *TyB = BCI->getOperand(0)->getType(); 2468 Type *TyA = BCI->getType(); 2469 assert(TyA == DestTy && TyB == SrcTy); 2470 (void) TyA; 2471 (void) TyB; 2472 Instruction *I = replaceInstUsesWith(*BCI, NewPN); 2473 if (BCI == &CI) 2474 RetVal = I; 2475 } else if (auto *PHI = dyn_cast<PHINode>(V)) { 2476 assert(OldPhiNodes.count(PHI) > 0); 2477 (void) PHI; 2478 } else { 2479 llvm_unreachable("all uses should be handled"); 2480 } 2481 } 2482 } 2483 2484 return RetVal; 2485 } 2486 2487 Instruction *InstCombiner::visitBitCast(BitCastInst &CI) { 2488 // If the operands are integer typed then apply the integer transforms, 2489 // otherwise just apply the common ones. 2490 Value *Src = CI.getOperand(0); 2491 Type *SrcTy = Src->getType(); 2492 Type *DestTy = CI.getType(); 2493 2494 // Get rid of casts from one type to the same type. These are useless and can 2495 // be replaced by the operand. 2496 if (DestTy == Src->getType()) 2497 return replaceInstUsesWith(CI, Src); 2498 2499 if (isa<PointerType>(SrcTy) && isa<PointerType>(DestTy)) { 2500 PointerType *SrcPTy = cast<PointerType>(SrcTy); 2501 PointerType *DstPTy = cast<PointerType>(DestTy); 2502 Type *DstElTy = DstPTy->getElementType(); 2503 Type *SrcElTy = SrcPTy->getElementType(); 2504 2505 // Casting pointers between the same type, but with different address spaces 2506 // is an addrspace cast rather than a bitcast. 2507 if ((DstElTy == SrcElTy) && 2508 (DstPTy->getAddressSpace() != SrcPTy->getAddressSpace())) 2509 return new AddrSpaceCastInst(Src, DestTy); 2510 2511 // If we are casting a alloca to a pointer to a type of the same 2512 // size, rewrite the allocation instruction to allocate the "right" type. 2513 // There is no need to modify malloc calls because it is their bitcast that 2514 // needs to be cleaned up. 2515 if (AllocaInst *AI = dyn_cast<AllocaInst>(Src)) 2516 if (Instruction *V = PromoteCastOfAllocation(CI, *AI)) 2517 return V; 2518 2519 // When the type pointed to is not sized the cast cannot be 2520 // turned into a gep. 2521 Type *PointeeType = 2522 cast<PointerType>(Src->getType()->getScalarType())->getElementType(); 2523 if (!PointeeType->isSized()) 2524 return nullptr; 2525 2526 // If the source and destination are pointers, and this cast is equivalent 2527 // to a getelementptr X, 0, 0, 0... turn it into the appropriate gep. 2528 // This can enhance SROA and other transforms that want type-safe pointers. 2529 unsigned NumZeros = 0; 2530 while (SrcElTy && SrcElTy != DstElTy) { 2531 SrcElTy = GetElementPtrInst::getTypeAtIndex(SrcElTy, (uint64_t)0); 2532 ++NumZeros; 2533 } 2534 2535 // If we found a path from the src to dest, create the getelementptr now. 2536 if (SrcElTy == DstElTy) { 2537 SmallVector<Value *, 8> Idxs(NumZeros + 1, Builder.getInt32(0)); 2538 GetElementPtrInst *GEP = 2539 GetElementPtrInst::Create(SrcPTy->getElementType(), Src, Idxs); 2540 2541 // If the source pointer is dereferenceable, then assume it points to an 2542 // allocated object and apply "inbounds" to the GEP. 2543 bool CanBeNull; 2544 if (Src->getPointerDereferenceableBytes(DL, CanBeNull)) { 2545 // In a non-default address space (not 0), a null pointer can not be 2546 // assumed inbounds, so ignore that case (dereferenceable_or_null). 2547 // The reason is that 'null' is not treated differently in these address 2548 // spaces, and we consequently ignore the 'gep inbounds' special case 2549 // for 'null' which allows 'inbounds' on 'null' if the indices are 2550 // zeros. 2551 if (SrcPTy->getAddressSpace() == 0 || !CanBeNull) 2552 GEP->setIsInBounds(); 2553 } 2554 return GEP; 2555 } 2556 } 2557 2558 if (FixedVectorType *DestVTy = dyn_cast<FixedVectorType>(DestTy)) { 2559 // Beware: messing with this target-specific oddity may cause trouble. 2560 if (DestVTy->getNumElements() == 1 && SrcTy->isX86_MMXTy()) { 2561 Value *Elem = Builder.CreateBitCast(Src, DestVTy->getElementType()); 2562 return InsertElementInst::Create(UndefValue::get(DestTy), Elem, 2563 Constant::getNullValue(Type::getInt32Ty(CI.getContext()))); 2564 } 2565 2566 if (isa<IntegerType>(SrcTy)) { 2567 // If this is a cast from an integer to vector, check to see if the input 2568 // is a trunc or zext of a bitcast from vector. If so, we can replace all 2569 // the casts with a shuffle and (potentially) a bitcast. 2570 if (isa<TruncInst>(Src) || isa<ZExtInst>(Src)) { 2571 CastInst *SrcCast = cast<CastInst>(Src); 2572 if (BitCastInst *BCIn = dyn_cast<BitCastInst>(SrcCast->getOperand(0))) 2573 if (isa<VectorType>(BCIn->getOperand(0)->getType())) 2574 if (Instruction *I = optimizeVectorResizeWithIntegerBitCasts( 2575 BCIn->getOperand(0), cast<VectorType>(DestTy), *this)) 2576 return I; 2577 } 2578 2579 // If the input is an 'or' instruction, we may be doing shifts and ors to 2580 // assemble the elements of the vector manually. Try to rip the code out 2581 // and replace it with insertelements. 2582 if (Value *V = optimizeIntegerToVectorInsertions(CI, *this)) 2583 return replaceInstUsesWith(CI, V); 2584 } 2585 } 2586 2587 if (FixedVectorType *SrcVTy = dyn_cast<FixedVectorType>(SrcTy)) { 2588 if (SrcVTy->getNumElements() == 1) { 2589 // If our destination is not a vector, then make this a straight 2590 // scalar-scalar cast. 2591 if (!DestTy->isVectorTy()) { 2592 Value *Elem = 2593 Builder.CreateExtractElement(Src, 2594 Constant::getNullValue(Type::getInt32Ty(CI.getContext()))); 2595 return CastInst::Create(Instruction::BitCast, Elem, DestTy); 2596 } 2597 2598 // Otherwise, see if our source is an insert. If so, then use the scalar 2599 // component directly: 2600 // bitcast (inselt <1 x elt> V, X, 0) to <n x m> --> bitcast X to <n x m> 2601 if (auto *InsElt = dyn_cast<InsertElementInst>(Src)) 2602 return new BitCastInst(InsElt->getOperand(1), DestTy); 2603 } 2604 } 2605 2606 if (auto *Shuf = dyn_cast<ShuffleVectorInst>(Src)) { 2607 // Okay, we have (bitcast (shuffle ..)). Check to see if this is 2608 // a bitcast to a vector with the same # elts. 2609 Value *ShufOp0 = Shuf->getOperand(0); 2610 Value *ShufOp1 = Shuf->getOperand(1); 2611 unsigned NumShufElts = Shuf->getType()->getNumElements(); 2612 unsigned NumSrcVecElts = 2613 cast<VectorType>(ShufOp0->getType())->getNumElements(); 2614 if (Shuf->hasOneUse() && DestTy->isVectorTy() && 2615 cast<VectorType>(DestTy)->getNumElements() == NumShufElts && 2616 NumShufElts == NumSrcVecElts) { 2617 BitCastInst *Tmp; 2618 // If either of the operands is a cast from CI.getType(), then 2619 // evaluating the shuffle in the casted destination's type will allow 2620 // us to eliminate at least one cast. 2621 if (((Tmp = dyn_cast<BitCastInst>(ShufOp0)) && 2622 Tmp->getOperand(0)->getType() == DestTy) || 2623 ((Tmp = dyn_cast<BitCastInst>(ShufOp1)) && 2624 Tmp->getOperand(0)->getType() == DestTy)) { 2625 Value *LHS = Builder.CreateBitCast(ShufOp0, DestTy); 2626 Value *RHS = Builder.CreateBitCast(ShufOp1, DestTy); 2627 // Return a new shuffle vector. Use the same element ID's, as we 2628 // know the vector types match #elts. 2629 return new ShuffleVectorInst(LHS, RHS, Shuf->getShuffleMask()); 2630 } 2631 } 2632 2633 // A bitcasted-to-scalar and byte-reversing shuffle is better recognized as 2634 // a byte-swap: 2635 // bitcast <N x i8> (shuf X, undef, <N, N-1,...0>) --> bswap (bitcast X) 2636 // TODO: We should match the related pattern for bitreverse. 2637 if (DestTy->isIntegerTy() && 2638 DL.isLegalInteger(DestTy->getScalarSizeInBits()) && 2639 SrcTy->getScalarSizeInBits() == 8 && NumShufElts % 2 == 0 && 2640 Shuf->hasOneUse() && Shuf->isReverse()) { 2641 assert(ShufOp0->getType() == SrcTy && "Unexpected shuffle mask"); 2642 assert(isa<UndefValue>(ShufOp1) && "Unexpected shuffle op"); 2643 Function *Bswap = 2644 Intrinsic::getDeclaration(CI.getModule(), Intrinsic::bswap, DestTy); 2645 Value *ScalarX = Builder.CreateBitCast(ShufOp0, DestTy); 2646 return IntrinsicInst::Create(Bswap, { ScalarX }); 2647 } 2648 } 2649 2650 // Handle the A->B->A cast, and there is an intervening PHI node. 2651 if (PHINode *PN = dyn_cast<PHINode>(Src)) 2652 if (Instruction *I = optimizeBitCastFromPhi(CI, PN)) 2653 return I; 2654 2655 if (Instruction *I = canonicalizeBitCastExtElt(CI, *this)) 2656 return I; 2657 2658 if (Instruction *I = foldBitCastBitwiseLogic(CI, Builder)) 2659 return I; 2660 2661 if (Instruction *I = foldBitCastSelect(CI, Builder)) 2662 return I; 2663 2664 if (SrcTy->isPointerTy()) 2665 return commonPointerCastTransforms(CI); 2666 return commonCastTransforms(CI); 2667 } 2668 2669 Instruction *InstCombiner::visitAddrSpaceCast(AddrSpaceCastInst &CI) { 2670 // If the destination pointer element type is not the same as the source's 2671 // first do a bitcast to the destination type, and then the addrspacecast. 2672 // This allows the cast to be exposed to other transforms. 2673 Value *Src = CI.getOperand(0); 2674 PointerType *SrcTy = cast<PointerType>(Src->getType()->getScalarType()); 2675 PointerType *DestTy = cast<PointerType>(CI.getType()->getScalarType()); 2676 2677 Type *DestElemTy = DestTy->getElementType(); 2678 if (SrcTy->getElementType() != DestElemTy) { 2679 Type *MidTy = PointerType::get(DestElemTy, SrcTy->getAddressSpace()); 2680 if (VectorType *VT = dyn_cast<VectorType>(CI.getType())) { 2681 // Handle vectors of pointers. 2682 // FIXME: what should happen for scalable vectors? 2683 MidTy = FixedVectorType::get(MidTy, VT->getNumElements()); 2684 } 2685 2686 Value *NewBitCast = Builder.CreateBitCast(Src, MidTy); 2687 return new AddrSpaceCastInst(NewBitCast, CI.getType()); 2688 } 2689 2690 return commonPointerCastTransforms(CI); 2691 } 2692