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