1 //===- InstructionCombining.cpp - Combine multiple instructions -----------===// 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 // InstructionCombining - Combine instructions to form fewer, simple 10 // instructions. This pass does not modify the CFG. This pass is where 11 // algebraic simplification happens. 12 // 13 // This pass combines things like: 14 // %Y = add i32 %X, 1 15 // %Z = add i32 %Y, 1 16 // into: 17 // %Z = add i32 %X, 2 18 // 19 // This is a simple worklist driven algorithm. 20 // 21 // This pass guarantees that the following canonicalizations are performed on 22 // the program: 23 // 1. If a binary operator has a constant operand, it is moved to the RHS 24 // 2. Bitwise operators with constant operands are always grouped so that 25 // shifts are performed first, then or's, then and's, then xor's. 26 // 3. Compare instructions are converted from <,>,<=,>= to ==,!= if possible 27 // 4. All cmp instructions on boolean values are replaced with logical ops 28 // 5. add X, X is represented as (X*2) => (X << 1) 29 // 6. Multiplies with a power-of-two constant argument are transformed into 30 // shifts. 31 // ... etc. 32 // 33 //===----------------------------------------------------------------------===// 34 35 #include "InstCombineInternal.h" 36 #include "llvm-c/Initialization.h" 37 #include "llvm-c/Transforms/InstCombine.h" 38 #include "llvm/ADT/APInt.h" 39 #include "llvm/ADT/ArrayRef.h" 40 #include "llvm/ADT/DenseMap.h" 41 #include "llvm/ADT/None.h" 42 #include "llvm/ADT/SmallPtrSet.h" 43 #include "llvm/ADT/SmallVector.h" 44 #include "llvm/ADT/Statistic.h" 45 #include "llvm/ADT/TinyPtrVector.h" 46 #include "llvm/Analysis/AliasAnalysis.h" 47 #include "llvm/Analysis/AssumptionCache.h" 48 #include "llvm/Analysis/BasicAliasAnalysis.h" 49 #include "llvm/Analysis/BlockFrequencyInfo.h" 50 #include "llvm/Analysis/CFG.h" 51 #include "llvm/Analysis/ConstantFolding.h" 52 #include "llvm/Analysis/EHPersonalities.h" 53 #include "llvm/Analysis/GlobalsModRef.h" 54 #include "llvm/Analysis/InstructionSimplify.h" 55 #include "llvm/Analysis/LazyBlockFrequencyInfo.h" 56 #include "llvm/Analysis/LoopInfo.h" 57 #include "llvm/Analysis/MemoryBuiltins.h" 58 #include "llvm/Analysis/OptimizationRemarkEmitter.h" 59 #include "llvm/Analysis/ProfileSummaryInfo.h" 60 #include "llvm/Analysis/TargetFolder.h" 61 #include "llvm/Analysis/TargetLibraryInfo.h" 62 #include "llvm/Analysis/TargetTransformInfo.h" 63 #include "llvm/Analysis/ValueTracking.h" 64 #include "llvm/Analysis/VectorUtils.h" 65 #include "llvm/IR/BasicBlock.h" 66 #include "llvm/IR/CFG.h" 67 #include "llvm/IR/Constant.h" 68 #include "llvm/IR/Constants.h" 69 #include "llvm/IR/DIBuilder.h" 70 #include "llvm/IR/DataLayout.h" 71 #include "llvm/IR/DerivedTypes.h" 72 #include "llvm/IR/Dominators.h" 73 #include "llvm/IR/Function.h" 74 #include "llvm/IR/GetElementPtrTypeIterator.h" 75 #include "llvm/IR/IRBuilder.h" 76 #include "llvm/IR/InstrTypes.h" 77 #include "llvm/IR/Instruction.h" 78 #include "llvm/IR/Instructions.h" 79 #include "llvm/IR/IntrinsicInst.h" 80 #include "llvm/IR/Intrinsics.h" 81 #include "llvm/IR/LegacyPassManager.h" 82 #include "llvm/IR/Metadata.h" 83 #include "llvm/IR/Operator.h" 84 #include "llvm/IR/PassManager.h" 85 #include "llvm/IR/PatternMatch.h" 86 #include "llvm/IR/Type.h" 87 #include "llvm/IR/Use.h" 88 #include "llvm/IR/User.h" 89 #include "llvm/IR/Value.h" 90 #include "llvm/IR/ValueHandle.h" 91 #include "llvm/InitializePasses.h" 92 #include "llvm/Pass.h" 93 #include "llvm/Support/CBindingWrapping.h" 94 #include "llvm/Support/Casting.h" 95 #include "llvm/Support/CommandLine.h" 96 #include "llvm/Support/Compiler.h" 97 #include "llvm/Support/Debug.h" 98 #include "llvm/Support/DebugCounter.h" 99 #include "llvm/Support/ErrorHandling.h" 100 #include "llvm/Support/KnownBits.h" 101 #include "llvm/Support/raw_ostream.h" 102 #include "llvm/Transforms/InstCombine/InstCombine.h" 103 #include "llvm/Transforms/InstCombine/InstCombineWorklist.h" 104 #include "llvm/Transforms/Utils/Local.h" 105 #include <algorithm> 106 #include <cassert> 107 #include <cstdint> 108 #include <memory> 109 #include <string> 110 #include <utility> 111 112 using namespace llvm; 113 using namespace llvm::PatternMatch; 114 115 #define DEBUG_TYPE "instcombine" 116 117 STATISTIC(NumWorklistIterations, 118 "Number of instruction combining iterations performed"); 119 120 STATISTIC(NumCombined , "Number of insts combined"); 121 STATISTIC(NumConstProp, "Number of constant folds"); 122 STATISTIC(NumDeadInst , "Number of dead inst eliminated"); 123 STATISTIC(NumSunkInst , "Number of instructions sunk"); 124 STATISTIC(NumExpand, "Number of expansions"); 125 STATISTIC(NumFactor , "Number of factorizations"); 126 STATISTIC(NumReassoc , "Number of reassociations"); 127 DEBUG_COUNTER(VisitCounter, "instcombine-visit", 128 "Controls which instructions are visited"); 129 130 // FIXME: these limits eventually should be as low as 2. 131 static constexpr unsigned InstCombineDefaultMaxIterations = 1000; 132 #ifndef NDEBUG 133 static constexpr unsigned InstCombineDefaultInfiniteLoopThreshold = 100; 134 #else 135 static constexpr unsigned InstCombineDefaultInfiniteLoopThreshold = 1000; 136 #endif 137 138 static cl::opt<bool> 139 EnableCodeSinking("instcombine-code-sinking", cl::desc("Enable code sinking"), 140 cl::init(true)); 141 142 static cl::opt<unsigned> LimitMaxIterations( 143 "instcombine-max-iterations", 144 cl::desc("Limit the maximum number of instruction combining iterations"), 145 cl::init(InstCombineDefaultMaxIterations)); 146 147 static cl::opt<unsigned> InfiniteLoopDetectionThreshold( 148 "instcombine-infinite-loop-threshold", 149 cl::desc("Number of instruction combining iterations considered an " 150 "infinite loop"), 151 cl::init(InstCombineDefaultInfiniteLoopThreshold), cl::Hidden); 152 153 static cl::opt<unsigned> 154 MaxArraySize("instcombine-maxarray-size", cl::init(1024), 155 cl::desc("Maximum array size considered when doing a combine")); 156 157 // FIXME: Remove this flag when it is no longer necessary to convert 158 // llvm.dbg.declare to avoid inaccurate debug info. Setting this to false 159 // increases variable availability at the cost of accuracy. Variables that 160 // cannot be promoted by mem2reg or SROA will be described as living in memory 161 // for their entire lifetime. However, passes like DSE and instcombine can 162 // delete stores to the alloca, leading to misleading and inaccurate debug 163 // information. This flag can be removed when those passes are fixed. 164 static cl::opt<unsigned> ShouldLowerDbgDeclare("instcombine-lower-dbg-declare", 165 cl::Hidden, cl::init(true)); 166 167 Optional<Instruction *> 168 InstCombiner::targetInstCombineIntrinsic(IntrinsicInst &II) { 169 // Handle target specific intrinsics 170 if (II.getCalledFunction()->isTargetIntrinsic()) { 171 return TTI.instCombineIntrinsic(*this, II); 172 } 173 return None; 174 } 175 176 Optional<Value *> InstCombiner::targetSimplifyDemandedUseBitsIntrinsic( 177 IntrinsicInst &II, APInt DemandedMask, KnownBits &Known, 178 bool &KnownBitsComputed) { 179 // Handle target specific intrinsics 180 if (II.getCalledFunction()->isTargetIntrinsic()) { 181 return TTI.simplifyDemandedUseBitsIntrinsic(*this, II, DemandedMask, Known, 182 KnownBitsComputed); 183 } 184 return None; 185 } 186 187 Optional<Value *> InstCombiner::targetSimplifyDemandedVectorEltsIntrinsic( 188 IntrinsicInst &II, APInt DemandedElts, APInt &UndefElts, APInt &UndefElts2, 189 APInt &UndefElts3, 190 std::function<void(Instruction *, unsigned, APInt, APInt &)> 191 SimplifyAndSetOp) { 192 // Handle target specific intrinsics 193 if (II.getCalledFunction()->isTargetIntrinsic()) { 194 return TTI.simplifyDemandedVectorEltsIntrinsic( 195 *this, II, DemandedElts, UndefElts, UndefElts2, UndefElts3, 196 SimplifyAndSetOp); 197 } 198 return None; 199 } 200 201 Value *InstCombinerImpl::EmitGEPOffset(User *GEP) { 202 return llvm::EmitGEPOffset(&Builder, DL, GEP); 203 } 204 205 /// Return true if it is desirable to convert an integer computation from a 206 /// given bit width to a new bit width. 207 /// We don't want to convert from a legal to an illegal type or from a smaller 208 /// to a larger illegal type. A width of '1' is always treated as a legal type 209 /// because i1 is a fundamental type in IR, and there are many specialized 210 /// optimizations for i1 types. Widths of 8, 16 or 32 are equally treated as 211 /// legal to convert to, in order to open up more combining opportunities. 212 /// NOTE: this treats i8, i16 and i32 specially, due to them being so common 213 /// from frontend languages. 214 bool InstCombinerImpl::shouldChangeType(unsigned FromWidth, 215 unsigned ToWidth) const { 216 bool FromLegal = FromWidth == 1 || DL.isLegalInteger(FromWidth); 217 bool ToLegal = ToWidth == 1 || DL.isLegalInteger(ToWidth); 218 219 // Convert to widths of 8, 16 or 32 even if they are not legal types. Only 220 // shrink types, to prevent infinite loops. 221 if (ToWidth < FromWidth && (ToWidth == 8 || ToWidth == 16 || ToWidth == 32)) 222 return true; 223 224 // If this is a legal integer from type, and the result would be an illegal 225 // type, don't do the transformation. 226 if (FromLegal && !ToLegal) 227 return false; 228 229 // Otherwise, if both are illegal, do not increase the size of the result. We 230 // do allow things like i160 -> i64, but not i64 -> i160. 231 if (!FromLegal && !ToLegal && ToWidth > FromWidth) 232 return false; 233 234 return true; 235 } 236 237 /// Return true if it is desirable to convert a computation from 'From' to 'To'. 238 /// We don't want to convert from a legal to an illegal type or from a smaller 239 /// to a larger illegal type. i1 is always treated as a legal type because it is 240 /// a fundamental type in IR, and there are many specialized optimizations for 241 /// i1 types. 242 bool InstCombinerImpl::shouldChangeType(Type *From, Type *To) const { 243 // TODO: This could be extended to allow vectors. Datalayout changes might be 244 // needed to properly support that. 245 if (!From->isIntegerTy() || !To->isIntegerTy()) 246 return false; 247 248 unsigned FromWidth = From->getPrimitiveSizeInBits(); 249 unsigned ToWidth = To->getPrimitiveSizeInBits(); 250 return shouldChangeType(FromWidth, ToWidth); 251 } 252 253 // Return true, if No Signed Wrap should be maintained for I. 254 // The No Signed Wrap flag can be kept if the operation "B (I.getOpcode) C", 255 // where both B and C should be ConstantInts, results in a constant that does 256 // not overflow. This function only handles the Add and Sub opcodes. For 257 // all other opcodes, the function conservatively returns false. 258 static bool maintainNoSignedWrap(BinaryOperator &I, Value *B, Value *C) { 259 auto *OBO = dyn_cast<OverflowingBinaryOperator>(&I); 260 if (!OBO || !OBO->hasNoSignedWrap()) 261 return false; 262 263 // We reason about Add and Sub Only. 264 Instruction::BinaryOps Opcode = I.getOpcode(); 265 if (Opcode != Instruction::Add && Opcode != Instruction::Sub) 266 return false; 267 268 const APInt *BVal, *CVal; 269 if (!match(B, m_APInt(BVal)) || !match(C, m_APInt(CVal))) 270 return false; 271 272 bool Overflow = false; 273 if (Opcode == Instruction::Add) 274 (void)BVal->sadd_ov(*CVal, Overflow); 275 else 276 (void)BVal->ssub_ov(*CVal, Overflow); 277 278 return !Overflow; 279 } 280 281 static bool hasNoUnsignedWrap(BinaryOperator &I) { 282 auto *OBO = dyn_cast<OverflowingBinaryOperator>(&I); 283 return OBO && OBO->hasNoUnsignedWrap(); 284 } 285 286 static bool hasNoSignedWrap(BinaryOperator &I) { 287 auto *OBO = dyn_cast<OverflowingBinaryOperator>(&I); 288 return OBO && OBO->hasNoSignedWrap(); 289 } 290 291 /// Conservatively clears subclassOptionalData after a reassociation or 292 /// commutation. We preserve fast-math flags when applicable as they can be 293 /// preserved. 294 static void ClearSubclassDataAfterReassociation(BinaryOperator &I) { 295 FPMathOperator *FPMO = dyn_cast<FPMathOperator>(&I); 296 if (!FPMO) { 297 I.clearSubclassOptionalData(); 298 return; 299 } 300 301 FastMathFlags FMF = I.getFastMathFlags(); 302 I.clearSubclassOptionalData(); 303 I.setFastMathFlags(FMF); 304 } 305 306 /// Combine constant operands of associative operations either before or after a 307 /// cast to eliminate one of the associative operations: 308 /// (op (cast (op X, C2)), C1) --> (cast (op X, op (C1, C2))) 309 /// (op (cast (op X, C2)), C1) --> (op (cast X), op (C1, C2)) 310 static bool simplifyAssocCastAssoc(BinaryOperator *BinOp1, 311 InstCombinerImpl &IC) { 312 auto *Cast = dyn_cast<CastInst>(BinOp1->getOperand(0)); 313 if (!Cast || !Cast->hasOneUse()) 314 return false; 315 316 // TODO: Enhance logic for other casts and remove this check. 317 auto CastOpcode = Cast->getOpcode(); 318 if (CastOpcode != Instruction::ZExt) 319 return false; 320 321 // TODO: Enhance logic for other BinOps and remove this check. 322 if (!BinOp1->isBitwiseLogicOp()) 323 return false; 324 325 auto AssocOpcode = BinOp1->getOpcode(); 326 auto *BinOp2 = dyn_cast<BinaryOperator>(Cast->getOperand(0)); 327 if (!BinOp2 || !BinOp2->hasOneUse() || BinOp2->getOpcode() != AssocOpcode) 328 return false; 329 330 Constant *C1, *C2; 331 if (!match(BinOp1->getOperand(1), m_Constant(C1)) || 332 !match(BinOp2->getOperand(1), m_Constant(C2))) 333 return false; 334 335 // TODO: This assumes a zext cast. 336 // Eg, if it was a trunc, we'd cast C1 to the source type because casting C2 337 // to the destination type might lose bits. 338 339 // Fold the constants together in the destination type: 340 // (op (cast (op X, C2)), C1) --> (op (cast X), FoldedC) 341 Type *DestTy = C1->getType(); 342 Constant *CastC2 = ConstantExpr::getCast(CastOpcode, C2, DestTy); 343 Constant *FoldedC = ConstantExpr::get(AssocOpcode, C1, CastC2); 344 IC.replaceOperand(*Cast, 0, BinOp2->getOperand(0)); 345 IC.replaceOperand(*BinOp1, 1, FoldedC); 346 return true; 347 } 348 349 /// This performs a few simplifications for operators that are associative or 350 /// commutative: 351 /// 352 /// Commutative operators: 353 /// 354 /// 1. Order operands such that they are listed from right (least complex) to 355 /// left (most complex). This puts constants before unary operators before 356 /// binary operators. 357 /// 358 /// Associative operators: 359 /// 360 /// 2. Transform: "(A op B) op C" ==> "A op (B op C)" if "B op C" simplifies. 361 /// 3. Transform: "A op (B op C)" ==> "(A op B) op C" if "A op B" simplifies. 362 /// 363 /// Associative and commutative operators: 364 /// 365 /// 4. Transform: "(A op B) op C" ==> "(C op A) op B" if "C op A" simplifies. 366 /// 5. Transform: "A op (B op C)" ==> "B op (C op A)" if "C op A" simplifies. 367 /// 6. Transform: "(A op C1) op (B op C2)" ==> "(A op B) op (C1 op C2)" 368 /// if C1 and C2 are constants. 369 bool InstCombinerImpl::SimplifyAssociativeOrCommutative(BinaryOperator &I) { 370 Instruction::BinaryOps Opcode = I.getOpcode(); 371 bool Changed = false; 372 373 do { 374 // Order operands such that they are listed from right (least complex) to 375 // left (most complex). This puts constants before unary operators before 376 // binary operators. 377 if (I.isCommutative() && getComplexity(I.getOperand(0)) < 378 getComplexity(I.getOperand(1))) 379 Changed = !I.swapOperands(); 380 381 BinaryOperator *Op0 = dyn_cast<BinaryOperator>(I.getOperand(0)); 382 BinaryOperator *Op1 = dyn_cast<BinaryOperator>(I.getOperand(1)); 383 384 if (I.isAssociative()) { 385 // Transform: "(A op B) op C" ==> "A op (B op C)" if "B op C" simplifies. 386 if (Op0 && Op0->getOpcode() == Opcode) { 387 Value *A = Op0->getOperand(0); 388 Value *B = Op0->getOperand(1); 389 Value *C = I.getOperand(1); 390 391 // Does "B op C" simplify? 392 if (Value *V = SimplifyBinOp(Opcode, B, C, SQ.getWithInstruction(&I))) { 393 // It simplifies to V. Form "A op V". 394 replaceOperand(I, 0, A); 395 replaceOperand(I, 1, V); 396 bool IsNUW = hasNoUnsignedWrap(I) && hasNoUnsignedWrap(*Op0); 397 bool IsNSW = maintainNoSignedWrap(I, B, C) && hasNoSignedWrap(*Op0); 398 399 // Conservatively clear all optional flags since they may not be 400 // preserved by the reassociation. Reset nsw/nuw based on the above 401 // analysis. 402 ClearSubclassDataAfterReassociation(I); 403 404 // Note: this is only valid because SimplifyBinOp doesn't look at 405 // the operands to Op0. 406 if (IsNUW) 407 I.setHasNoUnsignedWrap(true); 408 409 if (IsNSW) 410 I.setHasNoSignedWrap(true); 411 412 Changed = true; 413 ++NumReassoc; 414 continue; 415 } 416 } 417 418 // Transform: "A op (B op C)" ==> "(A op B) op C" if "A op B" simplifies. 419 if (Op1 && Op1->getOpcode() == Opcode) { 420 Value *A = I.getOperand(0); 421 Value *B = Op1->getOperand(0); 422 Value *C = Op1->getOperand(1); 423 424 // Does "A op B" simplify? 425 if (Value *V = SimplifyBinOp(Opcode, A, B, SQ.getWithInstruction(&I))) { 426 // It simplifies to V. Form "V op C". 427 replaceOperand(I, 0, V); 428 replaceOperand(I, 1, C); 429 // Conservatively clear the optional flags, since they may not be 430 // preserved by the reassociation. 431 ClearSubclassDataAfterReassociation(I); 432 Changed = true; 433 ++NumReassoc; 434 continue; 435 } 436 } 437 } 438 439 if (I.isAssociative() && I.isCommutative()) { 440 if (simplifyAssocCastAssoc(&I, *this)) { 441 Changed = true; 442 ++NumReassoc; 443 continue; 444 } 445 446 // Transform: "(A op B) op C" ==> "(C op A) op B" if "C op A" simplifies. 447 if (Op0 && Op0->getOpcode() == Opcode) { 448 Value *A = Op0->getOperand(0); 449 Value *B = Op0->getOperand(1); 450 Value *C = I.getOperand(1); 451 452 // Does "C op A" simplify? 453 if (Value *V = SimplifyBinOp(Opcode, C, A, SQ.getWithInstruction(&I))) { 454 // It simplifies to V. Form "V op B". 455 replaceOperand(I, 0, V); 456 replaceOperand(I, 1, B); 457 // Conservatively clear the optional flags, since they may not be 458 // preserved by the reassociation. 459 ClearSubclassDataAfterReassociation(I); 460 Changed = true; 461 ++NumReassoc; 462 continue; 463 } 464 } 465 466 // Transform: "A op (B op C)" ==> "B op (C op A)" if "C op A" simplifies. 467 if (Op1 && Op1->getOpcode() == Opcode) { 468 Value *A = I.getOperand(0); 469 Value *B = Op1->getOperand(0); 470 Value *C = Op1->getOperand(1); 471 472 // Does "C op A" simplify? 473 if (Value *V = SimplifyBinOp(Opcode, C, A, SQ.getWithInstruction(&I))) { 474 // It simplifies to V. Form "B op V". 475 replaceOperand(I, 0, B); 476 replaceOperand(I, 1, V); 477 // Conservatively clear the optional flags, since they may not be 478 // preserved by the reassociation. 479 ClearSubclassDataAfterReassociation(I); 480 Changed = true; 481 ++NumReassoc; 482 continue; 483 } 484 } 485 486 // Transform: "(A op C1) op (B op C2)" ==> "(A op B) op (C1 op C2)" 487 // if C1 and C2 are constants. 488 Value *A, *B; 489 Constant *C1, *C2; 490 if (Op0 && Op1 && 491 Op0->getOpcode() == Opcode && Op1->getOpcode() == Opcode && 492 match(Op0, m_OneUse(m_BinOp(m_Value(A), m_Constant(C1)))) && 493 match(Op1, m_OneUse(m_BinOp(m_Value(B), m_Constant(C2))))) { 494 bool IsNUW = hasNoUnsignedWrap(I) && 495 hasNoUnsignedWrap(*Op0) && 496 hasNoUnsignedWrap(*Op1); 497 BinaryOperator *NewBO = (IsNUW && Opcode == Instruction::Add) ? 498 BinaryOperator::CreateNUW(Opcode, A, B) : 499 BinaryOperator::Create(Opcode, A, B); 500 501 if (isa<FPMathOperator>(NewBO)) { 502 FastMathFlags Flags = I.getFastMathFlags(); 503 Flags &= Op0->getFastMathFlags(); 504 Flags &= Op1->getFastMathFlags(); 505 NewBO->setFastMathFlags(Flags); 506 } 507 InsertNewInstWith(NewBO, I); 508 NewBO->takeName(Op1); 509 replaceOperand(I, 0, NewBO); 510 replaceOperand(I, 1, ConstantExpr::get(Opcode, C1, C2)); 511 // Conservatively clear the optional flags, since they may not be 512 // preserved by the reassociation. 513 ClearSubclassDataAfterReassociation(I); 514 if (IsNUW) 515 I.setHasNoUnsignedWrap(true); 516 517 Changed = true; 518 continue; 519 } 520 } 521 522 // No further simplifications. 523 return Changed; 524 } while (true); 525 } 526 527 /// Return whether "X LOp (Y ROp Z)" is always equal to 528 /// "(X LOp Y) ROp (X LOp Z)". 529 static bool leftDistributesOverRight(Instruction::BinaryOps LOp, 530 Instruction::BinaryOps ROp) { 531 // X & (Y | Z) <--> (X & Y) | (X & Z) 532 // X & (Y ^ Z) <--> (X & Y) ^ (X & Z) 533 if (LOp == Instruction::And) 534 return ROp == Instruction::Or || ROp == Instruction::Xor; 535 536 // X | (Y & Z) <--> (X | Y) & (X | Z) 537 if (LOp == Instruction::Or) 538 return ROp == Instruction::And; 539 540 // X * (Y + Z) <--> (X * Y) + (X * Z) 541 // X * (Y - Z) <--> (X * Y) - (X * Z) 542 if (LOp == Instruction::Mul) 543 return ROp == Instruction::Add || ROp == Instruction::Sub; 544 545 return false; 546 } 547 548 /// Return whether "(X LOp Y) ROp Z" is always equal to 549 /// "(X ROp Z) LOp (Y ROp Z)". 550 static bool rightDistributesOverLeft(Instruction::BinaryOps LOp, 551 Instruction::BinaryOps ROp) { 552 if (Instruction::isCommutative(ROp)) 553 return leftDistributesOverRight(ROp, LOp); 554 555 // (X {&|^} Y) >> Z <--> (X >> Z) {&|^} (Y >> Z) for all shifts. 556 return Instruction::isBitwiseLogicOp(LOp) && Instruction::isShift(ROp); 557 558 // TODO: It would be nice to handle division, aka "(X + Y)/Z = X/Z + Y/Z", 559 // but this requires knowing that the addition does not overflow and other 560 // such subtleties. 561 } 562 563 /// This function returns identity value for given opcode, which can be used to 564 /// factor patterns like (X * 2) + X ==> (X * 2) + (X * 1) ==> X * (2 + 1). 565 static Value *getIdentityValue(Instruction::BinaryOps Opcode, Value *V) { 566 if (isa<Constant>(V)) 567 return nullptr; 568 569 return ConstantExpr::getBinOpIdentity(Opcode, V->getType()); 570 } 571 572 /// This function predicates factorization using distributive laws. By default, 573 /// it just returns the 'Op' inputs. But for special-cases like 574 /// 'add(shl(X, 5), ...)', this function will have TopOpcode == Instruction::Add 575 /// and Op = shl(X, 5). The 'shl' is treated as the more general 'mul X, 32' to 576 /// allow more factorization opportunities. 577 static Instruction::BinaryOps 578 getBinOpsForFactorization(Instruction::BinaryOps TopOpcode, BinaryOperator *Op, 579 Value *&LHS, Value *&RHS) { 580 assert(Op && "Expected a binary operator"); 581 LHS = Op->getOperand(0); 582 RHS = Op->getOperand(1); 583 if (TopOpcode == Instruction::Add || TopOpcode == Instruction::Sub) { 584 Constant *C; 585 if (match(Op, m_Shl(m_Value(), m_Constant(C)))) { 586 // X << C --> X * (1 << C) 587 RHS = ConstantExpr::getShl(ConstantInt::get(Op->getType(), 1), C); 588 return Instruction::Mul; 589 } 590 // TODO: We can add other conversions e.g. shr => div etc. 591 } 592 return Op->getOpcode(); 593 } 594 595 /// This tries to simplify binary operations by factorizing out common terms 596 /// (e. g. "(A*B)+(A*C)" -> "A*(B+C)"). 597 Value *InstCombinerImpl::tryFactorization(BinaryOperator &I, 598 Instruction::BinaryOps InnerOpcode, 599 Value *A, Value *B, Value *C, 600 Value *D) { 601 assert(A && B && C && D && "All values must be provided"); 602 603 Value *V = nullptr; 604 Value *SimplifiedInst = nullptr; 605 Value *LHS = I.getOperand(0), *RHS = I.getOperand(1); 606 Instruction::BinaryOps TopLevelOpcode = I.getOpcode(); 607 608 // Does "X op' Y" always equal "Y op' X"? 609 bool InnerCommutative = Instruction::isCommutative(InnerOpcode); 610 611 // Does "X op' (Y op Z)" always equal "(X op' Y) op (X op' Z)"? 612 if (leftDistributesOverRight(InnerOpcode, TopLevelOpcode)) 613 // Does the instruction have the form "(A op' B) op (A op' D)" or, in the 614 // commutative case, "(A op' B) op (C op' A)"? 615 if (A == C || (InnerCommutative && A == D)) { 616 if (A != C) 617 std::swap(C, D); 618 // Consider forming "A op' (B op D)". 619 // If "B op D" simplifies then it can be formed with no cost. 620 V = SimplifyBinOp(TopLevelOpcode, B, D, SQ.getWithInstruction(&I)); 621 // If "B op D" doesn't simplify then only go on if both of the existing 622 // operations "A op' B" and "C op' D" will be zapped as no longer used. 623 if (!V && LHS->hasOneUse() && RHS->hasOneUse()) 624 V = Builder.CreateBinOp(TopLevelOpcode, B, D, RHS->getName()); 625 if (V) { 626 SimplifiedInst = Builder.CreateBinOp(InnerOpcode, A, V); 627 } 628 } 629 630 // Does "(X op Y) op' Z" always equal "(X op' Z) op (Y op' Z)"? 631 if (!SimplifiedInst && rightDistributesOverLeft(TopLevelOpcode, InnerOpcode)) 632 // Does the instruction have the form "(A op' B) op (C op' B)" or, in the 633 // commutative case, "(A op' B) op (B op' D)"? 634 if (B == D || (InnerCommutative && B == C)) { 635 if (B != D) 636 std::swap(C, D); 637 // Consider forming "(A op C) op' B". 638 // If "A op C" simplifies then it can be formed with no cost. 639 V = SimplifyBinOp(TopLevelOpcode, A, C, SQ.getWithInstruction(&I)); 640 641 // If "A op C" doesn't simplify then only go on if both of the existing 642 // operations "A op' B" and "C op' D" will be zapped as no longer used. 643 if (!V && LHS->hasOneUse() && RHS->hasOneUse()) 644 V = Builder.CreateBinOp(TopLevelOpcode, A, C, LHS->getName()); 645 if (V) { 646 SimplifiedInst = Builder.CreateBinOp(InnerOpcode, V, B); 647 } 648 } 649 650 if (SimplifiedInst) { 651 ++NumFactor; 652 SimplifiedInst->takeName(&I); 653 654 // Check if we can add NSW/NUW flags to SimplifiedInst. If so, set them. 655 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(SimplifiedInst)) { 656 if (isa<OverflowingBinaryOperator>(SimplifiedInst)) { 657 bool HasNSW = false; 658 bool HasNUW = false; 659 if (isa<OverflowingBinaryOperator>(&I)) { 660 HasNSW = I.hasNoSignedWrap(); 661 HasNUW = I.hasNoUnsignedWrap(); 662 } 663 664 if (auto *LOBO = dyn_cast<OverflowingBinaryOperator>(LHS)) { 665 HasNSW &= LOBO->hasNoSignedWrap(); 666 HasNUW &= LOBO->hasNoUnsignedWrap(); 667 } 668 669 if (auto *ROBO = dyn_cast<OverflowingBinaryOperator>(RHS)) { 670 HasNSW &= ROBO->hasNoSignedWrap(); 671 HasNUW &= ROBO->hasNoUnsignedWrap(); 672 } 673 674 if (TopLevelOpcode == Instruction::Add && 675 InnerOpcode == Instruction::Mul) { 676 // We can propagate 'nsw' if we know that 677 // %Y = mul nsw i16 %X, C 678 // %Z = add nsw i16 %Y, %X 679 // => 680 // %Z = mul nsw i16 %X, C+1 681 // 682 // iff C+1 isn't INT_MIN 683 const APInt *CInt; 684 if (match(V, m_APInt(CInt))) { 685 if (!CInt->isMinSignedValue()) 686 BO->setHasNoSignedWrap(HasNSW); 687 } 688 689 // nuw can be propagated with any constant or nuw value. 690 BO->setHasNoUnsignedWrap(HasNUW); 691 } 692 } 693 } 694 } 695 return SimplifiedInst; 696 } 697 698 /// This tries to simplify binary operations which some other binary operation 699 /// distributes over either by factorizing out common terms 700 /// (eg "(A*B)+(A*C)" -> "A*(B+C)") or expanding out if this results in 701 /// simplifications (eg: "A & (B | C) -> (A&B) | (A&C)" if this is a win). 702 /// Returns the simplified value, or null if it didn't simplify. 703 Value *InstCombinerImpl::SimplifyUsingDistributiveLaws(BinaryOperator &I) { 704 Value *LHS = I.getOperand(0), *RHS = I.getOperand(1); 705 BinaryOperator *Op0 = dyn_cast<BinaryOperator>(LHS); 706 BinaryOperator *Op1 = dyn_cast<BinaryOperator>(RHS); 707 Instruction::BinaryOps TopLevelOpcode = I.getOpcode(); 708 709 { 710 // Factorization. 711 Value *A, *B, *C, *D; 712 Instruction::BinaryOps LHSOpcode, RHSOpcode; 713 if (Op0) 714 LHSOpcode = getBinOpsForFactorization(TopLevelOpcode, Op0, A, B); 715 if (Op1) 716 RHSOpcode = getBinOpsForFactorization(TopLevelOpcode, Op1, C, D); 717 718 // The instruction has the form "(A op' B) op (C op' D)". Try to factorize 719 // a common term. 720 if (Op0 && Op1 && LHSOpcode == RHSOpcode) 721 if (Value *V = tryFactorization(I, LHSOpcode, A, B, C, D)) 722 return V; 723 724 // The instruction has the form "(A op' B) op (C)". Try to factorize common 725 // term. 726 if (Op0) 727 if (Value *Ident = getIdentityValue(LHSOpcode, RHS)) 728 if (Value *V = tryFactorization(I, LHSOpcode, A, B, RHS, Ident)) 729 return V; 730 731 // The instruction has the form "(B) op (C op' D)". Try to factorize common 732 // term. 733 if (Op1) 734 if (Value *Ident = getIdentityValue(RHSOpcode, LHS)) 735 if (Value *V = tryFactorization(I, RHSOpcode, LHS, Ident, C, D)) 736 return V; 737 } 738 739 // Expansion. 740 if (Op0 && rightDistributesOverLeft(Op0->getOpcode(), TopLevelOpcode)) { 741 // The instruction has the form "(A op' B) op C". See if expanding it out 742 // to "(A op C) op' (B op C)" results in simplifications. 743 Value *A = Op0->getOperand(0), *B = Op0->getOperand(1), *C = RHS; 744 Instruction::BinaryOps InnerOpcode = Op0->getOpcode(); // op' 745 746 // Disable the use of undef because it's not safe to distribute undef. 747 auto SQDistributive = SQ.getWithInstruction(&I).getWithoutUndef(); 748 Value *L = SimplifyBinOp(TopLevelOpcode, A, C, SQDistributive); 749 Value *R = SimplifyBinOp(TopLevelOpcode, B, C, SQDistributive); 750 751 // Do "A op C" and "B op C" both simplify? 752 if (L && R) { 753 // They do! Return "L op' R". 754 ++NumExpand; 755 C = Builder.CreateBinOp(InnerOpcode, L, R); 756 C->takeName(&I); 757 return C; 758 } 759 760 // Does "A op C" simplify to the identity value for the inner opcode? 761 if (L && L == ConstantExpr::getBinOpIdentity(InnerOpcode, L->getType())) { 762 // They do! Return "B op C". 763 ++NumExpand; 764 C = Builder.CreateBinOp(TopLevelOpcode, B, C); 765 C->takeName(&I); 766 return C; 767 } 768 769 // Does "B op C" simplify to the identity value for the inner opcode? 770 if (R && R == ConstantExpr::getBinOpIdentity(InnerOpcode, R->getType())) { 771 // They do! Return "A op C". 772 ++NumExpand; 773 C = Builder.CreateBinOp(TopLevelOpcode, A, C); 774 C->takeName(&I); 775 return C; 776 } 777 } 778 779 if (Op1 && leftDistributesOverRight(TopLevelOpcode, Op1->getOpcode())) { 780 // The instruction has the form "A op (B op' C)". See if expanding it out 781 // to "(A op B) op' (A op C)" results in simplifications. 782 Value *A = LHS, *B = Op1->getOperand(0), *C = Op1->getOperand(1); 783 Instruction::BinaryOps InnerOpcode = Op1->getOpcode(); // op' 784 785 // Disable the use of undef because it's not safe to distribute undef. 786 auto SQDistributive = SQ.getWithInstruction(&I).getWithoutUndef(); 787 Value *L = SimplifyBinOp(TopLevelOpcode, A, B, SQDistributive); 788 Value *R = SimplifyBinOp(TopLevelOpcode, A, C, SQDistributive); 789 790 // Do "A op B" and "A op C" both simplify? 791 if (L && R) { 792 // They do! Return "L op' R". 793 ++NumExpand; 794 A = Builder.CreateBinOp(InnerOpcode, L, R); 795 A->takeName(&I); 796 return A; 797 } 798 799 // Does "A op B" simplify to the identity value for the inner opcode? 800 if (L && L == ConstantExpr::getBinOpIdentity(InnerOpcode, L->getType())) { 801 // They do! Return "A op C". 802 ++NumExpand; 803 A = Builder.CreateBinOp(TopLevelOpcode, A, C); 804 A->takeName(&I); 805 return A; 806 } 807 808 // Does "A op C" simplify to the identity value for the inner opcode? 809 if (R && R == ConstantExpr::getBinOpIdentity(InnerOpcode, R->getType())) { 810 // They do! Return "A op B". 811 ++NumExpand; 812 A = Builder.CreateBinOp(TopLevelOpcode, A, B); 813 A->takeName(&I); 814 return A; 815 } 816 } 817 818 return SimplifySelectsFeedingBinaryOp(I, LHS, RHS); 819 } 820 821 Value *InstCombinerImpl::SimplifySelectsFeedingBinaryOp(BinaryOperator &I, 822 Value *LHS, 823 Value *RHS) { 824 Value *A, *B, *C, *D, *E, *F; 825 bool LHSIsSelect = match(LHS, m_Select(m_Value(A), m_Value(B), m_Value(C))); 826 bool RHSIsSelect = match(RHS, m_Select(m_Value(D), m_Value(E), m_Value(F))); 827 if (!LHSIsSelect && !RHSIsSelect) 828 return nullptr; 829 830 FastMathFlags FMF; 831 BuilderTy::FastMathFlagGuard Guard(Builder); 832 if (isa<FPMathOperator>(&I)) { 833 FMF = I.getFastMathFlags(); 834 Builder.setFastMathFlags(FMF); 835 } 836 837 Instruction::BinaryOps Opcode = I.getOpcode(); 838 SimplifyQuery Q = SQ.getWithInstruction(&I); 839 840 Value *Cond, *True = nullptr, *False = nullptr; 841 if (LHSIsSelect && RHSIsSelect && A == D) { 842 // (A ? B : C) op (A ? E : F) -> A ? (B op E) : (C op F) 843 Cond = A; 844 True = SimplifyBinOp(Opcode, B, E, FMF, Q); 845 False = SimplifyBinOp(Opcode, C, F, FMF, Q); 846 847 if (LHS->hasOneUse() && RHS->hasOneUse()) { 848 if (False && !True) 849 True = Builder.CreateBinOp(Opcode, B, E); 850 else if (True && !False) 851 False = Builder.CreateBinOp(Opcode, C, F); 852 } 853 } else if (LHSIsSelect && LHS->hasOneUse()) { 854 // (A ? B : C) op Y -> A ? (B op Y) : (C op Y) 855 Cond = A; 856 True = SimplifyBinOp(Opcode, B, RHS, FMF, Q); 857 False = SimplifyBinOp(Opcode, C, RHS, FMF, Q); 858 } else if (RHSIsSelect && RHS->hasOneUse()) { 859 // X op (D ? E : F) -> D ? (X op E) : (X op F) 860 Cond = D; 861 True = SimplifyBinOp(Opcode, LHS, E, FMF, Q); 862 False = SimplifyBinOp(Opcode, LHS, F, FMF, Q); 863 } 864 865 if (!True || !False) 866 return nullptr; 867 868 Value *SI = Builder.CreateSelect(Cond, True, False); 869 SI->takeName(&I); 870 return SI; 871 } 872 873 /// Given a 'sub' instruction, return the RHS of the instruction if the LHS is a 874 /// constant zero (which is the 'negate' form). 875 Value *InstCombinerImpl::dyn_castNegVal(Value *V) const { 876 Value *NegV; 877 if (match(V, m_Neg(m_Value(NegV)))) 878 return NegV; 879 880 // Constants can be considered to be negated values if they can be folded. 881 if (ConstantInt *C = dyn_cast<ConstantInt>(V)) 882 return ConstantExpr::getNeg(C); 883 884 if (ConstantDataVector *C = dyn_cast<ConstantDataVector>(V)) 885 if (C->getType()->getElementType()->isIntegerTy()) 886 return ConstantExpr::getNeg(C); 887 888 if (ConstantVector *CV = dyn_cast<ConstantVector>(V)) { 889 for (unsigned i = 0, e = CV->getNumOperands(); i != e; ++i) { 890 Constant *Elt = CV->getAggregateElement(i); 891 if (!Elt) 892 return nullptr; 893 894 if (isa<UndefValue>(Elt)) 895 continue; 896 897 if (!isa<ConstantInt>(Elt)) 898 return nullptr; 899 } 900 return ConstantExpr::getNeg(CV); 901 } 902 903 return nullptr; 904 } 905 906 static Value *foldOperationIntoSelectOperand(Instruction &I, Value *SO, 907 InstCombiner::BuilderTy &Builder) { 908 if (auto *Cast = dyn_cast<CastInst>(&I)) 909 return Builder.CreateCast(Cast->getOpcode(), SO, I.getType()); 910 911 assert(I.isBinaryOp() && "Unexpected opcode for select folding"); 912 913 // Figure out if the constant is the left or the right argument. 914 bool ConstIsRHS = isa<Constant>(I.getOperand(1)); 915 Constant *ConstOperand = cast<Constant>(I.getOperand(ConstIsRHS)); 916 917 if (auto *SOC = dyn_cast<Constant>(SO)) { 918 if (ConstIsRHS) 919 return ConstantExpr::get(I.getOpcode(), SOC, ConstOperand); 920 return ConstantExpr::get(I.getOpcode(), ConstOperand, SOC); 921 } 922 923 Value *Op0 = SO, *Op1 = ConstOperand; 924 if (!ConstIsRHS) 925 std::swap(Op0, Op1); 926 927 auto *BO = cast<BinaryOperator>(&I); 928 Value *RI = Builder.CreateBinOp(BO->getOpcode(), Op0, Op1, 929 SO->getName() + ".op"); 930 auto *FPInst = dyn_cast<Instruction>(RI); 931 if (FPInst && isa<FPMathOperator>(FPInst)) 932 FPInst->copyFastMathFlags(BO); 933 return RI; 934 } 935 936 Instruction *InstCombinerImpl::FoldOpIntoSelect(Instruction &Op, 937 SelectInst *SI) { 938 // Don't modify shared select instructions. 939 if (!SI->hasOneUse()) 940 return nullptr; 941 942 Value *TV = SI->getTrueValue(); 943 Value *FV = SI->getFalseValue(); 944 if (!(isa<Constant>(TV) || isa<Constant>(FV))) 945 return nullptr; 946 947 // Bool selects with constant operands can be folded to logical ops. 948 if (SI->getType()->isIntOrIntVectorTy(1)) 949 return nullptr; 950 951 // If it's a bitcast involving vectors, make sure it has the same number of 952 // elements on both sides. 953 if (auto *BC = dyn_cast<BitCastInst>(&Op)) { 954 VectorType *DestTy = dyn_cast<VectorType>(BC->getDestTy()); 955 VectorType *SrcTy = dyn_cast<VectorType>(BC->getSrcTy()); 956 957 // Verify that either both or neither are vectors. 958 if ((SrcTy == nullptr) != (DestTy == nullptr)) 959 return nullptr; 960 961 // If vectors, verify that they have the same number of elements. 962 if (SrcTy && SrcTy->getElementCount() != DestTy->getElementCount()) 963 return nullptr; 964 } 965 966 // Test if a CmpInst instruction is used exclusively by a select as 967 // part of a minimum or maximum operation. If so, refrain from doing 968 // any other folding. This helps out other analyses which understand 969 // non-obfuscated minimum and maximum idioms, such as ScalarEvolution 970 // and CodeGen. And in this case, at least one of the comparison 971 // operands has at least one user besides the compare (the select), 972 // which would often largely negate the benefit of folding anyway. 973 if (auto *CI = dyn_cast<CmpInst>(SI->getCondition())) { 974 if (CI->hasOneUse()) { 975 Value *Op0 = CI->getOperand(0), *Op1 = CI->getOperand(1); 976 977 // FIXME: This is a hack to avoid infinite looping with min/max patterns. 978 // We have to ensure that vector constants that only differ with 979 // undef elements are treated as equivalent. 980 auto areLooselyEqual = [](Value *A, Value *B) { 981 if (A == B) 982 return true; 983 984 // Test for vector constants. 985 Constant *ConstA, *ConstB; 986 if (!match(A, m_Constant(ConstA)) || !match(B, m_Constant(ConstB))) 987 return false; 988 989 // TODO: Deal with FP constants? 990 if (!A->getType()->isIntOrIntVectorTy() || A->getType() != B->getType()) 991 return false; 992 993 // Compare for equality including undefs as equal. 994 auto *Cmp = ConstantExpr::getCompare(ICmpInst::ICMP_EQ, ConstA, ConstB); 995 const APInt *C; 996 return match(Cmp, m_APIntAllowUndef(C)) && C->isOneValue(); 997 }; 998 999 if ((areLooselyEqual(TV, Op0) && areLooselyEqual(FV, Op1)) || 1000 (areLooselyEqual(FV, Op0) && areLooselyEqual(TV, Op1))) 1001 return nullptr; 1002 } 1003 } 1004 1005 Value *NewTV = foldOperationIntoSelectOperand(Op, TV, Builder); 1006 Value *NewFV = foldOperationIntoSelectOperand(Op, FV, Builder); 1007 return SelectInst::Create(SI->getCondition(), NewTV, NewFV, "", nullptr, SI); 1008 } 1009 1010 static Value *foldOperationIntoPhiValue(BinaryOperator *I, Value *InV, 1011 InstCombiner::BuilderTy &Builder) { 1012 bool ConstIsRHS = isa<Constant>(I->getOperand(1)); 1013 Constant *C = cast<Constant>(I->getOperand(ConstIsRHS)); 1014 1015 if (auto *InC = dyn_cast<Constant>(InV)) { 1016 if (ConstIsRHS) 1017 return ConstantExpr::get(I->getOpcode(), InC, C); 1018 return ConstantExpr::get(I->getOpcode(), C, InC); 1019 } 1020 1021 Value *Op0 = InV, *Op1 = C; 1022 if (!ConstIsRHS) 1023 std::swap(Op0, Op1); 1024 1025 Value *RI = Builder.CreateBinOp(I->getOpcode(), Op0, Op1, "phi.bo"); 1026 auto *FPInst = dyn_cast<Instruction>(RI); 1027 if (FPInst && isa<FPMathOperator>(FPInst)) 1028 FPInst->copyFastMathFlags(I); 1029 return RI; 1030 } 1031 1032 Instruction *InstCombinerImpl::foldOpIntoPhi(Instruction &I, PHINode *PN) { 1033 unsigned NumPHIValues = PN->getNumIncomingValues(); 1034 if (NumPHIValues == 0) 1035 return nullptr; 1036 1037 // We normally only transform phis with a single use. However, if a PHI has 1038 // multiple uses and they are all the same operation, we can fold *all* of the 1039 // uses into the PHI. 1040 if (!PN->hasOneUse()) { 1041 // Walk the use list for the instruction, comparing them to I. 1042 for (User *U : PN->users()) { 1043 Instruction *UI = cast<Instruction>(U); 1044 if (UI != &I && !I.isIdenticalTo(UI)) 1045 return nullptr; 1046 } 1047 // Otherwise, we can replace *all* users with the new PHI we form. 1048 } 1049 1050 // Check to see if all of the operands of the PHI are simple constants 1051 // (constantint/constantfp/undef). If there is one non-constant value, 1052 // remember the BB it is in. If there is more than one or if *it* is a PHI, 1053 // bail out. We don't do arbitrary constant expressions here because moving 1054 // their computation can be expensive without a cost model. 1055 BasicBlock *NonConstBB = nullptr; 1056 for (unsigned i = 0; i != NumPHIValues; ++i) { 1057 Value *InVal = PN->getIncomingValue(i); 1058 // If I is a freeze instruction, count undef as a non-constant. 1059 if (match(InVal, m_ImmConstant()) && 1060 (!isa<FreezeInst>(I) || isGuaranteedNotToBeUndefOrPoison(InVal))) 1061 continue; 1062 1063 if (isa<PHINode>(InVal)) return nullptr; // Itself a phi. 1064 if (NonConstBB) return nullptr; // More than one non-const value. 1065 1066 NonConstBB = PN->getIncomingBlock(i); 1067 1068 // If the InVal is an invoke at the end of the pred block, then we can't 1069 // insert a computation after it without breaking the edge. 1070 if (isa<InvokeInst>(InVal)) 1071 if (cast<Instruction>(InVal)->getParent() == NonConstBB) 1072 return nullptr; 1073 1074 // If the incoming non-constant value is in I's block, we will remove one 1075 // instruction, but insert another equivalent one, leading to infinite 1076 // instcombine. 1077 if (isPotentiallyReachable(I.getParent(), NonConstBB, &DT, LI)) 1078 return nullptr; 1079 } 1080 1081 // If there is exactly one non-constant value, we can insert a copy of the 1082 // operation in that block. However, if this is a critical edge, we would be 1083 // inserting the computation on some other paths (e.g. inside a loop). Only 1084 // do this if the pred block is unconditionally branching into the phi block. 1085 // Also, make sure that the pred block is not dead code. 1086 if (NonConstBB != nullptr) { 1087 BranchInst *BI = dyn_cast<BranchInst>(NonConstBB->getTerminator()); 1088 if (!BI || !BI->isUnconditional() || !DT.isReachableFromEntry(NonConstBB)) 1089 return nullptr; 1090 } 1091 1092 // Okay, we can do the transformation: create the new PHI node. 1093 PHINode *NewPN = PHINode::Create(I.getType(), PN->getNumIncomingValues()); 1094 InsertNewInstBefore(NewPN, *PN); 1095 NewPN->takeName(PN); 1096 1097 // If we are going to have to insert a new computation, do so right before the 1098 // predecessor's terminator. 1099 if (NonConstBB) 1100 Builder.SetInsertPoint(NonConstBB->getTerminator()); 1101 1102 // Next, add all of the operands to the PHI. 1103 if (SelectInst *SI = dyn_cast<SelectInst>(&I)) { 1104 // We only currently try to fold the condition of a select when it is a phi, 1105 // not the true/false values. 1106 Value *TrueV = SI->getTrueValue(); 1107 Value *FalseV = SI->getFalseValue(); 1108 BasicBlock *PhiTransBB = PN->getParent(); 1109 for (unsigned i = 0; i != NumPHIValues; ++i) { 1110 BasicBlock *ThisBB = PN->getIncomingBlock(i); 1111 Value *TrueVInPred = TrueV->DoPHITranslation(PhiTransBB, ThisBB); 1112 Value *FalseVInPred = FalseV->DoPHITranslation(PhiTransBB, ThisBB); 1113 Value *InV = nullptr; 1114 // Beware of ConstantExpr: it may eventually evaluate to getNullValue, 1115 // even if currently isNullValue gives false. 1116 Constant *InC = dyn_cast<Constant>(PN->getIncomingValue(i)); 1117 // For vector constants, we cannot use isNullValue to fold into 1118 // FalseVInPred versus TrueVInPred. When we have individual nonzero 1119 // elements in the vector, we will incorrectly fold InC to 1120 // `TrueVInPred`. 1121 if (InC && isa<ConstantInt>(InC)) 1122 InV = InC->isNullValue() ? FalseVInPred : TrueVInPred; 1123 else { 1124 // Generate the select in the same block as PN's current incoming block. 1125 // Note: ThisBB need not be the NonConstBB because vector constants 1126 // which are constants by definition are handled here. 1127 // FIXME: This can lead to an increase in IR generation because we might 1128 // generate selects for vector constant phi operand, that could not be 1129 // folded to TrueVInPred or FalseVInPred as done for ConstantInt. For 1130 // non-vector phis, this transformation was always profitable because 1131 // the select would be generated exactly once in the NonConstBB. 1132 Builder.SetInsertPoint(ThisBB->getTerminator()); 1133 InV = Builder.CreateSelect(PN->getIncomingValue(i), TrueVInPred, 1134 FalseVInPred, "phi.sel"); 1135 } 1136 NewPN->addIncoming(InV, ThisBB); 1137 } 1138 } else if (CmpInst *CI = dyn_cast<CmpInst>(&I)) { 1139 Constant *C = cast<Constant>(I.getOperand(1)); 1140 for (unsigned i = 0; i != NumPHIValues; ++i) { 1141 Value *InV = nullptr; 1142 if (auto *InC = dyn_cast<Constant>(PN->getIncomingValue(i))) 1143 InV = ConstantExpr::getCompare(CI->getPredicate(), InC, C); 1144 else 1145 InV = Builder.CreateCmp(CI->getPredicate(), PN->getIncomingValue(i), 1146 C, "phi.cmp"); 1147 NewPN->addIncoming(InV, PN->getIncomingBlock(i)); 1148 } 1149 } else if (auto *BO = dyn_cast<BinaryOperator>(&I)) { 1150 for (unsigned i = 0; i != NumPHIValues; ++i) { 1151 Value *InV = foldOperationIntoPhiValue(BO, PN->getIncomingValue(i), 1152 Builder); 1153 NewPN->addIncoming(InV, PN->getIncomingBlock(i)); 1154 } 1155 } else if (isa<FreezeInst>(&I)) { 1156 for (unsigned i = 0; i != NumPHIValues; ++i) { 1157 Value *InV; 1158 if (NonConstBB == PN->getIncomingBlock(i)) 1159 InV = Builder.CreateFreeze(PN->getIncomingValue(i), "phi.fr"); 1160 else 1161 InV = PN->getIncomingValue(i); 1162 NewPN->addIncoming(InV, PN->getIncomingBlock(i)); 1163 } 1164 } else { 1165 CastInst *CI = cast<CastInst>(&I); 1166 Type *RetTy = CI->getType(); 1167 for (unsigned i = 0; i != NumPHIValues; ++i) { 1168 Value *InV; 1169 if (Constant *InC = dyn_cast<Constant>(PN->getIncomingValue(i))) 1170 InV = ConstantExpr::getCast(CI->getOpcode(), InC, RetTy); 1171 else 1172 InV = Builder.CreateCast(CI->getOpcode(), PN->getIncomingValue(i), 1173 I.getType(), "phi.cast"); 1174 NewPN->addIncoming(InV, PN->getIncomingBlock(i)); 1175 } 1176 } 1177 1178 for (auto UI = PN->user_begin(), E = PN->user_end(); UI != E;) { 1179 Instruction *User = cast<Instruction>(*UI++); 1180 if (User == &I) continue; 1181 replaceInstUsesWith(*User, NewPN); 1182 eraseInstFromFunction(*User); 1183 } 1184 return replaceInstUsesWith(I, NewPN); 1185 } 1186 1187 Instruction *InstCombinerImpl::foldBinOpIntoSelectOrPhi(BinaryOperator &I) { 1188 if (!isa<Constant>(I.getOperand(1))) 1189 return nullptr; 1190 1191 if (auto *Sel = dyn_cast<SelectInst>(I.getOperand(0))) { 1192 if (Instruction *NewSel = FoldOpIntoSelect(I, Sel)) 1193 return NewSel; 1194 } else if (auto *PN = dyn_cast<PHINode>(I.getOperand(0))) { 1195 if (Instruction *NewPhi = foldOpIntoPhi(I, PN)) 1196 return NewPhi; 1197 } 1198 return nullptr; 1199 } 1200 1201 /// Given a pointer type and a constant offset, determine whether or not there 1202 /// is a sequence of GEP indices into the pointed type that will land us at the 1203 /// specified offset. If so, fill them into NewIndices and return the resultant 1204 /// element type, otherwise return null. 1205 Type * 1206 InstCombinerImpl::FindElementAtOffset(PointerType *PtrTy, int64_t Offset, 1207 SmallVectorImpl<Value *> &NewIndices) { 1208 Type *Ty = PtrTy->getElementType(); 1209 if (!Ty->isSized()) 1210 return nullptr; 1211 1212 // Start with the index over the outer type. Note that the type size 1213 // might be zero (even if the offset isn't zero) if the indexed type 1214 // is something like [0 x {int, int}] 1215 Type *IndexTy = DL.getIndexType(PtrTy); 1216 int64_t FirstIdx = 0; 1217 if (int64_t TySize = DL.getTypeAllocSize(Ty)) { 1218 FirstIdx = Offset/TySize; 1219 Offset -= FirstIdx*TySize; 1220 1221 // Handle hosts where % returns negative instead of values [0..TySize). 1222 if (Offset < 0) { 1223 --FirstIdx; 1224 Offset += TySize; 1225 assert(Offset >= 0); 1226 } 1227 assert((uint64_t)Offset < (uint64_t)TySize && "Out of range offset"); 1228 } 1229 1230 NewIndices.push_back(ConstantInt::get(IndexTy, FirstIdx)); 1231 1232 // Index into the types. If we fail, set OrigBase to null. 1233 while (Offset) { 1234 // Indexing into tail padding between struct/array elements. 1235 if (uint64_t(Offset * 8) >= DL.getTypeSizeInBits(Ty)) 1236 return nullptr; 1237 1238 if (StructType *STy = dyn_cast<StructType>(Ty)) { 1239 const StructLayout *SL = DL.getStructLayout(STy); 1240 assert(Offset < (int64_t)SL->getSizeInBytes() && 1241 "Offset must stay within the indexed type"); 1242 1243 unsigned Elt = SL->getElementContainingOffset(Offset); 1244 NewIndices.push_back(ConstantInt::get(Type::getInt32Ty(Ty->getContext()), 1245 Elt)); 1246 1247 Offset -= SL->getElementOffset(Elt); 1248 Ty = STy->getElementType(Elt); 1249 } else if (ArrayType *AT = dyn_cast<ArrayType>(Ty)) { 1250 uint64_t EltSize = DL.getTypeAllocSize(AT->getElementType()); 1251 assert(EltSize && "Cannot index into a zero-sized array"); 1252 NewIndices.push_back(ConstantInt::get(IndexTy,Offset/EltSize)); 1253 Offset %= EltSize; 1254 Ty = AT->getElementType(); 1255 } else { 1256 // Otherwise, we can't index into the middle of this atomic type, bail. 1257 return nullptr; 1258 } 1259 } 1260 1261 return Ty; 1262 } 1263 1264 static bool shouldMergeGEPs(GEPOperator &GEP, GEPOperator &Src) { 1265 // If this GEP has only 0 indices, it is the same pointer as 1266 // Src. If Src is not a trivial GEP too, don't combine 1267 // the indices. 1268 if (GEP.hasAllZeroIndices() && !Src.hasAllZeroIndices() && 1269 !Src.hasOneUse()) 1270 return false; 1271 return true; 1272 } 1273 1274 /// Return a value X such that Val = X * Scale, or null if none. 1275 /// If the multiplication is known not to overflow, then NoSignedWrap is set. 1276 Value *InstCombinerImpl::Descale(Value *Val, APInt Scale, bool &NoSignedWrap) { 1277 assert(isa<IntegerType>(Val->getType()) && "Can only descale integers!"); 1278 assert(cast<IntegerType>(Val->getType())->getBitWidth() == 1279 Scale.getBitWidth() && "Scale not compatible with value!"); 1280 1281 // If Val is zero or Scale is one then Val = Val * Scale. 1282 if (match(Val, m_Zero()) || Scale == 1) { 1283 NoSignedWrap = true; 1284 return Val; 1285 } 1286 1287 // If Scale is zero then it does not divide Val. 1288 if (Scale.isMinValue()) 1289 return nullptr; 1290 1291 // Look through chains of multiplications, searching for a constant that is 1292 // divisible by Scale. For example, descaling X*(Y*(Z*4)) by a factor of 4 1293 // will find the constant factor 4 and produce X*(Y*Z). Descaling X*(Y*8) by 1294 // a factor of 4 will produce X*(Y*2). The principle of operation is to bore 1295 // down from Val: 1296 // 1297 // Val = M1 * X || Analysis starts here and works down 1298 // M1 = M2 * Y || Doesn't descend into terms with more 1299 // M2 = Z * 4 \/ than one use 1300 // 1301 // Then to modify a term at the bottom: 1302 // 1303 // Val = M1 * X 1304 // M1 = Z * Y || Replaced M2 with Z 1305 // 1306 // Then to work back up correcting nsw flags. 1307 1308 // Op - the term we are currently analyzing. Starts at Val then drills down. 1309 // Replaced with its descaled value before exiting from the drill down loop. 1310 Value *Op = Val; 1311 1312 // Parent - initially null, but after drilling down notes where Op came from. 1313 // In the example above, Parent is (Val, 0) when Op is M1, because M1 is the 1314 // 0'th operand of Val. 1315 std::pair<Instruction *, unsigned> Parent; 1316 1317 // Set if the transform requires a descaling at deeper levels that doesn't 1318 // overflow. 1319 bool RequireNoSignedWrap = false; 1320 1321 // Log base 2 of the scale. Negative if not a power of 2. 1322 int32_t logScale = Scale.exactLogBase2(); 1323 1324 for (;; Op = Parent.first->getOperand(Parent.second)) { // Drill down 1325 if (ConstantInt *CI = dyn_cast<ConstantInt>(Op)) { 1326 // If Op is a constant divisible by Scale then descale to the quotient. 1327 APInt Quotient(Scale), Remainder(Scale); // Init ensures right bitwidth. 1328 APInt::sdivrem(CI->getValue(), Scale, Quotient, Remainder); 1329 if (!Remainder.isMinValue()) 1330 // Not divisible by Scale. 1331 return nullptr; 1332 // Replace with the quotient in the parent. 1333 Op = ConstantInt::get(CI->getType(), Quotient); 1334 NoSignedWrap = true; 1335 break; 1336 } 1337 1338 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(Op)) { 1339 if (BO->getOpcode() == Instruction::Mul) { 1340 // Multiplication. 1341 NoSignedWrap = BO->hasNoSignedWrap(); 1342 if (RequireNoSignedWrap && !NoSignedWrap) 1343 return nullptr; 1344 1345 // There are three cases for multiplication: multiplication by exactly 1346 // the scale, multiplication by a constant different to the scale, and 1347 // multiplication by something else. 1348 Value *LHS = BO->getOperand(0); 1349 Value *RHS = BO->getOperand(1); 1350 1351 if (ConstantInt *CI = dyn_cast<ConstantInt>(RHS)) { 1352 // Multiplication by a constant. 1353 if (CI->getValue() == Scale) { 1354 // Multiplication by exactly the scale, replace the multiplication 1355 // by its left-hand side in the parent. 1356 Op = LHS; 1357 break; 1358 } 1359 1360 // Otherwise drill down into the constant. 1361 if (!Op->hasOneUse()) 1362 return nullptr; 1363 1364 Parent = std::make_pair(BO, 1); 1365 continue; 1366 } 1367 1368 // Multiplication by something else. Drill down into the left-hand side 1369 // since that's where the reassociate pass puts the good stuff. 1370 if (!Op->hasOneUse()) 1371 return nullptr; 1372 1373 Parent = std::make_pair(BO, 0); 1374 continue; 1375 } 1376 1377 if (logScale > 0 && BO->getOpcode() == Instruction::Shl && 1378 isa<ConstantInt>(BO->getOperand(1))) { 1379 // Multiplication by a power of 2. 1380 NoSignedWrap = BO->hasNoSignedWrap(); 1381 if (RequireNoSignedWrap && !NoSignedWrap) 1382 return nullptr; 1383 1384 Value *LHS = BO->getOperand(0); 1385 int32_t Amt = cast<ConstantInt>(BO->getOperand(1))-> 1386 getLimitedValue(Scale.getBitWidth()); 1387 // Op = LHS << Amt. 1388 1389 if (Amt == logScale) { 1390 // Multiplication by exactly the scale, replace the multiplication 1391 // by its left-hand side in the parent. 1392 Op = LHS; 1393 break; 1394 } 1395 if (Amt < logScale || !Op->hasOneUse()) 1396 return nullptr; 1397 1398 // Multiplication by more than the scale. Reduce the multiplying amount 1399 // by the scale in the parent. 1400 Parent = std::make_pair(BO, 1); 1401 Op = ConstantInt::get(BO->getType(), Amt - logScale); 1402 break; 1403 } 1404 } 1405 1406 if (!Op->hasOneUse()) 1407 return nullptr; 1408 1409 if (CastInst *Cast = dyn_cast<CastInst>(Op)) { 1410 if (Cast->getOpcode() == Instruction::SExt) { 1411 // Op is sign-extended from a smaller type, descale in the smaller type. 1412 unsigned SmallSize = Cast->getSrcTy()->getPrimitiveSizeInBits(); 1413 APInt SmallScale = Scale.trunc(SmallSize); 1414 // Suppose Op = sext X, and we descale X as Y * SmallScale. We want to 1415 // descale Op as (sext Y) * Scale. In order to have 1416 // sext (Y * SmallScale) = (sext Y) * Scale 1417 // some conditions need to hold however: SmallScale must sign-extend to 1418 // Scale and the multiplication Y * SmallScale should not overflow. 1419 if (SmallScale.sext(Scale.getBitWidth()) != Scale) 1420 // SmallScale does not sign-extend to Scale. 1421 return nullptr; 1422 assert(SmallScale.exactLogBase2() == logScale); 1423 // Require that Y * SmallScale must not overflow. 1424 RequireNoSignedWrap = true; 1425 1426 // Drill down through the cast. 1427 Parent = std::make_pair(Cast, 0); 1428 Scale = SmallScale; 1429 continue; 1430 } 1431 1432 if (Cast->getOpcode() == Instruction::Trunc) { 1433 // Op is truncated from a larger type, descale in the larger type. 1434 // Suppose Op = trunc X, and we descale X as Y * sext Scale. Then 1435 // trunc (Y * sext Scale) = (trunc Y) * Scale 1436 // always holds. However (trunc Y) * Scale may overflow even if 1437 // trunc (Y * sext Scale) does not, so nsw flags need to be cleared 1438 // from this point up in the expression (see later). 1439 if (RequireNoSignedWrap) 1440 return nullptr; 1441 1442 // Drill down through the cast. 1443 unsigned LargeSize = Cast->getSrcTy()->getPrimitiveSizeInBits(); 1444 Parent = std::make_pair(Cast, 0); 1445 Scale = Scale.sext(LargeSize); 1446 if (logScale + 1 == (int32_t)Cast->getType()->getPrimitiveSizeInBits()) 1447 logScale = -1; 1448 assert(Scale.exactLogBase2() == logScale); 1449 continue; 1450 } 1451 } 1452 1453 // Unsupported expression, bail out. 1454 return nullptr; 1455 } 1456 1457 // If Op is zero then Val = Op * Scale. 1458 if (match(Op, m_Zero())) { 1459 NoSignedWrap = true; 1460 return Op; 1461 } 1462 1463 // We know that we can successfully descale, so from here on we can safely 1464 // modify the IR. Op holds the descaled version of the deepest term in the 1465 // expression. NoSignedWrap is 'true' if multiplying Op by Scale is known 1466 // not to overflow. 1467 1468 if (!Parent.first) 1469 // The expression only had one term. 1470 return Op; 1471 1472 // Rewrite the parent using the descaled version of its operand. 1473 assert(Parent.first->hasOneUse() && "Drilled down when more than one use!"); 1474 assert(Op != Parent.first->getOperand(Parent.second) && 1475 "Descaling was a no-op?"); 1476 replaceOperand(*Parent.first, Parent.second, Op); 1477 Worklist.push(Parent.first); 1478 1479 // Now work back up the expression correcting nsw flags. The logic is based 1480 // on the following observation: if X * Y is known not to overflow as a signed 1481 // multiplication, and Y is replaced by a value Z with smaller absolute value, 1482 // then X * Z will not overflow as a signed multiplication either. As we work 1483 // our way up, having NoSignedWrap 'true' means that the descaled value at the 1484 // current level has strictly smaller absolute value than the original. 1485 Instruction *Ancestor = Parent.first; 1486 do { 1487 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(Ancestor)) { 1488 // If the multiplication wasn't nsw then we can't say anything about the 1489 // value of the descaled multiplication, and we have to clear nsw flags 1490 // from this point on up. 1491 bool OpNoSignedWrap = BO->hasNoSignedWrap(); 1492 NoSignedWrap &= OpNoSignedWrap; 1493 if (NoSignedWrap != OpNoSignedWrap) { 1494 BO->setHasNoSignedWrap(NoSignedWrap); 1495 Worklist.push(Ancestor); 1496 } 1497 } else if (Ancestor->getOpcode() == Instruction::Trunc) { 1498 // The fact that the descaled input to the trunc has smaller absolute 1499 // value than the original input doesn't tell us anything useful about 1500 // the absolute values of the truncations. 1501 NoSignedWrap = false; 1502 } 1503 assert((Ancestor->getOpcode() != Instruction::SExt || NoSignedWrap) && 1504 "Failed to keep proper track of nsw flags while drilling down?"); 1505 1506 if (Ancestor == Val) 1507 // Got to the top, all done! 1508 return Val; 1509 1510 // Move up one level in the expression. 1511 assert(Ancestor->hasOneUse() && "Drilled down when more than one use!"); 1512 Ancestor = Ancestor->user_back(); 1513 } while (true); 1514 } 1515 1516 Instruction *InstCombinerImpl::foldVectorBinop(BinaryOperator &Inst) { 1517 if (!isa<VectorType>(Inst.getType())) 1518 return nullptr; 1519 1520 BinaryOperator::BinaryOps Opcode = Inst.getOpcode(); 1521 Value *LHS = Inst.getOperand(0), *RHS = Inst.getOperand(1); 1522 assert(cast<VectorType>(LHS->getType())->getElementCount() == 1523 cast<VectorType>(Inst.getType())->getElementCount()); 1524 assert(cast<VectorType>(RHS->getType())->getElementCount() == 1525 cast<VectorType>(Inst.getType())->getElementCount()); 1526 1527 // If both operands of the binop are vector concatenations, then perform the 1528 // narrow binop on each pair of the source operands followed by concatenation 1529 // of the results. 1530 Value *L0, *L1, *R0, *R1; 1531 ArrayRef<int> Mask; 1532 if (match(LHS, m_Shuffle(m_Value(L0), m_Value(L1), m_Mask(Mask))) && 1533 match(RHS, m_Shuffle(m_Value(R0), m_Value(R1), m_SpecificMask(Mask))) && 1534 LHS->hasOneUse() && RHS->hasOneUse() && 1535 cast<ShuffleVectorInst>(LHS)->isConcat() && 1536 cast<ShuffleVectorInst>(RHS)->isConcat()) { 1537 // This transform does not have the speculative execution constraint as 1538 // below because the shuffle is a concatenation. The new binops are 1539 // operating on exactly the same elements as the existing binop. 1540 // TODO: We could ease the mask requirement to allow different undef lanes, 1541 // but that requires an analysis of the binop-with-undef output value. 1542 Value *NewBO0 = Builder.CreateBinOp(Opcode, L0, R0); 1543 if (auto *BO = dyn_cast<BinaryOperator>(NewBO0)) 1544 BO->copyIRFlags(&Inst); 1545 Value *NewBO1 = Builder.CreateBinOp(Opcode, L1, R1); 1546 if (auto *BO = dyn_cast<BinaryOperator>(NewBO1)) 1547 BO->copyIRFlags(&Inst); 1548 return new ShuffleVectorInst(NewBO0, NewBO1, Mask); 1549 } 1550 1551 // It may not be safe to reorder shuffles and things like div, urem, etc. 1552 // because we may trap when executing those ops on unknown vector elements. 1553 // See PR20059. 1554 if (!isSafeToSpeculativelyExecute(&Inst)) 1555 return nullptr; 1556 1557 auto createBinOpShuffle = [&](Value *X, Value *Y, ArrayRef<int> M) { 1558 Value *XY = Builder.CreateBinOp(Opcode, X, Y); 1559 if (auto *BO = dyn_cast<BinaryOperator>(XY)) 1560 BO->copyIRFlags(&Inst); 1561 return new ShuffleVectorInst(XY, UndefValue::get(XY->getType()), M); 1562 }; 1563 1564 // If both arguments of the binary operation are shuffles that use the same 1565 // mask and shuffle within a single vector, move the shuffle after the binop. 1566 Value *V1, *V2; 1567 if (match(LHS, m_Shuffle(m_Value(V1), m_Undef(), m_Mask(Mask))) && 1568 match(RHS, m_Shuffle(m_Value(V2), m_Undef(), m_SpecificMask(Mask))) && 1569 V1->getType() == V2->getType() && 1570 (LHS->hasOneUse() || RHS->hasOneUse() || LHS == RHS)) { 1571 // Op(shuffle(V1, Mask), shuffle(V2, Mask)) -> shuffle(Op(V1, V2), Mask) 1572 return createBinOpShuffle(V1, V2, Mask); 1573 } 1574 1575 // If both arguments of a commutative binop are select-shuffles that use the 1576 // same mask with commuted operands, the shuffles are unnecessary. 1577 if (Inst.isCommutative() && 1578 match(LHS, m_Shuffle(m_Value(V1), m_Value(V2), m_Mask(Mask))) && 1579 match(RHS, 1580 m_Shuffle(m_Specific(V2), m_Specific(V1), m_SpecificMask(Mask)))) { 1581 auto *LShuf = cast<ShuffleVectorInst>(LHS); 1582 auto *RShuf = cast<ShuffleVectorInst>(RHS); 1583 // TODO: Allow shuffles that contain undefs in the mask? 1584 // That is legal, but it reduces undef knowledge. 1585 // TODO: Allow arbitrary shuffles by shuffling after binop? 1586 // That might be legal, but we have to deal with poison. 1587 if (LShuf->isSelect() && 1588 !is_contained(LShuf->getShuffleMask(), UndefMaskElem) && 1589 RShuf->isSelect() && 1590 !is_contained(RShuf->getShuffleMask(), UndefMaskElem)) { 1591 // Example: 1592 // LHS = shuffle V1, V2, <0, 5, 6, 3> 1593 // RHS = shuffle V2, V1, <0, 5, 6, 3> 1594 // LHS + RHS --> (V10+V20, V21+V11, V22+V12, V13+V23) --> V1 + V2 1595 Instruction *NewBO = BinaryOperator::Create(Opcode, V1, V2); 1596 NewBO->copyIRFlags(&Inst); 1597 return NewBO; 1598 } 1599 } 1600 1601 // If one argument is a shuffle within one vector and the other is a constant, 1602 // try moving the shuffle after the binary operation. This canonicalization 1603 // intends to move shuffles closer to other shuffles and binops closer to 1604 // other binops, so they can be folded. It may also enable demanded elements 1605 // transforms. 1606 Constant *C; 1607 auto *InstVTy = dyn_cast<FixedVectorType>(Inst.getType()); 1608 if (InstVTy && 1609 match(&Inst, 1610 m_c_BinOp(m_OneUse(m_Shuffle(m_Value(V1), m_Undef(), m_Mask(Mask))), 1611 m_ImmConstant(C))) && 1612 cast<FixedVectorType>(V1->getType())->getNumElements() <= 1613 InstVTy->getNumElements()) { 1614 assert(InstVTy->getScalarType() == V1->getType()->getScalarType() && 1615 "Shuffle should not change scalar type"); 1616 1617 // Find constant NewC that has property: 1618 // shuffle(NewC, ShMask) = C 1619 // If such constant does not exist (example: ShMask=<0,0> and C=<1,2>) 1620 // reorder is not possible. A 1-to-1 mapping is not required. Example: 1621 // ShMask = <1,1,2,2> and C = <5,5,6,6> --> NewC = <undef,5,6,undef> 1622 bool ConstOp1 = isa<Constant>(RHS); 1623 ArrayRef<int> ShMask = Mask; 1624 unsigned SrcVecNumElts = 1625 cast<FixedVectorType>(V1->getType())->getNumElements(); 1626 UndefValue *UndefScalar = UndefValue::get(C->getType()->getScalarType()); 1627 SmallVector<Constant *, 16> NewVecC(SrcVecNumElts, UndefScalar); 1628 bool MayChange = true; 1629 unsigned NumElts = InstVTy->getNumElements(); 1630 for (unsigned I = 0; I < NumElts; ++I) { 1631 Constant *CElt = C->getAggregateElement(I); 1632 if (ShMask[I] >= 0) { 1633 assert(ShMask[I] < (int)NumElts && "Not expecting narrowing shuffle"); 1634 Constant *NewCElt = NewVecC[ShMask[I]]; 1635 // Bail out if: 1636 // 1. The constant vector contains a constant expression. 1637 // 2. The shuffle needs an element of the constant vector that can't 1638 // be mapped to a new constant vector. 1639 // 3. This is a widening shuffle that copies elements of V1 into the 1640 // extended elements (extending with undef is allowed). 1641 if (!CElt || (!isa<UndefValue>(NewCElt) && NewCElt != CElt) || 1642 I >= SrcVecNumElts) { 1643 MayChange = false; 1644 break; 1645 } 1646 NewVecC[ShMask[I]] = CElt; 1647 } 1648 // If this is a widening shuffle, we must be able to extend with undef 1649 // elements. If the original binop does not produce an undef in the high 1650 // lanes, then this transform is not safe. 1651 // Similarly for undef lanes due to the shuffle mask, we can only 1652 // transform binops that preserve undef. 1653 // TODO: We could shuffle those non-undef constant values into the 1654 // result by using a constant vector (rather than an undef vector) 1655 // as operand 1 of the new binop, but that might be too aggressive 1656 // for target-independent shuffle creation. 1657 if (I >= SrcVecNumElts || ShMask[I] < 0) { 1658 Constant *MaybeUndef = 1659 ConstOp1 ? ConstantExpr::get(Opcode, UndefScalar, CElt) 1660 : ConstantExpr::get(Opcode, CElt, UndefScalar); 1661 if (!isa<UndefValue>(MaybeUndef)) { 1662 MayChange = false; 1663 break; 1664 } 1665 } 1666 } 1667 if (MayChange) { 1668 Constant *NewC = ConstantVector::get(NewVecC); 1669 // It may not be safe to execute a binop on a vector with undef elements 1670 // because the entire instruction can be folded to undef or create poison 1671 // that did not exist in the original code. 1672 if (Inst.isIntDivRem() || (Inst.isShift() && ConstOp1)) 1673 NewC = getSafeVectorConstantForBinop(Opcode, NewC, ConstOp1); 1674 1675 // Op(shuffle(V1, Mask), C) -> shuffle(Op(V1, NewC), Mask) 1676 // Op(C, shuffle(V1, Mask)) -> shuffle(Op(NewC, V1), Mask) 1677 Value *NewLHS = ConstOp1 ? V1 : NewC; 1678 Value *NewRHS = ConstOp1 ? NewC : V1; 1679 return createBinOpShuffle(NewLHS, NewRHS, Mask); 1680 } 1681 } 1682 1683 // Try to reassociate to sink a splat shuffle after a binary operation. 1684 if (Inst.isAssociative() && Inst.isCommutative()) { 1685 // Canonicalize shuffle operand as LHS. 1686 if (isa<ShuffleVectorInst>(RHS)) 1687 std::swap(LHS, RHS); 1688 1689 Value *X; 1690 ArrayRef<int> MaskC; 1691 int SplatIndex; 1692 BinaryOperator *BO; 1693 if (!match(LHS, 1694 m_OneUse(m_Shuffle(m_Value(X), m_Undef(), m_Mask(MaskC)))) || 1695 !match(MaskC, m_SplatOrUndefMask(SplatIndex)) || 1696 X->getType() != Inst.getType() || !match(RHS, m_OneUse(m_BinOp(BO))) || 1697 BO->getOpcode() != Opcode) 1698 return nullptr; 1699 1700 // FIXME: This may not be safe if the analysis allows undef elements. By 1701 // moving 'Y' before the splat shuffle, we are implicitly assuming 1702 // that it is not undef/poison at the splat index. 1703 Value *Y, *OtherOp; 1704 if (isSplatValue(BO->getOperand(0), SplatIndex)) { 1705 Y = BO->getOperand(0); 1706 OtherOp = BO->getOperand(1); 1707 } else if (isSplatValue(BO->getOperand(1), SplatIndex)) { 1708 Y = BO->getOperand(1); 1709 OtherOp = BO->getOperand(0); 1710 } else { 1711 return nullptr; 1712 } 1713 1714 // X and Y are splatted values, so perform the binary operation on those 1715 // values followed by a splat followed by the 2nd binary operation: 1716 // bo (splat X), (bo Y, OtherOp) --> bo (splat (bo X, Y)), OtherOp 1717 Value *NewBO = Builder.CreateBinOp(Opcode, X, Y); 1718 SmallVector<int, 8> NewMask(MaskC.size(), SplatIndex); 1719 Value *NewSplat = Builder.CreateShuffleVector(NewBO, NewMask); 1720 Instruction *R = BinaryOperator::Create(Opcode, NewSplat, OtherOp); 1721 1722 // Intersect FMF on both new binops. Other (poison-generating) flags are 1723 // dropped to be safe. 1724 if (isa<FPMathOperator>(R)) { 1725 R->copyFastMathFlags(&Inst); 1726 R->andIRFlags(BO); 1727 } 1728 if (auto *NewInstBO = dyn_cast<BinaryOperator>(NewBO)) 1729 NewInstBO->copyIRFlags(R); 1730 return R; 1731 } 1732 1733 return nullptr; 1734 } 1735 1736 /// Try to narrow the width of a binop if at least 1 operand is an extend of 1737 /// of a value. This requires a potentially expensive known bits check to make 1738 /// sure the narrow op does not overflow. 1739 Instruction *InstCombinerImpl::narrowMathIfNoOverflow(BinaryOperator &BO) { 1740 // We need at least one extended operand. 1741 Value *Op0 = BO.getOperand(0), *Op1 = BO.getOperand(1); 1742 1743 // If this is a sub, we swap the operands since we always want an extension 1744 // on the RHS. The LHS can be an extension or a constant. 1745 if (BO.getOpcode() == Instruction::Sub) 1746 std::swap(Op0, Op1); 1747 1748 Value *X; 1749 bool IsSext = match(Op0, m_SExt(m_Value(X))); 1750 if (!IsSext && !match(Op0, m_ZExt(m_Value(X)))) 1751 return nullptr; 1752 1753 // If both operands are the same extension from the same source type and we 1754 // can eliminate at least one (hasOneUse), this might work. 1755 CastInst::CastOps CastOpc = IsSext ? Instruction::SExt : Instruction::ZExt; 1756 Value *Y; 1757 if (!(match(Op1, m_ZExtOrSExt(m_Value(Y))) && X->getType() == Y->getType() && 1758 cast<Operator>(Op1)->getOpcode() == CastOpc && 1759 (Op0->hasOneUse() || Op1->hasOneUse()))) { 1760 // If that did not match, see if we have a suitable constant operand. 1761 // Truncating and extending must produce the same constant. 1762 Constant *WideC; 1763 if (!Op0->hasOneUse() || !match(Op1, m_Constant(WideC))) 1764 return nullptr; 1765 Constant *NarrowC = ConstantExpr::getTrunc(WideC, X->getType()); 1766 if (ConstantExpr::getCast(CastOpc, NarrowC, BO.getType()) != WideC) 1767 return nullptr; 1768 Y = NarrowC; 1769 } 1770 1771 // Swap back now that we found our operands. 1772 if (BO.getOpcode() == Instruction::Sub) 1773 std::swap(X, Y); 1774 1775 // Both operands have narrow versions. Last step: the math must not overflow 1776 // in the narrow width. 1777 if (!willNotOverflow(BO.getOpcode(), X, Y, BO, IsSext)) 1778 return nullptr; 1779 1780 // bo (ext X), (ext Y) --> ext (bo X, Y) 1781 // bo (ext X), C --> ext (bo X, C') 1782 Value *NarrowBO = Builder.CreateBinOp(BO.getOpcode(), X, Y, "narrow"); 1783 if (auto *NewBinOp = dyn_cast<BinaryOperator>(NarrowBO)) { 1784 if (IsSext) 1785 NewBinOp->setHasNoSignedWrap(); 1786 else 1787 NewBinOp->setHasNoUnsignedWrap(); 1788 } 1789 return CastInst::Create(CastOpc, NarrowBO, BO.getType()); 1790 } 1791 1792 static bool isMergedGEPInBounds(GEPOperator &GEP1, GEPOperator &GEP2) { 1793 // At least one GEP must be inbounds. 1794 if (!GEP1.isInBounds() && !GEP2.isInBounds()) 1795 return false; 1796 1797 return (GEP1.isInBounds() || GEP1.hasAllZeroIndices()) && 1798 (GEP2.isInBounds() || GEP2.hasAllZeroIndices()); 1799 } 1800 1801 /// Thread a GEP operation with constant indices through the constant true/false 1802 /// arms of a select. 1803 static Instruction *foldSelectGEP(GetElementPtrInst &GEP, 1804 InstCombiner::BuilderTy &Builder) { 1805 if (!GEP.hasAllConstantIndices()) 1806 return nullptr; 1807 1808 Instruction *Sel; 1809 Value *Cond; 1810 Constant *TrueC, *FalseC; 1811 if (!match(GEP.getPointerOperand(), m_Instruction(Sel)) || 1812 !match(Sel, 1813 m_Select(m_Value(Cond), m_Constant(TrueC), m_Constant(FalseC)))) 1814 return nullptr; 1815 1816 // gep (select Cond, TrueC, FalseC), IndexC --> select Cond, TrueC', FalseC' 1817 // Propagate 'inbounds' and metadata from existing instructions. 1818 // Note: using IRBuilder to create the constants for efficiency. 1819 SmallVector<Value *, 4> IndexC(GEP.indices()); 1820 bool IsInBounds = GEP.isInBounds(); 1821 Value *NewTrueC = IsInBounds ? Builder.CreateInBoundsGEP(TrueC, IndexC) 1822 : Builder.CreateGEP(TrueC, IndexC); 1823 Value *NewFalseC = IsInBounds ? Builder.CreateInBoundsGEP(FalseC, IndexC) 1824 : Builder.CreateGEP(FalseC, IndexC); 1825 return SelectInst::Create(Cond, NewTrueC, NewFalseC, "", nullptr, Sel); 1826 } 1827 1828 Instruction *InstCombinerImpl::visitGetElementPtrInst(GetElementPtrInst &GEP) { 1829 SmallVector<Value *, 8> Ops(GEP.operands()); 1830 Type *GEPType = GEP.getType(); 1831 Type *GEPEltType = GEP.getSourceElementType(); 1832 bool IsGEPSrcEleScalable = isa<ScalableVectorType>(GEPEltType); 1833 if (Value *V = SimplifyGEPInst(GEPEltType, Ops, SQ.getWithInstruction(&GEP))) 1834 return replaceInstUsesWith(GEP, V); 1835 1836 // For vector geps, use the generic demanded vector support. 1837 // Skip if GEP return type is scalable. The number of elements is unknown at 1838 // compile-time. 1839 if (auto *GEPFVTy = dyn_cast<FixedVectorType>(GEPType)) { 1840 auto VWidth = GEPFVTy->getNumElements(); 1841 APInt UndefElts(VWidth, 0); 1842 APInt AllOnesEltMask(APInt::getAllOnesValue(VWidth)); 1843 if (Value *V = SimplifyDemandedVectorElts(&GEP, AllOnesEltMask, 1844 UndefElts)) { 1845 if (V != &GEP) 1846 return replaceInstUsesWith(GEP, V); 1847 return &GEP; 1848 } 1849 1850 // TODO: 1) Scalarize splat operands, 2) scalarize entire instruction if 1851 // possible (decide on canonical form for pointer broadcast), 3) exploit 1852 // undef elements to decrease demanded bits 1853 } 1854 1855 Value *PtrOp = GEP.getOperand(0); 1856 1857 // Eliminate unneeded casts for indices, and replace indices which displace 1858 // by multiples of a zero size type with zero. 1859 bool MadeChange = false; 1860 1861 // Index width may not be the same width as pointer width. 1862 // Data layout chooses the right type based on supported integer types. 1863 Type *NewScalarIndexTy = 1864 DL.getIndexType(GEP.getPointerOperandType()->getScalarType()); 1865 1866 gep_type_iterator GTI = gep_type_begin(GEP); 1867 for (User::op_iterator I = GEP.op_begin() + 1, E = GEP.op_end(); I != E; 1868 ++I, ++GTI) { 1869 // Skip indices into struct types. 1870 if (GTI.isStruct()) 1871 continue; 1872 1873 Type *IndexTy = (*I)->getType(); 1874 Type *NewIndexType = 1875 IndexTy->isVectorTy() 1876 ? VectorType::get(NewScalarIndexTy, 1877 cast<VectorType>(IndexTy)->getElementCount()) 1878 : NewScalarIndexTy; 1879 1880 // If the element type has zero size then any index over it is equivalent 1881 // to an index of zero, so replace it with zero if it is not zero already. 1882 Type *EltTy = GTI.getIndexedType(); 1883 if (EltTy->isSized() && DL.getTypeAllocSize(EltTy).isZero()) 1884 if (!isa<Constant>(*I) || !match(I->get(), m_Zero())) { 1885 *I = Constant::getNullValue(NewIndexType); 1886 MadeChange = true; 1887 } 1888 1889 if (IndexTy != NewIndexType) { 1890 // If we are using a wider index than needed for this platform, shrink 1891 // it to what we need. If narrower, sign-extend it to what we need. 1892 // This explicit cast can make subsequent optimizations more obvious. 1893 *I = Builder.CreateIntCast(*I, NewIndexType, true); 1894 MadeChange = true; 1895 } 1896 } 1897 if (MadeChange) 1898 return &GEP; 1899 1900 // Check to see if the inputs to the PHI node are getelementptr instructions. 1901 if (auto *PN = dyn_cast<PHINode>(PtrOp)) { 1902 auto *Op1 = dyn_cast<GetElementPtrInst>(PN->getOperand(0)); 1903 if (!Op1) 1904 return nullptr; 1905 1906 // Don't fold a GEP into itself through a PHI node. This can only happen 1907 // through the back-edge of a loop. Folding a GEP into itself means that 1908 // the value of the previous iteration needs to be stored in the meantime, 1909 // thus requiring an additional register variable to be live, but not 1910 // actually achieving anything (the GEP still needs to be executed once per 1911 // loop iteration). 1912 if (Op1 == &GEP) 1913 return nullptr; 1914 1915 int DI = -1; 1916 1917 for (auto I = PN->op_begin()+1, E = PN->op_end(); I !=E; ++I) { 1918 auto *Op2 = dyn_cast<GetElementPtrInst>(*I); 1919 if (!Op2 || Op1->getNumOperands() != Op2->getNumOperands()) 1920 return nullptr; 1921 1922 // As for Op1 above, don't try to fold a GEP into itself. 1923 if (Op2 == &GEP) 1924 return nullptr; 1925 1926 // Keep track of the type as we walk the GEP. 1927 Type *CurTy = nullptr; 1928 1929 for (unsigned J = 0, F = Op1->getNumOperands(); J != F; ++J) { 1930 if (Op1->getOperand(J)->getType() != Op2->getOperand(J)->getType()) 1931 return nullptr; 1932 1933 if (Op1->getOperand(J) != Op2->getOperand(J)) { 1934 if (DI == -1) { 1935 // We have not seen any differences yet in the GEPs feeding the 1936 // PHI yet, so we record this one if it is allowed to be a 1937 // variable. 1938 1939 // The first two arguments can vary for any GEP, the rest have to be 1940 // static for struct slots 1941 if (J > 1) { 1942 assert(CurTy && "No current type?"); 1943 if (CurTy->isStructTy()) 1944 return nullptr; 1945 } 1946 1947 DI = J; 1948 } else { 1949 // The GEP is different by more than one input. While this could be 1950 // extended to support GEPs that vary by more than one variable it 1951 // doesn't make sense since it greatly increases the complexity and 1952 // would result in an R+R+R addressing mode which no backend 1953 // directly supports and would need to be broken into several 1954 // simpler instructions anyway. 1955 return nullptr; 1956 } 1957 } 1958 1959 // Sink down a layer of the type for the next iteration. 1960 if (J > 0) { 1961 if (J == 1) { 1962 CurTy = Op1->getSourceElementType(); 1963 } else { 1964 CurTy = 1965 GetElementPtrInst::getTypeAtIndex(CurTy, Op1->getOperand(J)); 1966 } 1967 } 1968 } 1969 } 1970 1971 // If not all GEPs are identical we'll have to create a new PHI node. 1972 // Check that the old PHI node has only one use so that it will get 1973 // removed. 1974 if (DI != -1 && !PN->hasOneUse()) 1975 return nullptr; 1976 1977 auto *NewGEP = cast<GetElementPtrInst>(Op1->clone()); 1978 if (DI == -1) { 1979 // All the GEPs feeding the PHI are identical. Clone one down into our 1980 // BB so that it can be merged with the current GEP. 1981 } else { 1982 // All the GEPs feeding the PHI differ at a single offset. Clone a GEP 1983 // into the current block so it can be merged, and create a new PHI to 1984 // set that index. 1985 PHINode *NewPN; 1986 { 1987 IRBuilderBase::InsertPointGuard Guard(Builder); 1988 Builder.SetInsertPoint(PN); 1989 NewPN = Builder.CreatePHI(Op1->getOperand(DI)->getType(), 1990 PN->getNumOperands()); 1991 } 1992 1993 for (auto &I : PN->operands()) 1994 NewPN->addIncoming(cast<GEPOperator>(I)->getOperand(DI), 1995 PN->getIncomingBlock(I)); 1996 1997 NewGEP->setOperand(DI, NewPN); 1998 } 1999 2000 GEP.getParent()->getInstList().insert( 2001 GEP.getParent()->getFirstInsertionPt(), NewGEP); 2002 replaceOperand(GEP, 0, NewGEP); 2003 PtrOp = NewGEP; 2004 } 2005 2006 // Combine Indices - If the source pointer to this getelementptr instruction 2007 // is a getelementptr instruction, combine the indices of the two 2008 // getelementptr instructions into a single instruction. 2009 if (auto *Src = dyn_cast<GEPOperator>(PtrOp)) { 2010 if (!shouldMergeGEPs(*cast<GEPOperator>(&GEP), *Src)) 2011 return nullptr; 2012 2013 // Try to reassociate loop invariant GEP chains to enable LICM. 2014 if (LI && Src->getNumOperands() == 2 && GEP.getNumOperands() == 2 && 2015 Src->hasOneUse()) { 2016 if (Loop *L = LI->getLoopFor(GEP.getParent())) { 2017 Value *GO1 = GEP.getOperand(1); 2018 Value *SO1 = Src->getOperand(1); 2019 // Reassociate the two GEPs if SO1 is variant in the loop and GO1 is 2020 // invariant: this breaks the dependence between GEPs and allows LICM 2021 // to hoist the invariant part out of the loop. 2022 if (L->isLoopInvariant(GO1) && !L->isLoopInvariant(SO1)) { 2023 // We have to be careful here. 2024 // We have something like: 2025 // %src = getelementptr <ty>, <ty>* %base, <ty> %idx 2026 // %gep = getelementptr <ty>, <ty>* %src, <ty> %idx2 2027 // If we just swap idx & idx2 then we could inadvertantly 2028 // change %src from a vector to a scalar, or vice versa. 2029 // Cases: 2030 // 1) %base a scalar & idx a scalar & idx2 a vector 2031 // => Swapping idx & idx2 turns %src into a vector type. 2032 // 2) %base a scalar & idx a vector & idx2 a scalar 2033 // => Swapping idx & idx2 turns %src in a scalar type 2034 // 3) %base, %idx, and %idx2 are scalars 2035 // => %src & %gep are scalars 2036 // => swapping idx & idx2 is safe 2037 // 4) %base a vector 2038 // => %src is a vector 2039 // => swapping idx & idx2 is safe. 2040 auto *SO0 = Src->getOperand(0); 2041 auto *SO0Ty = SO0->getType(); 2042 if (!isa<VectorType>(GEPType) || // case 3 2043 isa<VectorType>(SO0Ty)) { // case 4 2044 Src->setOperand(1, GO1); 2045 GEP.setOperand(1, SO1); 2046 return &GEP; 2047 } else { 2048 // Case 1 or 2 2049 // -- have to recreate %src & %gep 2050 // put NewSrc at same location as %src 2051 Builder.SetInsertPoint(cast<Instruction>(PtrOp)); 2052 auto *NewSrc = cast<GetElementPtrInst>( 2053 Builder.CreateGEP(GEPEltType, SO0, GO1, Src->getName())); 2054 NewSrc->setIsInBounds(Src->isInBounds()); 2055 auto *NewGEP = GetElementPtrInst::Create(GEPEltType, NewSrc, {SO1}); 2056 NewGEP->setIsInBounds(GEP.isInBounds()); 2057 return NewGEP; 2058 } 2059 } 2060 } 2061 } 2062 2063 // Note that if our source is a gep chain itself then we wait for that 2064 // chain to be resolved before we perform this transformation. This 2065 // avoids us creating a TON of code in some cases. 2066 if (auto *SrcGEP = dyn_cast<GEPOperator>(Src->getOperand(0))) 2067 if (SrcGEP->getNumOperands() == 2 && shouldMergeGEPs(*Src, *SrcGEP)) 2068 return nullptr; // Wait until our source is folded to completion. 2069 2070 SmallVector<Value*, 8> Indices; 2071 2072 // Find out whether the last index in the source GEP is a sequential idx. 2073 bool EndsWithSequential = false; 2074 for (gep_type_iterator I = gep_type_begin(*Src), E = gep_type_end(*Src); 2075 I != E; ++I) 2076 EndsWithSequential = I.isSequential(); 2077 2078 // Can we combine the two pointer arithmetics offsets? 2079 if (EndsWithSequential) { 2080 // Replace: gep (gep %P, long B), long A, ... 2081 // With: T = long A+B; gep %P, T, ... 2082 Value *SO1 = Src->getOperand(Src->getNumOperands()-1); 2083 Value *GO1 = GEP.getOperand(1); 2084 2085 // If they aren't the same type, then the input hasn't been processed 2086 // by the loop above yet (which canonicalizes sequential index types to 2087 // intptr_t). Just avoid transforming this until the input has been 2088 // normalized. 2089 if (SO1->getType() != GO1->getType()) 2090 return nullptr; 2091 2092 Value *Sum = 2093 SimplifyAddInst(GO1, SO1, false, false, SQ.getWithInstruction(&GEP)); 2094 // Only do the combine when we are sure the cost after the 2095 // merge is never more than that before the merge. 2096 if (Sum == nullptr) 2097 return nullptr; 2098 2099 // Update the GEP in place if possible. 2100 if (Src->getNumOperands() == 2) { 2101 GEP.setIsInBounds(isMergedGEPInBounds(*Src, *cast<GEPOperator>(&GEP))); 2102 replaceOperand(GEP, 0, Src->getOperand(0)); 2103 replaceOperand(GEP, 1, Sum); 2104 return &GEP; 2105 } 2106 Indices.append(Src->op_begin()+1, Src->op_end()-1); 2107 Indices.push_back(Sum); 2108 Indices.append(GEP.op_begin()+2, GEP.op_end()); 2109 } else if (isa<Constant>(*GEP.idx_begin()) && 2110 cast<Constant>(*GEP.idx_begin())->isNullValue() && 2111 Src->getNumOperands() != 1) { 2112 // Otherwise we can do the fold if the first index of the GEP is a zero 2113 Indices.append(Src->op_begin()+1, Src->op_end()); 2114 Indices.append(GEP.idx_begin()+1, GEP.idx_end()); 2115 } 2116 2117 if (!Indices.empty()) 2118 return isMergedGEPInBounds(*Src, *cast<GEPOperator>(&GEP)) 2119 ? GetElementPtrInst::CreateInBounds( 2120 Src->getSourceElementType(), Src->getOperand(0), Indices, 2121 GEP.getName()) 2122 : GetElementPtrInst::Create(Src->getSourceElementType(), 2123 Src->getOperand(0), Indices, 2124 GEP.getName()); 2125 } 2126 2127 // Skip if GEP source element type is scalable. The type alloc size is unknown 2128 // at compile-time. 2129 if (GEP.getNumIndices() == 1 && !IsGEPSrcEleScalable) { 2130 unsigned AS = GEP.getPointerAddressSpace(); 2131 if (GEP.getOperand(1)->getType()->getScalarSizeInBits() == 2132 DL.getIndexSizeInBits(AS)) { 2133 uint64_t TyAllocSize = DL.getTypeAllocSize(GEPEltType).getFixedSize(); 2134 2135 bool Matched = false; 2136 uint64_t C; 2137 Value *V = nullptr; 2138 if (TyAllocSize == 1) { 2139 V = GEP.getOperand(1); 2140 Matched = true; 2141 } else if (match(GEP.getOperand(1), 2142 m_AShr(m_Value(V), m_ConstantInt(C)))) { 2143 if (TyAllocSize == 1ULL << C) 2144 Matched = true; 2145 } else if (match(GEP.getOperand(1), 2146 m_SDiv(m_Value(V), m_ConstantInt(C)))) { 2147 if (TyAllocSize == C) 2148 Matched = true; 2149 } 2150 2151 if (Matched) { 2152 // Canonicalize (gep i8* X, -(ptrtoint Y)) 2153 // to (inttoptr (sub (ptrtoint X), (ptrtoint Y))) 2154 // The GEP pattern is emitted by the SCEV expander for certain kinds of 2155 // pointer arithmetic. 2156 if (match(V, m_Neg(m_PtrToInt(m_Value())))) { 2157 Operator *Index = cast<Operator>(V); 2158 Value *PtrToInt = Builder.CreatePtrToInt(PtrOp, Index->getType()); 2159 Value *NewSub = Builder.CreateSub(PtrToInt, Index->getOperand(1)); 2160 return CastInst::Create(Instruction::IntToPtr, NewSub, GEPType); 2161 } 2162 // Canonicalize (gep i8* X, (ptrtoint Y)-(ptrtoint X)) 2163 // to (bitcast Y) 2164 Value *Y; 2165 if (match(V, m_Sub(m_PtrToInt(m_Value(Y)), 2166 m_PtrToInt(m_Specific(GEP.getOperand(0)))))) 2167 return CastInst::CreatePointerBitCastOrAddrSpaceCast(Y, GEPType); 2168 } 2169 } 2170 } 2171 2172 // We do not handle pointer-vector geps here. 2173 if (GEPType->isVectorTy()) 2174 return nullptr; 2175 2176 // Handle gep(bitcast x) and gep(gep x, 0, 0, 0). 2177 Value *StrippedPtr = PtrOp->stripPointerCasts(); 2178 PointerType *StrippedPtrTy = cast<PointerType>(StrippedPtr->getType()); 2179 2180 if (StrippedPtr != PtrOp) { 2181 bool HasZeroPointerIndex = false; 2182 Type *StrippedPtrEltTy = StrippedPtrTy->getElementType(); 2183 2184 if (auto *C = dyn_cast<ConstantInt>(GEP.getOperand(1))) 2185 HasZeroPointerIndex = C->isZero(); 2186 2187 // Transform: GEP (bitcast [10 x i8]* X to [0 x i8]*), i32 0, ... 2188 // into : GEP [10 x i8]* X, i32 0, ... 2189 // 2190 // Likewise, transform: GEP (bitcast i8* X to [0 x i8]*), i32 0, ... 2191 // into : GEP i8* X, ... 2192 // 2193 // This occurs when the program declares an array extern like "int X[];" 2194 if (HasZeroPointerIndex) { 2195 if (auto *CATy = dyn_cast<ArrayType>(GEPEltType)) { 2196 // GEP (bitcast i8* X to [0 x i8]*), i32 0, ... ? 2197 if (CATy->getElementType() == StrippedPtrEltTy) { 2198 // -> GEP i8* X, ... 2199 SmallVector<Value*, 8> Idx(GEP.idx_begin()+1, GEP.idx_end()); 2200 GetElementPtrInst *Res = GetElementPtrInst::Create( 2201 StrippedPtrEltTy, StrippedPtr, Idx, GEP.getName()); 2202 Res->setIsInBounds(GEP.isInBounds()); 2203 if (StrippedPtrTy->getAddressSpace() == GEP.getAddressSpace()) 2204 return Res; 2205 // Insert Res, and create an addrspacecast. 2206 // e.g., 2207 // GEP (addrspacecast i8 addrspace(1)* X to [0 x i8]*), i32 0, ... 2208 // -> 2209 // %0 = GEP i8 addrspace(1)* X, ... 2210 // addrspacecast i8 addrspace(1)* %0 to i8* 2211 return new AddrSpaceCastInst(Builder.Insert(Res), GEPType); 2212 } 2213 2214 if (auto *XATy = dyn_cast<ArrayType>(StrippedPtrEltTy)) { 2215 // GEP (bitcast [10 x i8]* X to [0 x i8]*), i32 0, ... ? 2216 if (CATy->getElementType() == XATy->getElementType()) { 2217 // -> GEP [10 x i8]* X, i32 0, ... 2218 // At this point, we know that the cast source type is a pointer 2219 // to an array of the same type as the destination pointer 2220 // array. Because the array type is never stepped over (there 2221 // is a leading zero) we can fold the cast into this GEP. 2222 if (StrippedPtrTy->getAddressSpace() == GEP.getAddressSpace()) { 2223 GEP.setSourceElementType(XATy); 2224 return replaceOperand(GEP, 0, StrippedPtr); 2225 } 2226 // Cannot replace the base pointer directly because StrippedPtr's 2227 // address space is different. Instead, create a new GEP followed by 2228 // an addrspacecast. 2229 // e.g., 2230 // GEP (addrspacecast [10 x i8] addrspace(1)* X to [0 x i8]*), 2231 // i32 0, ... 2232 // -> 2233 // %0 = GEP [10 x i8] addrspace(1)* X, ... 2234 // addrspacecast i8 addrspace(1)* %0 to i8* 2235 SmallVector<Value *, 8> Idx(GEP.indices()); 2236 Value *NewGEP = 2237 GEP.isInBounds() 2238 ? Builder.CreateInBoundsGEP(StrippedPtrEltTy, StrippedPtr, 2239 Idx, GEP.getName()) 2240 : Builder.CreateGEP(StrippedPtrEltTy, StrippedPtr, Idx, 2241 GEP.getName()); 2242 return new AddrSpaceCastInst(NewGEP, GEPType); 2243 } 2244 } 2245 } 2246 } else if (GEP.getNumOperands() == 2 && !IsGEPSrcEleScalable) { 2247 // Skip if GEP source element type is scalable. The type alloc size is 2248 // unknown at compile-time. 2249 // Transform things like: %t = getelementptr i32* 2250 // bitcast ([2 x i32]* %str to i32*), i32 %V into: %t1 = getelementptr [2 2251 // x i32]* %str, i32 0, i32 %V; bitcast 2252 if (StrippedPtrEltTy->isArrayTy() && 2253 DL.getTypeAllocSize(StrippedPtrEltTy->getArrayElementType()) == 2254 DL.getTypeAllocSize(GEPEltType)) { 2255 Type *IdxType = DL.getIndexType(GEPType); 2256 Value *Idx[2] = { Constant::getNullValue(IdxType), GEP.getOperand(1) }; 2257 Value *NewGEP = 2258 GEP.isInBounds() 2259 ? Builder.CreateInBoundsGEP(StrippedPtrEltTy, StrippedPtr, Idx, 2260 GEP.getName()) 2261 : Builder.CreateGEP(StrippedPtrEltTy, StrippedPtr, Idx, 2262 GEP.getName()); 2263 2264 // V and GEP are both pointer types --> BitCast 2265 return CastInst::CreatePointerBitCastOrAddrSpaceCast(NewGEP, GEPType); 2266 } 2267 2268 // Transform things like: 2269 // %V = mul i64 %N, 4 2270 // %t = getelementptr i8* bitcast (i32* %arr to i8*), i32 %V 2271 // into: %t1 = getelementptr i32* %arr, i32 %N; bitcast 2272 if (GEPEltType->isSized() && StrippedPtrEltTy->isSized()) { 2273 // Check that changing the type amounts to dividing the index by a scale 2274 // factor. 2275 uint64_t ResSize = DL.getTypeAllocSize(GEPEltType).getFixedSize(); 2276 uint64_t SrcSize = DL.getTypeAllocSize(StrippedPtrEltTy).getFixedSize(); 2277 if (ResSize && SrcSize % ResSize == 0) { 2278 Value *Idx = GEP.getOperand(1); 2279 unsigned BitWidth = Idx->getType()->getPrimitiveSizeInBits(); 2280 uint64_t Scale = SrcSize / ResSize; 2281 2282 // Earlier transforms ensure that the index has the right type 2283 // according to Data Layout, which considerably simplifies the 2284 // logic by eliminating implicit casts. 2285 assert(Idx->getType() == DL.getIndexType(GEPType) && 2286 "Index type does not match the Data Layout preferences"); 2287 2288 bool NSW; 2289 if (Value *NewIdx = Descale(Idx, APInt(BitWidth, Scale), NSW)) { 2290 // Successfully decomposed Idx as NewIdx * Scale, form a new GEP. 2291 // If the multiplication NewIdx * Scale may overflow then the new 2292 // GEP may not be "inbounds". 2293 Value *NewGEP = 2294 GEP.isInBounds() && NSW 2295 ? Builder.CreateInBoundsGEP(StrippedPtrEltTy, StrippedPtr, 2296 NewIdx, GEP.getName()) 2297 : Builder.CreateGEP(StrippedPtrEltTy, StrippedPtr, NewIdx, 2298 GEP.getName()); 2299 2300 // The NewGEP must be pointer typed, so must the old one -> BitCast 2301 return CastInst::CreatePointerBitCastOrAddrSpaceCast(NewGEP, 2302 GEPType); 2303 } 2304 } 2305 } 2306 2307 // Similarly, transform things like: 2308 // getelementptr i8* bitcast ([100 x double]* X to i8*), i32 %tmp 2309 // (where tmp = 8*tmp2) into: 2310 // getelementptr [100 x double]* %arr, i32 0, i32 %tmp2; bitcast 2311 if (GEPEltType->isSized() && StrippedPtrEltTy->isSized() && 2312 StrippedPtrEltTy->isArrayTy()) { 2313 // Check that changing to the array element type amounts to dividing the 2314 // index by a scale factor. 2315 uint64_t ResSize = DL.getTypeAllocSize(GEPEltType).getFixedSize(); 2316 uint64_t ArrayEltSize = 2317 DL.getTypeAllocSize(StrippedPtrEltTy->getArrayElementType()) 2318 .getFixedSize(); 2319 if (ResSize && ArrayEltSize % ResSize == 0) { 2320 Value *Idx = GEP.getOperand(1); 2321 unsigned BitWidth = Idx->getType()->getPrimitiveSizeInBits(); 2322 uint64_t Scale = ArrayEltSize / ResSize; 2323 2324 // Earlier transforms ensure that the index has the right type 2325 // according to the Data Layout, which considerably simplifies 2326 // the logic by eliminating implicit casts. 2327 assert(Idx->getType() == DL.getIndexType(GEPType) && 2328 "Index type does not match the Data Layout preferences"); 2329 2330 bool NSW; 2331 if (Value *NewIdx = Descale(Idx, APInt(BitWidth, Scale), NSW)) { 2332 // Successfully decomposed Idx as NewIdx * Scale, form a new GEP. 2333 // If the multiplication NewIdx * Scale may overflow then the new 2334 // GEP may not be "inbounds". 2335 Type *IndTy = DL.getIndexType(GEPType); 2336 Value *Off[2] = {Constant::getNullValue(IndTy), NewIdx}; 2337 2338 Value *NewGEP = 2339 GEP.isInBounds() && NSW 2340 ? Builder.CreateInBoundsGEP(StrippedPtrEltTy, StrippedPtr, 2341 Off, GEP.getName()) 2342 : Builder.CreateGEP(StrippedPtrEltTy, StrippedPtr, Off, 2343 GEP.getName()); 2344 // The NewGEP must be pointer typed, so must the old one -> BitCast 2345 return CastInst::CreatePointerBitCastOrAddrSpaceCast(NewGEP, 2346 GEPType); 2347 } 2348 } 2349 } 2350 } 2351 } 2352 2353 // addrspacecast between types is canonicalized as a bitcast, then an 2354 // addrspacecast. To take advantage of the below bitcast + struct GEP, look 2355 // through the addrspacecast. 2356 Value *ASCStrippedPtrOp = PtrOp; 2357 if (auto *ASC = dyn_cast<AddrSpaceCastInst>(PtrOp)) { 2358 // X = bitcast A addrspace(1)* to B addrspace(1)* 2359 // Y = addrspacecast A addrspace(1)* to B addrspace(2)* 2360 // Z = gep Y, <...constant indices...> 2361 // Into an addrspacecasted GEP of the struct. 2362 if (auto *BC = dyn_cast<BitCastInst>(ASC->getOperand(0))) 2363 ASCStrippedPtrOp = BC; 2364 } 2365 2366 if (auto *BCI = dyn_cast<BitCastInst>(ASCStrippedPtrOp)) { 2367 Value *SrcOp = BCI->getOperand(0); 2368 PointerType *SrcType = cast<PointerType>(BCI->getSrcTy()); 2369 Type *SrcEltType = SrcType->getElementType(); 2370 2371 // GEP directly using the source operand if this GEP is accessing an element 2372 // of a bitcasted pointer to vector or array of the same dimensions: 2373 // gep (bitcast <c x ty>* X to [c x ty]*), Y, Z --> gep X, Y, Z 2374 // gep (bitcast [c x ty]* X to <c x ty>*), Y, Z --> gep X, Y, Z 2375 auto areMatchingArrayAndVecTypes = [](Type *ArrTy, Type *VecTy, 2376 const DataLayout &DL) { 2377 auto *VecVTy = cast<FixedVectorType>(VecTy); 2378 return ArrTy->getArrayElementType() == VecVTy->getElementType() && 2379 ArrTy->getArrayNumElements() == VecVTy->getNumElements() && 2380 DL.getTypeAllocSize(ArrTy) == DL.getTypeAllocSize(VecTy); 2381 }; 2382 if (GEP.getNumOperands() == 3 && 2383 ((GEPEltType->isArrayTy() && isa<FixedVectorType>(SrcEltType) && 2384 areMatchingArrayAndVecTypes(GEPEltType, SrcEltType, DL)) || 2385 (isa<FixedVectorType>(GEPEltType) && SrcEltType->isArrayTy() && 2386 areMatchingArrayAndVecTypes(SrcEltType, GEPEltType, DL)))) { 2387 2388 // Create a new GEP here, as using `setOperand()` followed by 2389 // `setSourceElementType()` won't actually update the type of the 2390 // existing GEP Value. Causing issues if this Value is accessed when 2391 // constructing an AddrSpaceCastInst 2392 Value *NGEP = 2393 GEP.isInBounds() 2394 ? Builder.CreateInBoundsGEP(SrcEltType, SrcOp, {Ops[1], Ops[2]}) 2395 : Builder.CreateGEP(SrcEltType, SrcOp, {Ops[1], Ops[2]}); 2396 NGEP->takeName(&GEP); 2397 2398 // Preserve GEP address space to satisfy users 2399 if (NGEP->getType()->getPointerAddressSpace() != GEP.getAddressSpace()) 2400 return new AddrSpaceCastInst(NGEP, GEPType); 2401 2402 return replaceInstUsesWith(GEP, NGEP); 2403 } 2404 2405 // See if we can simplify: 2406 // X = bitcast A* to B* 2407 // Y = gep X, <...constant indices...> 2408 // into a gep of the original struct. This is important for SROA and alias 2409 // analysis of unions. If "A" is also a bitcast, wait for A/X to be merged. 2410 unsigned OffsetBits = DL.getIndexTypeSizeInBits(GEPType); 2411 APInt Offset(OffsetBits, 0); 2412 if (!isa<BitCastInst>(SrcOp) && GEP.accumulateConstantOffset(DL, Offset)) { 2413 // If this GEP instruction doesn't move the pointer, just replace the GEP 2414 // with a bitcast of the real input to the dest type. 2415 if (!Offset) { 2416 // If the bitcast is of an allocation, and the allocation will be 2417 // converted to match the type of the cast, don't touch this. 2418 if (isa<AllocaInst>(SrcOp) || isAllocationFn(SrcOp, &TLI)) { 2419 // See if the bitcast simplifies, if so, don't nuke this GEP yet. 2420 if (Instruction *I = visitBitCast(*BCI)) { 2421 if (I != BCI) { 2422 I->takeName(BCI); 2423 BCI->getParent()->getInstList().insert(BCI->getIterator(), I); 2424 replaceInstUsesWith(*BCI, I); 2425 } 2426 return &GEP; 2427 } 2428 } 2429 2430 if (SrcType->getPointerAddressSpace() != GEP.getAddressSpace()) 2431 return new AddrSpaceCastInst(SrcOp, GEPType); 2432 return new BitCastInst(SrcOp, GEPType); 2433 } 2434 2435 // Otherwise, if the offset is non-zero, we need to find out if there is a 2436 // field at Offset in 'A's type. If so, we can pull the cast through the 2437 // GEP. 2438 SmallVector<Value*, 8> NewIndices; 2439 if (FindElementAtOffset(SrcType, Offset.getSExtValue(), NewIndices)) { 2440 Value *NGEP = 2441 GEP.isInBounds() 2442 ? Builder.CreateInBoundsGEP(SrcEltType, SrcOp, NewIndices) 2443 : Builder.CreateGEP(SrcEltType, SrcOp, NewIndices); 2444 2445 if (NGEP->getType() == GEPType) 2446 return replaceInstUsesWith(GEP, NGEP); 2447 NGEP->takeName(&GEP); 2448 2449 if (NGEP->getType()->getPointerAddressSpace() != GEP.getAddressSpace()) 2450 return new AddrSpaceCastInst(NGEP, GEPType); 2451 return new BitCastInst(NGEP, GEPType); 2452 } 2453 } 2454 } 2455 2456 if (!GEP.isInBounds()) { 2457 unsigned IdxWidth = 2458 DL.getIndexSizeInBits(PtrOp->getType()->getPointerAddressSpace()); 2459 APInt BasePtrOffset(IdxWidth, 0); 2460 Value *UnderlyingPtrOp = 2461 PtrOp->stripAndAccumulateInBoundsConstantOffsets(DL, 2462 BasePtrOffset); 2463 if (auto *AI = dyn_cast<AllocaInst>(UnderlyingPtrOp)) { 2464 if (GEP.accumulateConstantOffset(DL, BasePtrOffset) && 2465 BasePtrOffset.isNonNegative()) { 2466 APInt AllocSize( 2467 IdxWidth, 2468 DL.getTypeAllocSize(AI->getAllocatedType()).getKnownMinSize()); 2469 if (BasePtrOffset.ule(AllocSize)) { 2470 return GetElementPtrInst::CreateInBounds( 2471 GEP.getSourceElementType(), PtrOp, makeArrayRef(Ops).slice(1), 2472 GEP.getName()); 2473 } 2474 } 2475 } 2476 } 2477 2478 if (Instruction *R = foldSelectGEP(GEP, Builder)) 2479 return R; 2480 2481 return nullptr; 2482 } 2483 2484 static bool isNeverEqualToUnescapedAlloc(Value *V, const TargetLibraryInfo *TLI, 2485 Instruction *AI) { 2486 if (isa<ConstantPointerNull>(V)) 2487 return true; 2488 if (auto *LI = dyn_cast<LoadInst>(V)) 2489 return isa<GlobalVariable>(LI->getPointerOperand()); 2490 // Two distinct allocations will never be equal. 2491 // We rely on LookThroughBitCast in isAllocLikeFn being false, since looking 2492 // through bitcasts of V can cause 2493 // the result statement below to be true, even when AI and V (ex: 2494 // i8* ->i32* ->i8* of AI) are the same allocations. 2495 return isAllocLikeFn(V, TLI) && V != AI; 2496 } 2497 2498 static bool isAllocSiteRemovable(Instruction *AI, 2499 SmallVectorImpl<WeakTrackingVH> &Users, 2500 const TargetLibraryInfo *TLI) { 2501 SmallVector<Instruction*, 4> Worklist; 2502 Worklist.push_back(AI); 2503 2504 do { 2505 Instruction *PI = Worklist.pop_back_val(); 2506 for (User *U : PI->users()) { 2507 Instruction *I = cast<Instruction>(U); 2508 switch (I->getOpcode()) { 2509 default: 2510 // Give up the moment we see something we can't handle. 2511 return false; 2512 2513 case Instruction::AddrSpaceCast: 2514 case Instruction::BitCast: 2515 case Instruction::GetElementPtr: 2516 Users.emplace_back(I); 2517 Worklist.push_back(I); 2518 continue; 2519 2520 case Instruction::ICmp: { 2521 ICmpInst *ICI = cast<ICmpInst>(I); 2522 // We can fold eq/ne comparisons with null to false/true, respectively. 2523 // We also fold comparisons in some conditions provided the alloc has 2524 // not escaped (see isNeverEqualToUnescapedAlloc). 2525 if (!ICI->isEquality()) 2526 return false; 2527 unsigned OtherIndex = (ICI->getOperand(0) == PI) ? 1 : 0; 2528 if (!isNeverEqualToUnescapedAlloc(ICI->getOperand(OtherIndex), TLI, AI)) 2529 return false; 2530 Users.emplace_back(I); 2531 continue; 2532 } 2533 2534 case Instruction::Call: 2535 // Ignore no-op and store intrinsics. 2536 if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(I)) { 2537 switch (II->getIntrinsicID()) { 2538 default: 2539 return false; 2540 2541 case Intrinsic::memmove: 2542 case Intrinsic::memcpy: 2543 case Intrinsic::memset: { 2544 MemIntrinsic *MI = cast<MemIntrinsic>(II); 2545 if (MI->isVolatile() || MI->getRawDest() != PI) 2546 return false; 2547 LLVM_FALLTHROUGH; 2548 } 2549 case Intrinsic::assume: 2550 case Intrinsic::invariant_start: 2551 case Intrinsic::invariant_end: 2552 case Intrinsic::lifetime_start: 2553 case Intrinsic::lifetime_end: 2554 case Intrinsic::objectsize: 2555 Users.emplace_back(I); 2556 continue; 2557 } 2558 } 2559 2560 if (isFreeCall(I, TLI)) { 2561 Users.emplace_back(I); 2562 continue; 2563 } 2564 return false; 2565 2566 case Instruction::Store: { 2567 StoreInst *SI = cast<StoreInst>(I); 2568 if (SI->isVolatile() || SI->getPointerOperand() != PI) 2569 return false; 2570 Users.emplace_back(I); 2571 continue; 2572 } 2573 } 2574 llvm_unreachable("missing a return?"); 2575 } 2576 } while (!Worklist.empty()); 2577 return true; 2578 } 2579 2580 Instruction *InstCombinerImpl::visitAllocSite(Instruction &MI) { 2581 // If we have a malloc call which is only used in any amount of comparisons to 2582 // null and free calls, delete the calls and replace the comparisons with true 2583 // or false as appropriate. 2584 2585 // This is based on the principle that we can substitute our own allocation 2586 // function (which will never return null) rather than knowledge of the 2587 // specific function being called. In some sense this can change the permitted 2588 // outputs of a program (when we convert a malloc to an alloca, the fact that 2589 // the allocation is now on the stack is potentially visible, for example), 2590 // but we believe in a permissible manner. 2591 SmallVector<WeakTrackingVH, 64> Users; 2592 2593 // If we are removing an alloca with a dbg.declare, insert dbg.value calls 2594 // before each store. 2595 SmallVector<DbgVariableIntrinsic *, 8> DVIs; 2596 std::unique_ptr<DIBuilder> DIB; 2597 if (isa<AllocaInst>(MI)) { 2598 findDbgUsers(DVIs, &MI); 2599 DIB.reset(new DIBuilder(*MI.getModule(), /*AllowUnresolved=*/false)); 2600 } 2601 2602 if (isAllocSiteRemovable(&MI, Users, &TLI)) { 2603 for (unsigned i = 0, e = Users.size(); i != e; ++i) { 2604 // Lowering all @llvm.objectsize calls first because they may 2605 // use a bitcast/GEP of the alloca we are removing. 2606 if (!Users[i]) 2607 continue; 2608 2609 Instruction *I = cast<Instruction>(&*Users[i]); 2610 2611 if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(I)) { 2612 if (II->getIntrinsicID() == Intrinsic::objectsize) { 2613 Value *Result = 2614 lowerObjectSizeCall(II, DL, &TLI, /*MustSucceed=*/true); 2615 replaceInstUsesWith(*I, Result); 2616 eraseInstFromFunction(*I); 2617 Users[i] = nullptr; // Skip examining in the next loop. 2618 } 2619 } 2620 } 2621 for (unsigned i = 0, e = Users.size(); i != e; ++i) { 2622 if (!Users[i]) 2623 continue; 2624 2625 Instruction *I = cast<Instruction>(&*Users[i]); 2626 2627 if (ICmpInst *C = dyn_cast<ICmpInst>(I)) { 2628 replaceInstUsesWith(*C, 2629 ConstantInt::get(Type::getInt1Ty(C->getContext()), 2630 C->isFalseWhenEqual())); 2631 } else if (auto *SI = dyn_cast<StoreInst>(I)) { 2632 for (auto *DVI : DVIs) 2633 if (DVI->isAddressOfVariable()) 2634 ConvertDebugDeclareToDebugValue(DVI, SI, *DIB); 2635 } else { 2636 // Casts, GEP, or anything else: we're about to delete this instruction, 2637 // so it can not have any valid uses. 2638 replaceInstUsesWith(*I, UndefValue::get(I->getType())); 2639 } 2640 eraseInstFromFunction(*I); 2641 } 2642 2643 if (InvokeInst *II = dyn_cast<InvokeInst>(&MI)) { 2644 // Replace invoke with a NOP intrinsic to maintain the original CFG 2645 Module *M = II->getModule(); 2646 Function *F = Intrinsic::getDeclaration(M, Intrinsic::donothing); 2647 InvokeInst::Create(F, II->getNormalDest(), II->getUnwindDest(), 2648 None, "", II->getParent()); 2649 } 2650 2651 // Remove debug intrinsics which describe the value contained within the 2652 // alloca. In addition to removing dbg.{declare,addr} which simply point to 2653 // the alloca, remove dbg.value(<alloca>, ..., DW_OP_deref)'s as well, e.g.: 2654 // 2655 // ``` 2656 // define void @foo(i32 %0) { 2657 // %a = alloca i32 ; Deleted. 2658 // store i32 %0, i32* %a 2659 // dbg.value(i32 %0, "arg0") ; Not deleted. 2660 // dbg.value(i32* %a, "arg0", DW_OP_deref) ; Deleted. 2661 // call void @trivially_inlinable_no_op(i32* %a) 2662 // ret void 2663 // } 2664 // ``` 2665 // 2666 // This may not be required if we stop describing the contents of allocas 2667 // using dbg.value(<alloca>, ..., DW_OP_deref), but we currently do this in 2668 // the LowerDbgDeclare utility. 2669 // 2670 // If there is a dead store to `%a` in @trivially_inlinable_no_op, the 2671 // "arg0" dbg.value may be stale after the call. However, failing to remove 2672 // the DW_OP_deref dbg.value causes large gaps in location coverage. 2673 for (auto *DVI : DVIs) 2674 if (DVI->isAddressOfVariable() || DVI->getExpression()->startsWithDeref()) 2675 DVI->eraseFromParent(); 2676 2677 return eraseInstFromFunction(MI); 2678 } 2679 return nullptr; 2680 } 2681 2682 /// Move the call to free before a NULL test. 2683 /// 2684 /// Check if this free is accessed after its argument has been test 2685 /// against NULL (property 0). 2686 /// If yes, it is legal to move this call in its predecessor block. 2687 /// 2688 /// The move is performed only if the block containing the call to free 2689 /// will be removed, i.e.: 2690 /// 1. it has only one predecessor P, and P has two successors 2691 /// 2. it contains the call, noops, and an unconditional branch 2692 /// 3. its successor is the same as its predecessor's successor 2693 /// 2694 /// The profitability is out-of concern here and this function should 2695 /// be called only if the caller knows this transformation would be 2696 /// profitable (e.g., for code size). 2697 static Instruction *tryToMoveFreeBeforeNullTest(CallInst &FI, 2698 const DataLayout &DL) { 2699 Value *Op = FI.getArgOperand(0); 2700 BasicBlock *FreeInstrBB = FI.getParent(); 2701 BasicBlock *PredBB = FreeInstrBB->getSinglePredecessor(); 2702 2703 // Validate part of constraint #1: Only one predecessor 2704 // FIXME: We can extend the number of predecessor, but in that case, we 2705 // would duplicate the call to free in each predecessor and it may 2706 // not be profitable even for code size. 2707 if (!PredBB) 2708 return nullptr; 2709 2710 // Validate constraint #2: Does this block contains only the call to 2711 // free, noops, and an unconditional branch? 2712 BasicBlock *SuccBB; 2713 Instruction *FreeInstrBBTerminator = FreeInstrBB->getTerminator(); 2714 if (!match(FreeInstrBBTerminator, m_UnconditionalBr(SuccBB))) 2715 return nullptr; 2716 2717 // If there are only 2 instructions in the block, at this point, 2718 // this is the call to free and unconditional. 2719 // If there are more than 2 instructions, check that they are noops 2720 // i.e., they won't hurt the performance of the generated code. 2721 if (FreeInstrBB->size() != 2) { 2722 for (const Instruction &Inst : FreeInstrBB->instructionsWithoutDebug()) { 2723 if (&Inst == &FI || &Inst == FreeInstrBBTerminator) 2724 continue; 2725 auto *Cast = dyn_cast<CastInst>(&Inst); 2726 if (!Cast || !Cast->isNoopCast(DL)) 2727 return nullptr; 2728 } 2729 } 2730 // Validate the rest of constraint #1 by matching on the pred branch. 2731 Instruction *TI = PredBB->getTerminator(); 2732 BasicBlock *TrueBB, *FalseBB; 2733 ICmpInst::Predicate Pred; 2734 if (!match(TI, m_Br(m_ICmp(Pred, 2735 m_CombineOr(m_Specific(Op), 2736 m_Specific(Op->stripPointerCasts())), 2737 m_Zero()), 2738 TrueBB, FalseBB))) 2739 return nullptr; 2740 if (Pred != ICmpInst::ICMP_EQ && Pred != ICmpInst::ICMP_NE) 2741 return nullptr; 2742 2743 // Validate constraint #3: Ensure the null case just falls through. 2744 if (SuccBB != (Pred == ICmpInst::ICMP_EQ ? TrueBB : FalseBB)) 2745 return nullptr; 2746 assert(FreeInstrBB == (Pred == ICmpInst::ICMP_EQ ? FalseBB : TrueBB) && 2747 "Broken CFG: missing edge from predecessor to successor"); 2748 2749 // At this point, we know that everything in FreeInstrBB can be moved 2750 // before TI. 2751 for (BasicBlock::iterator It = FreeInstrBB->begin(), End = FreeInstrBB->end(); 2752 It != End;) { 2753 Instruction &Instr = *It++; 2754 if (&Instr == FreeInstrBBTerminator) 2755 break; 2756 Instr.moveBefore(TI); 2757 } 2758 assert(FreeInstrBB->size() == 1 && 2759 "Only the branch instruction should remain"); 2760 return &FI; 2761 } 2762 2763 Instruction *InstCombinerImpl::visitFree(CallInst &FI) { 2764 Value *Op = FI.getArgOperand(0); 2765 2766 // free undef -> unreachable. 2767 if (isa<UndefValue>(Op)) { 2768 // Leave a marker since we can't modify the CFG here. 2769 CreateNonTerminatorUnreachable(&FI); 2770 return eraseInstFromFunction(FI); 2771 } 2772 2773 // If we have 'free null' delete the instruction. This can happen in stl code 2774 // when lots of inlining happens. 2775 if (isa<ConstantPointerNull>(Op)) 2776 return eraseInstFromFunction(FI); 2777 2778 // If we optimize for code size, try to move the call to free before the null 2779 // test so that simplify cfg can remove the empty block and dead code 2780 // elimination the branch. I.e., helps to turn something like: 2781 // if (foo) free(foo); 2782 // into 2783 // free(foo); 2784 // 2785 // Note that we can only do this for 'free' and not for any flavor of 2786 // 'operator delete'; there is no 'operator delete' symbol for which we are 2787 // permitted to invent a call, even if we're passing in a null pointer. 2788 if (MinimizeSize) { 2789 LibFunc Func; 2790 if (TLI.getLibFunc(FI, Func) && TLI.has(Func) && Func == LibFunc_free) 2791 if (Instruction *I = tryToMoveFreeBeforeNullTest(FI, DL)) 2792 return I; 2793 } 2794 2795 return nullptr; 2796 } 2797 2798 static bool isMustTailCall(Value *V) { 2799 if (auto *CI = dyn_cast<CallInst>(V)) 2800 return CI->isMustTailCall(); 2801 return false; 2802 } 2803 2804 Instruction *InstCombinerImpl::visitReturnInst(ReturnInst &RI) { 2805 if (RI.getNumOperands() == 0) // ret void 2806 return nullptr; 2807 2808 Value *ResultOp = RI.getOperand(0); 2809 Type *VTy = ResultOp->getType(); 2810 if (!VTy->isIntegerTy() || isa<Constant>(ResultOp)) 2811 return nullptr; 2812 2813 // Don't replace result of musttail calls. 2814 if (isMustTailCall(ResultOp)) 2815 return nullptr; 2816 2817 // There might be assume intrinsics dominating this return that completely 2818 // determine the value. If so, constant fold it. 2819 KnownBits Known = computeKnownBits(ResultOp, 0, &RI); 2820 if (Known.isConstant()) 2821 return replaceOperand(RI, 0, 2822 Constant::getIntegerValue(VTy, Known.getConstant())); 2823 2824 return nullptr; 2825 } 2826 2827 Instruction *InstCombinerImpl::visitUnreachableInst(UnreachableInst &I) { 2828 // Try to remove the previous instruction if it must lead to unreachable. 2829 // This includes instructions like stores and "llvm.assume" that may not get 2830 // removed by simple dead code elimination. 2831 Instruction *Prev = I.getPrevNonDebugInstruction(); 2832 if (Prev && !Prev->isEHPad() && 2833 isGuaranteedToTransferExecutionToSuccessor(Prev)) { 2834 // Temporarily disable removal of volatile stores preceding unreachable, 2835 // pending a potential LangRef change permitting volatile stores to trap. 2836 // TODO: Either remove this code, or properly integrate the check into 2837 // isGuaranteedToTransferExecutionToSuccessor(). 2838 if (auto *SI = dyn_cast<StoreInst>(Prev)) 2839 if (SI->isVolatile()) 2840 return nullptr; 2841 2842 // A value may still have uses before we process it here (for example, in 2843 // another unreachable block), so convert those to undef. 2844 replaceInstUsesWith(*Prev, UndefValue::get(Prev->getType())); 2845 eraseInstFromFunction(*Prev); 2846 return &I; 2847 } 2848 return nullptr; 2849 } 2850 2851 Instruction *InstCombinerImpl::visitUnconditionalBranchInst(BranchInst &BI) { 2852 assert(BI.isUnconditional() && "Only for unconditional branches."); 2853 2854 // If this store is the second-to-last instruction in the basic block 2855 // (excluding debug info and bitcasts of pointers) and if the block ends with 2856 // an unconditional branch, try to move the store to the successor block. 2857 2858 auto GetLastSinkableStore = [](BasicBlock::iterator BBI) { 2859 auto IsNoopInstrForStoreMerging = [](BasicBlock::iterator BBI) { 2860 return isa<DbgInfoIntrinsic>(BBI) || 2861 (isa<BitCastInst>(BBI) && BBI->getType()->isPointerTy()); 2862 }; 2863 2864 BasicBlock::iterator FirstInstr = BBI->getParent()->begin(); 2865 do { 2866 if (BBI != FirstInstr) 2867 --BBI; 2868 } while (BBI != FirstInstr && IsNoopInstrForStoreMerging(BBI)); 2869 2870 return dyn_cast<StoreInst>(BBI); 2871 }; 2872 2873 if (StoreInst *SI = GetLastSinkableStore(BasicBlock::iterator(BI))) 2874 if (mergeStoreIntoSuccessor(*SI)) 2875 return &BI; 2876 2877 return nullptr; 2878 } 2879 2880 Instruction *InstCombinerImpl::visitBranchInst(BranchInst &BI) { 2881 if (BI.isUnconditional()) 2882 return visitUnconditionalBranchInst(BI); 2883 2884 // Change br (not X), label True, label False to: br X, label False, True 2885 Value *X = nullptr; 2886 if (match(&BI, m_Br(m_Not(m_Value(X)), m_BasicBlock(), m_BasicBlock())) && 2887 !isa<Constant>(X)) { 2888 // Swap Destinations and condition... 2889 BI.swapSuccessors(); 2890 return replaceOperand(BI, 0, X); 2891 } 2892 2893 // If the condition is irrelevant, remove the use so that other 2894 // transforms on the condition become more effective. 2895 if (!isa<ConstantInt>(BI.getCondition()) && 2896 BI.getSuccessor(0) == BI.getSuccessor(1)) 2897 return replaceOperand( 2898 BI, 0, ConstantInt::getFalse(BI.getCondition()->getType())); 2899 2900 // Canonicalize, for example, fcmp_one -> fcmp_oeq. 2901 CmpInst::Predicate Pred; 2902 if (match(&BI, m_Br(m_OneUse(m_FCmp(Pred, m_Value(), m_Value())), 2903 m_BasicBlock(), m_BasicBlock())) && 2904 !isCanonicalPredicate(Pred)) { 2905 // Swap destinations and condition. 2906 CmpInst *Cond = cast<CmpInst>(BI.getCondition()); 2907 Cond->setPredicate(CmpInst::getInversePredicate(Pred)); 2908 BI.swapSuccessors(); 2909 Worklist.push(Cond); 2910 return &BI; 2911 } 2912 2913 return nullptr; 2914 } 2915 2916 Instruction *InstCombinerImpl::visitSwitchInst(SwitchInst &SI) { 2917 Value *Cond = SI.getCondition(); 2918 Value *Op0; 2919 ConstantInt *AddRHS; 2920 if (match(Cond, m_Add(m_Value(Op0), m_ConstantInt(AddRHS)))) { 2921 // Change 'switch (X+4) case 1:' into 'switch (X) case -3'. 2922 for (auto Case : SI.cases()) { 2923 Constant *NewCase = ConstantExpr::getSub(Case.getCaseValue(), AddRHS); 2924 assert(isa<ConstantInt>(NewCase) && 2925 "Result of expression should be constant"); 2926 Case.setValue(cast<ConstantInt>(NewCase)); 2927 } 2928 return replaceOperand(SI, 0, Op0); 2929 } 2930 2931 KnownBits Known = computeKnownBits(Cond, 0, &SI); 2932 unsigned LeadingKnownZeros = Known.countMinLeadingZeros(); 2933 unsigned LeadingKnownOnes = Known.countMinLeadingOnes(); 2934 2935 // Compute the number of leading bits we can ignore. 2936 // TODO: A better way to determine this would use ComputeNumSignBits(). 2937 for (auto &C : SI.cases()) { 2938 LeadingKnownZeros = std::min( 2939 LeadingKnownZeros, C.getCaseValue()->getValue().countLeadingZeros()); 2940 LeadingKnownOnes = std::min( 2941 LeadingKnownOnes, C.getCaseValue()->getValue().countLeadingOnes()); 2942 } 2943 2944 unsigned NewWidth = Known.getBitWidth() - std::max(LeadingKnownZeros, LeadingKnownOnes); 2945 2946 // Shrink the condition operand if the new type is smaller than the old type. 2947 // But do not shrink to a non-standard type, because backend can't generate 2948 // good code for that yet. 2949 // TODO: We can make it aggressive again after fixing PR39569. 2950 if (NewWidth > 0 && NewWidth < Known.getBitWidth() && 2951 shouldChangeType(Known.getBitWidth(), NewWidth)) { 2952 IntegerType *Ty = IntegerType::get(SI.getContext(), NewWidth); 2953 Builder.SetInsertPoint(&SI); 2954 Value *NewCond = Builder.CreateTrunc(Cond, Ty, "trunc"); 2955 2956 for (auto Case : SI.cases()) { 2957 APInt TruncatedCase = Case.getCaseValue()->getValue().trunc(NewWidth); 2958 Case.setValue(ConstantInt::get(SI.getContext(), TruncatedCase)); 2959 } 2960 return replaceOperand(SI, 0, NewCond); 2961 } 2962 2963 return nullptr; 2964 } 2965 2966 Instruction *InstCombinerImpl::visitExtractValueInst(ExtractValueInst &EV) { 2967 Value *Agg = EV.getAggregateOperand(); 2968 2969 if (!EV.hasIndices()) 2970 return replaceInstUsesWith(EV, Agg); 2971 2972 if (Value *V = SimplifyExtractValueInst(Agg, EV.getIndices(), 2973 SQ.getWithInstruction(&EV))) 2974 return replaceInstUsesWith(EV, V); 2975 2976 if (InsertValueInst *IV = dyn_cast<InsertValueInst>(Agg)) { 2977 // We're extracting from an insertvalue instruction, compare the indices 2978 const unsigned *exti, *exte, *insi, *inse; 2979 for (exti = EV.idx_begin(), insi = IV->idx_begin(), 2980 exte = EV.idx_end(), inse = IV->idx_end(); 2981 exti != exte && insi != inse; 2982 ++exti, ++insi) { 2983 if (*insi != *exti) 2984 // The insert and extract both reference distinctly different elements. 2985 // This means the extract is not influenced by the insert, and we can 2986 // replace the aggregate operand of the extract with the aggregate 2987 // operand of the insert. i.e., replace 2988 // %I = insertvalue { i32, { i32 } } %A, { i32 } { i32 42 }, 1 2989 // %E = extractvalue { i32, { i32 } } %I, 0 2990 // with 2991 // %E = extractvalue { i32, { i32 } } %A, 0 2992 return ExtractValueInst::Create(IV->getAggregateOperand(), 2993 EV.getIndices()); 2994 } 2995 if (exti == exte && insi == inse) 2996 // Both iterators are at the end: Index lists are identical. Replace 2997 // %B = insertvalue { i32, { i32 } } %A, i32 42, 1, 0 2998 // %C = extractvalue { i32, { i32 } } %B, 1, 0 2999 // with "i32 42" 3000 return replaceInstUsesWith(EV, IV->getInsertedValueOperand()); 3001 if (exti == exte) { 3002 // The extract list is a prefix of the insert list. i.e. replace 3003 // %I = insertvalue { i32, { i32 } } %A, i32 42, 1, 0 3004 // %E = extractvalue { i32, { i32 } } %I, 1 3005 // with 3006 // %X = extractvalue { i32, { i32 } } %A, 1 3007 // %E = insertvalue { i32 } %X, i32 42, 0 3008 // by switching the order of the insert and extract (though the 3009 // insertvalue should be left in, since it may have other uses). 3010 Value *NewEV = Builder.CreateExtractValue(IV->getAggregateOperand(), 3011 EV.getIndices()); 3012 return InsertValueInst::Create(NewEV, IV->getInsertedValueOperand(), 3013 makeArrayRef(insi, inse)); 3014 } 3015 if (insi == inse) 3016 // The insert list is a prefix of the extract list 3017 // We can simply remove the common indices from the extract and make it 3018 // operate on the inserted value instead of the insertvalue result. 3019 // i.e., replace 3020 // %I = insertvalue { i32, { i32 } } %A, { i32 } { i32 42 }, 1 3021 // %E = extractvalue { i32, { i32 } } %I, 1, 0 3022 // with 3023 // %E extractvalue { i32 } { i32 42 }, 0 3024 return ExtractValueInst::Create(IV->getInsertedValueOperand(), 3025 makeArrayRef(exti, exte)); 3026 } 3027 if (WithOverflowInst *WO = dyn_cast<WithOverflowInst>(Agg)) { 3028 // We're extracting from an overflow intrinsic, see if we're the only user, 3029 // which allows us to simplify multiple result intrinsics to simpler 3030 // things that just get one value. 3031 if (WO->hasOneUse()) { 3032 // Check if we're grabbing only the result of a 'with overflow' intrinsic 3033 // and replace it with a traditional binary instruction. 3034 if (*EV.idx_begin() == 0) { 3035 Instruction::BinaryOps BinOp = WO->getBinaryOp(); 3036 Value *LHS = WO->getLHS(), *RHS = WO->getRHS(); 3037 replaceInstUsesWith(*WO, UndefValue::get(WO->getType())); 3038 eraseInstFromFunction(*WO); 3039 return BinaryOperator::Create(BinOp, LHS, RHS); 3040 } 3041 3042 // If the normal result of the add is dead, and the RHS is a constant, 3043 // we can transform this into a range comparison. 3044 // overflow = uadd a, -4 --> overflow = icmp ugt a, 3 3045 if (WO->getIntrinsicID() == Intrinsic::uadd_with_overflow) 3046 if (ConstantInt *CI = dyn_cast<ConstantInt>(WO->getRHS())) 3047 return new ICmpInst(ICmpInst::ICMP_UGT, WO->getLHS(), 3048 ConstantExpr::getNot(CI)); 3049 } 3050 } 3051 if (LoadInst *L = dyn_cast<LoadInst>(Agg)) 3052 // If the (non-volatile) load only has one use, we can rewrite this to a 3053 // load from a GEP. This reduces the size of the load. If a load is used 3054 // only by extractvalue instructions then this either must have been 3055 // optimized before, or it is a struct with padding, in which case we 3056 // don't want to do the transformation as it loses padding knowledge. 3057 if (L->isSimple() && L->hasOneUse()) { 3058 // extractvalue has integer indices, getelementptr has Value*s. Convert. 3059 SmallVector<Value*, 4> Indices; 3060 // Prefix an i32 0 since we need the first element. 3061 Indices.push_back(Builder.getInt32(0)); 3062 for (ExtractValueInst::idx_iterator I = EV.idx_begin(), E = EV.idx_end(); 3063 I != E; ++I) 3064 Indices.push_back(Builder.getInt32(*I)); 3065 3066 // We need to insert these at the location of the old load, not at that of 3067 // the extractvalue. 3068 Builder.SetInsertPoint(L); 3069 Value *GEP = Builder.CreateInBoundsGEP(L->getType(), 3070 L->getPointerOperand(), Indices); 3071 Instruction *NL = Builder.CreateLoad(EV.getType(), GEP); 3072 // Whatever aliasing information we had for the orignal load must also 3073 // hold for the smaller load, so propagate the annotations. 3074 AAMDNodes Nodes; 3075 L->getAAMetadata(Nodes); 3076 NL->setAAMetadata(Nodes); 3077 // Returning the load directly will cause the main loop to insert it in 3078 // the wrong spot, so use replaceInstUsesWith(). 3079 return replaceInstUsesWith(EV, NL); 3080 } 3081 // We could simplify extracts from other values. Note that nested extracts may 3082 // already be simplified implicitly by the above: extract (extract (insert) ) 3083 // will be translated into extract ( insert ( extract ) ) first and then just 3084 // the value inserted, if appropriate. Similarly for extracts from single-use 3085 // loads: extract (extract (load)) will be translated to extract (load (gep)) 3086 // and if again single-use then via load (gep (gep)) to load (gep). 3087 // However, double extracts from e.g. function arguments or return values 3088 // aren't handled yet. 3089 return nullptr; 3090 } 3091 3092 /// Return 'true' if the given typeinfo will match anything. 3093 static bool isCatchAll(EHPersonality Personality, Constant *TypeInfo) { 3094 switch (Personality) { 3095 case EHPersonality::GNU_C: 3096 case EHPersonality::GNU_C_SjLj: 3097 case EHPersonality::Rust: 3098 // The GCC C EH and Rust personality only exists to support cleanups, so 3099 // it's not clear what the semantics of catch clauses are. 3100 return false; 3101 case EHPersonality::Unknown: 3102 return false; 3103 case EHPersonality::GNU_Ada: 3104 // While __gnat_all_others_value will match any Ada exception, it doesn't 3105 // match foreign exceptions (or didn't, before gcc-4.7). 3106 return false; 3107 case EHPersonality::GNU_CXX: 3108 case EHPersonality::GNU_CXX_SjLj: 3109 case EHPersonality::GNU_ObjC: 3110 case EHPersonality::MSVC_X86SEH: 3111 case EHPersonality::MSVC_TableSEH: 3112 case EHPersonality::MSVC_CXX: 3113 case EHPersonality::CoreCLR: 3114 case EHPersonality::Wasm_CXX: 3115 case EHPersonality::XL_CXX: 3116 return TypeInfo->isNullValue(); 3117 } 3118 llvm_unreachable("invalid enum"); 3119 } 3120 3121 static bool shorter_filter(const Value *LHS, const Value *RHS) { 3122 return 3123 cast<ArrayType>(LHS->getType())->getNumElements() 3124 < 3125 cast<ArrayType>(RHS->getType())->getNumElements(); 3126 } 3127 3128 Instruction *InstCombinerImpl::visitLandingPadInst(LandingPadInst &LI) { 3129 // The logic here should be correct for any real-world personality function. 3130 // However if that turns out not to be true, the offending logic can always 3131 // be conditioned on the personality function, like the catch-all logic is. 3132 EHPersonality Personality = 3133 classifyEHPersonality(LI.getParent()->getParent()->getPersonalityFn()); 3134 3135 // Simplify the list of clauses, eg by removing repeated catch clauses 3136 // (these are often created by inlining). 3137 bool MakeNewInstruction = false; // If true, recreate using the following: 3138 SmallVector<Constant *, 16> NewClauses; // - Clauses for the new instruction; 3139 bool CleanupFlag = LI.isCleanup(); // - The new instruction is a cleanup. 3140 3141 SmallPtrSet<Value *, 16> AlreadyCaught; // Typeinfos known caught already. 3142 for (unsigned i = 0, e = LI.getNumClauses(); i != e; ++i) { 3143 bool isLastClause = i + 1 == e; 3144 if (LI.isCatch(i)) { 3145 // A catch clause. 3146 Constant *CatchClause = LI.getClause(i); 3147 Constant *TypeInfo = CatchClause->stripPointerCasts(); 3148 3149 // If we already saw this clause, there is no point in having a second 3150 // copy of it. 3151 if (AlreadyCaught.insert(TypeInfo).second) { 3152 // This catch clause was not already seen. 3153 NewClauses.push_back(CatchClause); 3154 } else { 3155 // Repeated catch clause - drop the redundant copy. 3156 MakeNewInstruction = true; 3157 } 3158 3159 // If this is a catch-all then there is no point in keeping any following 3160 // clauses or marking the landingpad as having a cleanup. 3161 if (isCatchAll(Personality, TypeInfo)) { 3162 if (!isLastClause) 3163 MakeNewInstruction = true; 3164 CleanupFlag = false; 3165 break; 3166 } 3167 } else { 3168 // A filter clause. If any of the filter elements were already caught 3169 // then they can be dropped from the filter. It is tempting to try to 3170 // exploit the filter further by saying that any typeinfo that does not 3171 // occur in the filter can't be caught later (and thus can be dropped). 3172 // However this would be wrong, since typeinfos can match without being 3173 // equal (for example if one represents a C++ class, and the other some 3174 // class derived from it). 3175 assert(LI.isFilter(i) && "Unsupported landingpad clause!"); 3176 Constant *FilterClause = LI.getClause(i); 3177 ArrayType *FilterType = cast<ArrayType>(FilterClause->getType()); 3178 unsigned NumTypeInfos = FilterType->getNumElements(); 3179 3180 // An empty filter catches everything, so there is no point in keeping any 3181 // following clauses or marking the landingpad as having a cleanup. By 3182 // dealing with this case here the following code is made a bit simpler. 3183 if (!NumTypeInfos) { 3184 NewClauses.push_back(FilterClause); 3185 if (!isLastClause) 3186 MakeNewInstruction = true; 3187 CleanupFlag = false; 3188 break; 3189 } 3190 3191 bool MakeNewFilter = false; // If true, make a new filter. 3192 SmallVector<Constant *, 16> NewFilterElts; // New elements. 3193 if (isa<ConstantAggregateZero>(FilterClause)) { 3194 // Not an empty filter - it contains at least one null typeinfo. 3195 assert(NumTypeInfos > 0 && "Should have handled empty filter already!"); 3196 Constant *TypeInfo = 3197 Constant::getNullValue(FilterType->getElementType()); 3198 // If this typeinfo is a catch-all then the filter can never match. 3199 if (isCatchAll(Personality, TypeInfo)) { 3200 // Throw the filter away. 3201 MakeNewInstruction = true; 3202 continue; 3203 } 3204 3205 // There is no point in having multiple copies of this typeinfo, so 3206 // discard all but the first copy if there is more than one. 3207 NewFilterElts.push_back(TypeInfo); 3208 if (NumTypeInfos > 1) 3209 MakeNewFilter = true; 3210 } else { 3211 ConstantArray *Filter = cast<ConstantArray>(FilterClause); 3212 SmallPtrSet<Value *, 16> SeenInFilter; // For uniquing the elements. 3213 NewFilterElts.reserve(NumTypeInfos); 3214 3215 // Remove any filter elements that were already caught or that already 3216 // occurred in the filter. While there, see if any of the elements are 3217 // catch-alls. If so, the filter can be discarded. 3218 bool SawCatchAll = false; 3219 for (unsigned j = 0; j != NumTypeInfos; ++j) { 3220 Constant *Elt = Filter->getOperand(j); 3221 Constant *TypeInfo = Elt->stripPointerCasts(); 3222 if (isCatchAll(Personality, TypeInfo)) { 3223 // This element is a catch-all. Bail out, noting this fact. 3224 SawCatchAll = true; 3225 break; 3226 } 3227 3228 // Even if we've seen a type in a catch clause, we don't want to 3229 // remove it from the filter. An unexpected type handler may be 3230 // set up for a call site which throws an exception of the same 3231 // type caught. In order for the exception thrown by the unexpected 3232 // handler to propagate correctly, the filter must be correctly 3233 // described for the call site. 3234 // 3235 // Example: 3236 // 3237 // void unexpected() { throw 1;} 3238 // void foo() throw (int) { 3239 // std::set_unexpected(unexpected); 3240 // try { 3241 // throw 2.0; 3242 // } catch (int i) {} 3243 // } 3244 3245 // There is no point in having multiple copies of the same typeinfo in 3246 // a filter, so only add it if we didn't already. 3247 if (SeenInFilter.insert(TypeInfo).second) 3248 NewFilterElts.push_back(cast<Constant>(Elt)); 3249 } 3250 // A filter containing a catch-all cannot match anything by definition. 3251 if (SawCatchAll) { 3252 // Throw the filter away. 3253 MakeNewInstruction = true; 3254 continue; 3255 } 3256 3257 // If we dropped something from the filter, make a new one. 3258 if (NewFilterElts.size() < NumTypeInfos) 3259 MakeNewFilter = true; 3260 } 3261 if (MakeNewFilter) { 3262 FilterType = ArrayType::get(FilterType->getElementType(), 3263 NewFilterElts.size()); 3264 FilterClause = ConstantArray::get(FilterType, NewFilterElts); 3265 MakeNewInstruction = true; 3266 } 3267 3268 NewClauses.push_back(FilterClause); 3269 3270 // If the new filter is empty then it will catch everything so there is 3271 // no point in keeping any following clauses or marking the landingpad 3272 // as having a cleanup. The case of the original filter being empty was 3273 // already handled above. 3274 if (MakeNewFilter && !NewFilterElts.size()) { 3275 assert(MakeNewInstruction && "New filter but not a new instruction!"); 3276 CleanupFlag = false; 3277 break; 3278 } 3279 } 3280 } 3281 3282 // If several filters occur in a row then reorder them so that the shortest 3283 // filters come first (those with the smallest number of elements). This is 3284 // advantageous because shorter filters are more likely to match, speeding up 3285 // unwinding, but mostly because it increases the effectiveness of the other 3286 // filter optimizations below. 3287 for (unsigned i = 0, e = NewClauses.size(); i + 1 < e; ) { 3288 unsigned j; 3289 // Find the maximal 'j' s.t. the range [i, j) consists entirely of filters. 3290 for (j = i; j != e; ++j) 3291 if (!isa<ArrayType>(NewClauses[j]->getType())) 3292 break; 3293 3294 // Check whether the filters are already sorted by length. We need to know 3295 // if sorting them is actually going to do anything so that we only make a 3296 // new landingpad instruction if it does. 3297 for (unsigned k = i; k + 1 < j; ++k) 3298 if (shorter_filter(NewClauses[k+1], NewClauses[k])) { 3299 // Not sorted, so sort the filters now. Doing an unstable sort would be 3300 // correct too but reordering filters pointlessly might confuse users. 3301 std::stable_sort(NewClauses.begin() + i, NewClauses.begin() + j, 3302 shorter_filter); 3303 MakeNewInstruction = true; 3304 break; 3305 } 3306 3307 // Look for the next batch of filters. 3308 i = j + 1; 3309 } 3310 3311 // If typeinfos matched if and only if equal, then the elements of a filter L 3312 // that occurs later than a filter F could be replaced by the intersection of 3313 // the elements of F and L. In reality two typeinfos can match without being 3314 // equal (for example if one represents a C++ class, and the other some class 3315 // derived from it) so it would be wrong to perform this transform in general. 3316 // However the transform is correct and useful if F is a subset of L. In that 3317 // case L can be replaced by F, and thus removed altogether since repeating a 3318 // filter is pointless. So here we look at all pairs of filters F and L where 3319 // L follows F in the list of clauses, and remove L if every element of F is 3320 // an element of L. This can occur when inlining C++ functions with exception 3321 // specifications. 3322 for (unsigned i = 0; i + 1 < NewClauses.size(); ++i) { 3323 // Examine each filter in turn. 3324 Value *Filter = NewClauses[i]; 3325 ArrayType *FTy = dyn_cast<ArrayType>(Filter->getType()); 3326 if (!FTy) 3327 // Not a filter - skip it. 3328 continue; 3329 unsigned FElts = FTy->getNumElements(); 3330 // Examine each filter following this one. Doing this backwards means that 3331 // we don't have to worry about filters disappearing under us when removed. 3332 for (unsigned j = NewClauses.size() - 1; j != i; --j) { 3333 Value *LFilter = NewClauses[j]; 3334 ArrayType *LTy = dyn_cast<ArrayType>(LFilter->getType()); 3335 if (!LTy) 3336 // Not a filter - skip it. 3337 continue; 3338 // If Filter is a subset of LFilter, i.e. every element of Filter is also 3339 // an element of LFilter, then discard LFilter. 3340 SmallVectorImpl<Constant *>::iterator J = NewClauses.begin() + j; 3341 // If Filter is empty then it is a subset of LFilter. 3342 if (!FElts) { 3343 // Discard LFilter. 3344 NewClauses.erase(J); 3345 MakeNewInstruction = true; 3346 // Move on to the next filter. 3347 continue; 3348 } 3349 unsigned LElts = LTy->getNumElements(); 3350 // If Filter is longer than LFilter then it cannot be a subset of it. 3351 if (FElts > LElts) 3352 // Move on to the next filter. 3353 continue; 3354 // At this point we know that LFilter has at least one element. 3355 if (isa<ConstantAggregateZero>(LFilter)) { // LFilter only contains zeros. 3356 // Filter is a subset of LFilter iff Filter contains only zeros (as we 3357 // already know that Filter is not longer than LFilter). 3358 if (isa<ConstantAggregateZero>(Filter)) { 3359 assert(FElts <= LElts && "Should have handled this case earlier!"); 3360 // Discard LFilter. 3361 NewClauses.erase(J); 3362 MakeNewInstruction = true; 3363 } 3364 // Move on to the next filter. 3365 continue; 3366 } 3367 ConstantArray *LArray = cast<ConstantArray>(LFilter); 3368 if (isa<ConstantAggregateZero>(Filter)) { // Filter only contains zeros. 3369 // Since Filter is non-empty and contains only zeros, it is a subset of 3370 // LFilter iff LFilter contains a zero. 3371 assert(FElts > 0 && "Should have eliminated the empty filter earlier!"); 3372 for (unsigned l = 0; l != LElts; ++l) 3373 if (LArray->getOperand(l)->isNullValue()) { 3374 // LFilter contains a zero - discard it. 3375 NewClauses.erase(J); 3376 MakeNewInstruction = true; 3377 break; 3378 } 3379 // Move on to the next filter. 3380 continue; 3381 } 3382 // At this point we know that both filters are ConstantArrays. Loop over 3383 // operands to see whether every element of Filter is also an element of 3384 // LFilter. Since filters tend to be short this is probably faster than 3385 // using a method that scales nicely. 3386 ConstantArray *FArray = cast<ConstantArray>(Filter); 3387 bool AllFound = true; 3388 for (unsigned f = 0; f != FElts; ++f) { 3389 Value *FTypeInfo = FArray->getOperand(f)->stripPointerCasts(); 3390 AllFound = false; 3391 for (unsigned l = 0; l != LElts; ++l) { 3392 Value *LTypeInfo = LArray->getOperand(l)->stripPointerCasts(); 3393 if (LTypeInfo == FTypeInfo) { 3394 AllFound = true; 3395 break; 3396 } 3397 } 3398 if (!AllFound) 3399 break; 3400 } 3401 if (AllFound) { 3402 // Discard LFilter. 3403 NewClauses.erase(J); 3404 MakeNewInstruction = true; 3405 } 3406 // Move on to the next filter. 3407 } 3408 } 3409 3410 // If we changed any of the clauses, replace the old landingpad instruction 3411 // with a new one. 3412 if (MakeNewInstruction) { 3413 LandingPadInst *NLI = LandingPadInst::Create(LI.getType(), 3414 NewClauses.size()); 3415 for (unsigned i = 0, e = NewClauses.size(); i != e; ++i) 3416 NLI->addClause(NewClauses[i]); 3417 // A landing pad with no clauses must have the cleanup flag set. It is 3418 // theoretically possible, though highly unlikely, that we eliminated all 3419 // clauses. If so, force the cleanup flag to true. 3420 if (NewClauses.empty()) 3421 CleanupFlag = true; 3422 NLI->setCleanup(CleanupFlag); 3423 return NLI; 3424 } 3425 3426 // Even if none of the clauses changed, we may nonetheless have understood 3427 // that the cleanup flag is pointless. Clear it if so. 3428 if (LI.isCleanup() != CleanupFlag) { 3429 assert(!CleanupFlag && "Adding a cleanup, not removing one?!"); 3430 LI.setCleanup(CleanupFlag); 3431 return &LI; 3432 } 3433 3434 return nullptr; 3435 } 3436 3437 Instruction *InstCombinerImpl::visitFreeze(FreezeInst &I) { 3438 Value *Op0 = I.getOperand(0); 3439 3440 if (Value *V = SimplifyFreezeInst(Op0, SQ.getWithInstruction(&I))) 3441 return replaceInstUsesWith(I, V); 3442 3443 // freeze (phi const, x) --> phi const, (freeze x) 3444 if (auto *PN = dyn_cast<PHINode>(Op0)) { 3445 if (Instruction *NV = foldOpIntoPhi(I, PN)) 3446 return NV; 3447 } 3448 3449 if (match(Op0, m_Undef())) { 3450 // If I is freeze(undef), see its uses and fold it to the best constant. 3451 // - or: pick -1 3452 // - select's condition: pick the value that leads to choosing a constant 3453 // - other ops: pick 0 3454 Constant *BestValue = nullptr; 3455 Constant *NullValue = Constant::getNullValue(I.getType()); 3456 for (const auto *U : I.users()) { 3457 Constant *C = NullValue; 3458 3459 if (match(U, m_Or(m_Value(), m_Value()))) 3460 C = Constant::getAllOnesValue(I.getType()); 3461 else if (const auto *SI = dyn_cast<SelectInst>(U)) { 3462 if (SI->getCondition() == &I) { 3463 APInt CondVal(1, isa<Constant>(SI->getFalseValue()) ? 0 : 1); 3464 C = Constant::getIntegerValue(I.getType(), CondVal); 3465 } 3466 } 3467 3468 if (!BestValue) 3469 BestValue = C; 3470 else if (BestValue != C) 3471 BestValue = NullValue; 3472 } 3473 3474 return replaceInstUsesWith(I, BestValue); 3475 } 3476 3477 return nullptr; 3478 } 3479 3480 /// Try to move the specified instruction from its current block into the 3481 /// beginning of DestBlock, which can only happen if it's safe to move the 3482 /// instruction past all of the instructions between it and the end of its 3483 /// block. 3484 static bool TryToSinkInstruction(Instruction *I, BasicBlock *DestBlock) { 3485 assert(I->getSingleUndroppableUse() && "Invariants didn't hold!"); 3486 BasicBlock *SrcBlock = I->getParent(); 3487 3488 // Cannot move control-flow-involving, volatile loads, vaarg, etc. 3489 if (isa<PHINode>(I) || I->isEHPad() || I->mayHaveSideEffects() || 3490 I->isTerminator()) 3491 return false; 3492 3493 // Do not sink static or dynamic alloca instructions. Static allocas must 3494 // remain in the entry block, and dynamic allocas must not be sunk in between 3495 // a stacksave / stackrestore pair, which would incorrectly shorten its 3496 // lifetime. 3497 if (isa<AllocaInst>(I)) 3498 return false; 3499 3500 // Do not sink into catchswitch blocks. 3501 if (isa<CatchSwitchInst>(DestBlock->getTerminator())) 3502 return false; 3503 3504 // Do not sink convergent call instructions. 3505 if (auto *CI = dyn_cast<CallInst>(I)) { 3506 if (CI->isConvergent()) 3507 return false; 3508 } 3509 // We can only sink load instructions if there is nothing between the load and 3510 // the end of block that could change the value. 3511 if (I->mayReadFromMemory()) { 3512 // We don't want to do any sophisticated alias analysis, so we only check 3513 // the instructions after I in I's parent block if we try to sink to its 3514 // successor block. 3515 if (DestBlock->getUniquePredecessor() != I->getParent()) 3516 return false; 3517 for (BasicBlock::iterator Scan = I->getIterator(), 3518 E = I->getParent()->end(); 3519 Scan != E; ++Scan) 3520 if (Scan->mayWriteToMemory()) 3521 return false; 3522 } 3523 3524 I->dropDroppableUses([DestBlock](const Use *U) { 3525 if (auto *I = dyn_cast<Instruction>(U->getUser())) 3526 return I->getParent() != DestBlock; 3527 return true; 3528 }); 3529 /// FIXME: We could remove droppable uses that are not dominated by 3530 /// the new position. 3531 3532 BasicBlock::iterator InsertPos = DestBlock->getFirstInsertionPt(); 3533 I->moveBefore(&*InsertPos); 3534 ++NumSunkInst; 3535 3536 // Also sink all related debug uses from the source basic block. Otherwise we 3537 // get debug use before the def. Attempt to salvage debug uses first, to 3538 // maximise the range variables have location for. If we cannot salvage, then 3539 // mark the location undef: we know it was supposed to receive a new location 3540 // here, but that computation has been sunk. 3541 SmallVector<DbgVariableIntrinsic *, 2> DbgUsers; 3542 findDbgUsers(DbgUsers, I); 3543 3544 // Update the arguments of a dbg.declare instruction, so that it 3545 // does not point into a sunk instruction. 3546 auto updateDbgDeclare = [&I](DbgVariableIntrinsic *DII) { 3547 if (!isa<DbgDeclareInst>(DII)) 3548 return false; 3549 3550 if (isa<CastInst>(I)) 3551 DII->setOperand( 3552 0, MetadataAsValue::get(I->getContext(), 3553 ValueAsMetadata::get(I->getOperand(0)))); 3554 return true; 3555 }; 3556 3557 SmallVector<DbgVariableIntrinsic *, 2> DIIClones; 3558 for (auto User : DbgUsers) { 3559 // A dbg.declare instruction should not be cloned, since there can only be 3560 // one per variable fragment. It should be left in the original place 3561 // because the sunk instruction is not an alloca (otherwise we could not be 3562 // here). 3563 if (User->getParent() != SrcBlock || updateDbgDeclare(User)) 3564 continue; 3565 3566 DIIClones.emplace_back(cast<DbgVariableIntrinsic>(User->clone())); 3567 LLVM_DEBUG(dbgs() << "CLONE: " << *DIIClones.back() << '\n'); 3568 } 3569 3570 // Perform salvaging without the clones, then sink the clones. 3571 if (!DIIClones.empty()) { 3572 salvageDebugInfoForDbgValues(*I, DbgUsers); 3573 for (auto &DIIClone : DIIClones) { 3574 DIIClone->insertBefore(&*InsertPos); 3575 LLVM_DEBUG(dbgs() << "SINK: " << *DIIClone << '\n'); 3576 } 3577 } 3578 3579 return true; 3580 } 3581 3582 bool InstCombinerImpl::run() { 3583 while (!Worklist.isEmpty()) { 3584 // Walk deferred instructions in reverse order, and push them to the 3585 // worklist, which means they'll end up popped from the worklist in-order. 3586 while (Instruction *I = Worklist.popDeferred()) { 3587 // Check to see if we can DCE the instruction. We do this already here to 3588 // reduce the number of uses and thus allow other folds to trigger. 3589 // Note that eraseInstFromFunction() may push additional instructions on 3590 // the deferred worklist, so this will DCE whole instruction chains. 3591 if (isInstructionTriviallyDead(I, &TLI)) { 3592 eraseInstFromFunction(*I); 3593 ++NumDeadInst; 3594 continue; 3595 } 3596 3597 Worklist.push(I); 3598 } 3599 3600 Instruction *I = Worklist.removeOne(); 3601 if (I == nullptr) continue; // skip null values. 3602 3603 // Check to see if we can DCE the instruction. 3604 if (isInstructionTriviallyDead(I, &TLI)) { 3605 eraseInstFromFunction(*I); 3606 ++NumDeadInst; 3607 continue; 3608 } 3609 3610 if (!DebugCounter::shouldExecute(VisitCounter)) 3611 continue; 3612 3613 // Instruction isn't dead, see if we can constant propagate it. 3614 if (!I->use_empty() && 3615 (I->getNumOperands() == 0 || isa<Constant>(I->getOperand(0)))) { 3616 if (Constant *C = ConstantFoldInstruction(I, DL, &TLI)) { 3617 LLVM_DEBUG(dbgs() << "IC: ConstFold to: " << *C << " from: " << *I 3618 << '\n'); 3619 3620 // Add operands to the worklist. 3621 replaceInstUsesWith(*I, C); 3622 ++NumConstProp; 3623 if (isInstructionTriviallyDead(I, &TLI)) 3624 eraseInstFromFunction(*I); 3625 MadeIRChange = true; 3626 continue; 3627 } 3628 } 3629 3630 // See if we can trivially sink this instruction to its user if we can 3631 // prove that the successor is not executed more frequently than our block. 3632 if (EnableCodeSinking) 3633 if (Use *SingleUse = I->getSingleUndroppableUse()) { 3634 BasicBlock *BB = I->getParent(); 3635 Instruction *UserInst = cast<Instruction>(SingleUse->getUser()); 3636 BasicBlock *UserParent; 3637 3638 // Get the block the use occurs in. 3639 if (PHINode *PN = dyn_cast<PHINode>(UserInst)) 3640 UserParent = PN->getIncomingBlock(*SingleUse); 3641 else 3642 UserParent = UserInst->getParent(); 3643 3644 // Try sinking to another block. If that block is unreachable, then do 3645 // not bother. SimplifyCFG should handle it. 3646 if (UserParent != BB && DT.isReachableFromEntry(UserParent)) { 3647 // See if the user is one of our successors that has only one 3648 // predecessor, so that we don't have to split the critical edge. 3649 bool ShouldSink = UserParent->getUniquePredecessor() == BB; 3650 // Another option where we can sink is a block that ends with a 3651 // terminator that does not pass control to other block (such as 3652 // return or unreachable). In this case: 3653 // - I dominates the User (by SSA form); 3654 // - the User will be executed at most once. 3655 // So sinking I down to User is always profitable or neutral. 3656 if (!ShouldSink) { 3657 auto *Term = UserParent->getTerminator(); 3658 ShouldSink = isa<ReturnInst>(Term) || isa<UnreachableInst>(Term); 3659 } 3660 if (ShouldSink) { 3661 assert(DT.dominates(BB, UserParent) && 3662 "Dominance relation broken?"); 3663 // Okay, the CFG is simple enough, try to sink this instruction. 3664 if (TryToSinkInstruction(I, UserParent)) { 3665 LLVM_DEBUG(dbgs() << "IC: Sink: " << *I << '\n'); 3666 MadeIRChange = true; 3667 // We'll add uses of the sunk instruction below, but since sinking 3668 // can expose opportunities for it's *operands* add them to the 3669 // worklist 3670 for (Use &U : I->operands()) 3671 if (Instruction *OpI = dyn_cast<Instruction>(U.get())) 3672 Worklist.push(OpI); 3673 } 3674 } 3675 } 3676 } 3677 3678 // Now that we have an instruction, try combining it to simplify it. 3679 Builder.SetInsertPoint(I); 3680 Builder.CollectMetadataToCopy( 3681 I, {LLVMContext::MD_dbg, LLVMContext::MD_annotation}); 3682 3683 #ifndef NDEBUG 3684 std::string OrigI; 3685 #endif 3686 LLVM_DEBUG(raw_string_ostream SS(OrigI); I->print(SS); OrigI = SS.str();); 3687 LLVM_DEBUG(dbgs() << "IC: Visiting: " << OrigI << '\n'); 3688 3689 if (Instruction *Result = visit(*I)) { 3690 ++NumCombined; 3691 // Should we replace the old instruction with a new one? 3692 if (Result != I) { 3693 LLVM_DEBUG(dbgs() << "IC: Old = " << *I << '\n' 3694 << " New = " << *Result << '\n'); 3695 3696 Result->copyMetadata(*I, 3697 {LLVMContext::MD_dbg, LLVMContext::MD_annotation}); 3698 // Everything uses the new instruction now. 3699 I->replaceAllUsesWith(Result); 3700 3701 // Move the name to the new instruction first. 3702 Result->takeName(I); 3703 3704 // Insert the new instruction into the basic block... 3705 BasicBlock *InstParent = I->getParent(); 3706 BasicBlock::iterator InsertPos = I->getIterator(); 3707 3708 // Are we replace a PHI with something that isn't a PHI, or vice versa? 3709 if (isa<PHINode>(Result) != isa<PHINode>(I)) { 3710 // We need to fix up the insertion point. 3711 if (isa<PHINode>(I)) // PHI -> Non-PHI 3712 InsertPos = InstParent->getFirstInsertionPt(); 3713 else // Non-PHI -> PHI 3714 InsertPos = InstParent->getFirstNonPHI()->getIterator(); 3715 } 3716 3717 InstParent->getInstList().insert(InsertPos, Result); 3718 3719 // Push the new instruction and any users onto the worklist. 3720 Worklist.pushUsersToWorkList(*Result); 3721 Worklist.push(Result); 3722 3723 eraseInstFromFunction(*I); 3724 } else { 3725 LLVM_DEBUG(dbgs() << "IC: Mod = " << OrigI << '\n' 3726 << " New = " << *I << '\n'); 3727 3728 // If the instruction was modified, it's possible that it is now dead. 3729 // if so, remove it. 3730 if (isInstructionTriviallyDead(I, &TLI)) { 3731 eraseInstFromFunction(*I); 3732 } else { 3733 Worklist.pushUsersToWorkList(*I); 3734 Worklist.push(I); 3735 } 3736 } 3737 MadeIRChange = true; 3738 } 3739 } 3740 3741 Worklist.zap(); 3742 return MadeIRChange; 3743 } 3744 3745 /// Populate the IC worklist from a function, by walking it in depth-first 3746 /// order and adding all reachable code to the worklist. 3747 /// 3748 /// This has a couple of tricks to make the code faster and more powerful. In 3749 /// particular, we constant fold and DCE instructions as we go, to avoid adding 3750 /// them to the worklist (this significantly speeds up instcombine on code where 3751 /// many instructions are dead or constant). Additionally, if we find a branch 3752 /// whose condition is a known constant, we only visit the reachable successors. 3753 static bool prepareICWorklistFromFunction(Function &F, const DataLayout &DL, 3754 const TargetLibraryInfo *TLI, 3755 InstCombineWorklist &ICWorklist) { 3756 bool MadeIRChange = false; 3757 SmallPtrSet<BasicBlock *, 32> Visited; 3758 SmallVector<BasicBlock*, 256> Worklist; 3759 Worklist.push_back(&F.front()); 3760 3761 SmallVector<Instruction*, 128> InstrsForInstCombineWorklist; 3762 DenseMap<Constant *, Constant *> FoldedConstants; 3763 3764 do { 3765 BasicBlock *BB = Worklist.pop_back_val(); 3766 3767 // We have now visited this block! If we've already been here, ignore it. 3768 if (!Visited.insert(BB).second) 3769 continue; 3770 3771 for (BasicBlock::iterator BBI = BB->begin(), E = BB->end(); BBI != E; ) { 3772 Instruction *Inst = &*BBI++; 3773 3774 // ConstantProp instruction if trivially constant. 3775 if (!Inst->use_empty() && 3776 (Inst->getNumOperands() == 0 || isa<Constant>(Inst->getOperand(0)))) 3777 if (Constant *C = ConstantFoldInstruction(Inst, DL, TLI)) { 3778 LLVM_DEBUG(dbgs() << "IC: ConstFold to: " << *C << " from: " << *Inst 3779 << '\n'); 3780 Inst->replaceAllUsesWith(C); 3781 ++NumConstProp; 3782 if (isInstructionTriviallyDead(Inst, TLI)) 3783 Inst->eraseFromParent(); 3784 MadeIRChange = true; 3785 continue; 3786 } 3787 3788 // See if we can constant fold its operands. 3789 for (Use &U : Inst->operands()) { 3790 if (!isa<ConstantVector>(U) && !isa<ConstantExpr>(U)) 3791 continue; 3792 3793 auto *C = cast<Constant>(U); 3794 Constant *&FoldRes = FoldedConstants[C]; 3795 if (!FoldRes) 3796 FoldRes = ConstantFoldConstant(C, DL, TLI); 3797 3798 if (FoldRes != C) { 3799 LLVM_DEBUG(dbgs() << "IC: ConstFold operand of: " << *Inst 3800 << "\n Old = " << *C 3801 << "\n New = " << *FoldRes << '\n'); 3802 U = FoldRes; 3803 MadeIRChange = true; 3804 } 3805 } 3806 3807 // Skip processing debug intrinsics in InstCombine. Processing these call instructions 3808 // consumes non-trivial amount of time and provides no value for the optimization. 3809 if (!isa<DbgInfoIntrinsic>(Inst)) 3810 InstrsForInstCombineWorklist.push_back(Inst); 3811 } 3812 3813 // Recursively visit successors. If this is a branch or switch on a 3814 // constant, only visit the reachable successor. 3815 Instruction *TI = BB->getTerminator(); 3816 if (BranchInst *BI = dyn_cast<BranchInst>(TI)) { 3817 if (BI->isConditional() && isa<ConstantInt>(BI->getCondition())) { 3818 bool CondVal = cast<ConstantInt>(BI->getCondition())->getZExtValue(); 3819 BasicBlock *ReachableBB = BI->getSuccessor(!CondVal); 3820 Worklist.push_back(ReachableBB); 3821 continue; 3822 } 3823 } else if (SwitchInst *SI = dyn_cast<SwitchInst>(TI)) { 3824 if (ConstantInt *Cond = dyn_cast<ConstantInt>(SI->getCondition())) { 3825 Worklist.push_back(SI->findCaseValue(Cond)->getCaseSuccessor()); 3826 continue; 3827 } 3828 } 3829 3830 for (BasicBlock *SuccBB : successors(TI)) 3831 Worklist.push_back(SuccBB); 3832 } while (!Worklist.empty()); 3833 3834 // Remove instructions inside unreachable blocks. This prevents the 3835 // instcombine code from having to deal with some bad special cases, and 3836 // reduces use counts of instructions. 3837 for (BasicBlock &BB : F) { 3838 if (Visited.count(&BB)) 3839 continue; 3840 3841 unsigned NumDeadInstInBB; 3842 unsigned NumDeadDbgInstInBB; 3843 std::tie(NumDeadInstInBB, NumDeadDbgInstInBB) = 3844 removeAllNonTerminatorAndEHPadInstructions(&BB); 3845 3846 MadeIRChange |= NumDeadInstInBB + NumDeadDbgInstInBB > 0; 3847 NumDeadInst += NumDeadInstInBB; 3848 } 3849 3850 // Once we've found all of the instructions to add to instcombine's worklist, 3851 // add them in reverse order. This way instcombine will visit from the top 3852 // of the function down. This jives well with the way that it adds all uses 3853 // of instructions to the worklist after doing a transformation, thus avoiding 3854 // some N^2 behavior in pathological cases. 3855 ICWorklist.reserve(InstrsForInstCombineWorklist.size()); 3856 for (Instruction *Inst : reverse(InstrsForInstCombineWorklist)) { 3857 // DCE instruction if trivially dead. As we iterate in reverse program 3858 // order here, we will clean up whole chains of dead instructions. 3859 if (isInstructionTriviallyDead(Inst, TLI)) { 3860 ++NumDeadInst; 3861 LLVM_DEBUG(dbgs() << "IC: DCE: " << *Inst << '\n'); 3862 salvageDebugInfo(*Inst); 3863 Inst->eraseFromParent(); 3864 MadeIRChange = true; 3865 continue; 3866 } 3867 3868 ICWorklist.push(Inst); 3869 } 3870 3871 return MadeIRChange; 3872 } 3873 3874 static bool combineInstructionsOverFunction( 3875 Function &F, InstCombineWorklist &Worklist, AliasAnalysis *AA, 3876 AssumptionCache &AC, TargetLibraryInfo &TLI, TargetTransformInfo &TTI, 3877 DominatorTree &DT, OptimizationRemarkEmitter &ORE, BlockFrequencyInfo *BFI, 3878 ProfileSummaryInfo *PSI, unsigned MaxIterations, LoopInfo *LI) { 3879 auto &DL = F.getParent()->getDataLayout(); 3880 MaxIterations = std::min(MaxIterations, LimitMaxIterations.getValue()); 3881 3882 /// Builder - This is an IRBuilder that automatically inserts new 3883 /// instructions into the worklist when they are created. 3884 IRBuilder<TargetFolder, IRBuilderCallbackInserter> Builder( 3885 F.getContext(), TargetFolder(DL), 3886 IRBuilderCallbackInserter([&Worklist, &AC](Instruction *I) { 3887 Worklist.add(I); 3888 if (match(I, m_Intrinsic<Intrinsic::assume>())) 3889 AC.registerAssumption(cast<CallInst>(I)); 3890 })); 3891 3892 // Lower dbg.declare intrinsics otherwise their value may be clobbered 3893 // by instcombiner. 3894 bool MadeIRChange = false; 3895 if (ShouldLowerDbgDeclare) 3896 MadeIRChange = LowerDbgDeclare(F); 3897 3898 // Iterate while there is work to do. 3899 unsigned Iteration = 0; 3900 while (true) { 3901 ++NumWorklistIterations; 3902 ++Iteration; 3903 3904 if (Iteration > InfiniteLoopDetectionThreshold) { 3905 report_fatal_error( 3906 "Instruction Combining seems stuck in an infinite loop after " + 3907 Twine(InfiniteLoopDetectionThreshold) + " iterations."); 3908 } 3909 3910 if (Iteration > MaxIterations) { 3911 LLVM_DEBUG(dbgs() << "\n\n[IC] Iteration limit #" << MaxIterations 3912 << " on " << F.getName() 3913 << " reached; stopping before reaching a fixpoint\n"); 3914 break; 3915 } 3916 3917 LLVM_DEBUG(dbgs() << "\n\nINSTCOMBINE ITERATION #" << Iteration << " on " 3918 << F.getName() << "\n"); 3919 3920 MadeIRChange |= prepareICWorklistFromFunction(F, DL, &TLI, Worklist); 3921 3922 InstCombinerImpl IC(Worklist, Builder, F.hasMinSize(), AA, AC, TLI, TTI, DT, 3923 ORE, BFI, PSI, DL, LI); 3924 IC.MaxArraySizeForCombine = MaxArraySize; 3925 3926 if (!IC.run()) 3927 break; 3928 3929 MadeIRChange = true; 3930 } 3931 3932 return MadeIRChange; 3933 } 3934 3935 InstCombinePass::InstCombinePass() : MaxIterations(LimitMaxIterations) {} 3936 3937 InstCombinePass::InstCombinePass(unsigned MaxIterations) 3938 : MaxIterations(MaxIterations) {} 3939 3940 PreservedAnalyses InstCombinePass::run(Function &F, 3941 FunctionAnalysisManager &AM) { 3942 auto &AC = AM.getResult<AssumptionAnalysis>(F); 3943 auto &DT = AM.getResult<DominatorTreeAnalysis>(F); 3944 auto &TLI = AM.getResult<TargetLibraryAnalysis>(F); 3945 auto &ORE = AM.getResult<OptimizationRemarkEmitterAnalysis>(F); 3946 auto &TTI = AM.getResult<TargetIRAnalysis>(F); 3947 3948 auto *LI = AM.getCachedResult<LoopAnalysis>(F); 3949 3950 auto *AA = &AM.getResult<AAManager>(F); 3951 auto &MAMProxy = AM.getResult<ModuleAnalysisManagerFunctionProxy>(F); 3952 ProfileSummaryInfo *PSI = 3953 MAMProxy.getCachedResult<ProfileSummaryAnalysis>(*F.getParent()); 3954 auto *BFI = (PSI && PSI->hasProfileSummary()) ? 3955 &AM.getResult<BlockFrequencyAnalysis>(F) : nullptr; 3956 3957 if (!combineInstructionsOverFunction(F, Worklist, AA, AC, TLI, TTI, DT, ORE, 3958 BFI, PSI, MaxIterations, LI)) 3959 // No changes, all analyses are preserved. 3960 return PreservedAnalyses::all(); 3961 3962 // Mark all the analyses that instcombine updates as preserved. 3963 PreservedAnalyses PA; 3964 PA.preserveSet<CFGAnalyses>(); 3965 PA.preserve<AAManager>(); 3966 PA.preserve<BasicAA>(); 3967 PA.preserve<GlobalsAA>(); 3968 return PA; 3969 } 3970 3971 void InstructionCombiningPass::getAnalysisUsage(AnalysisUsage &AU) const { 3972 AU.setPreservesCFG(); 3973 AU.addRequired<AAResultsWrapperPass>(); 3974 AU.addRequired<AssumptionCacheTracker>(); 3975 AU.addRequired<TargetLibraryInfoWrapperPass>(); 3976 AU.addRequired<TargetTransformInfoWrapperPass>(); 3977 AU.addRequired<DominatorTreeWrapperPass>(); 3978 AU.addRequired<OptimizationRemarkEmitterWrapperPass>(); 3979 AU.addPreserved<DominatorTreeWrapperPass>(); 3980 AU.addPreserved<AAResultsWrapperPass>(); 3981 AU.addPreserved<BasicAAWrapperPass>(); 3982 AU.addPreserved<GlobalsAAWrapperPass>(); 3983 AU.addRequired<ProfileSummaryInfoWrapperPass>(); 3984 LazyBlockFrequencyInfoPass::getLazyBFIAnalysisUsage(AU); 3985 } 3986 3987 bool InstructionCombiningPass::runOnFunction(Function &F) { 3988 if (skipFunction(F)) 3989 return false; 3990 3991 // Required analyses. 3992 auto AA = &getAnalysis<AAResultsWrapperPass>().getAAResults(); 3993 auto &AC = getAnalysis<AssumptionCacheTracker>().getAssumptionCache(F); 3994 auto &TLI = getAnalysis<TargetLibraryInfoWrapperPass>().getTLI(F); 3995 auto &TTI = getAnalysis<TargetTransformInfoWrapperPass>().getTTI(F); 3996 auto &DT = getAnalysis<DominatorTreeWrapperPass>().getDomTree(); 3997 auto &ORE = getAnalysis<OptimizationRemarkEmitterWrapperPass>().getORE(); 3998 3999 // Optional analyses. 4000 auto *LIWP = getAnalysisIfAvailable<LoopInfoWrapperPass>(); 4001 auto *LI = LIWP ? &LIWP->getLoopInfo() : nullptr; 4002 ProfileSummaryInfo *PSI = 4003 &getAnalysis<ProfileSummaryInfoWrapperPass>().getPSI(); 4004 BlockFrequencyInfo *BFI = 4005 (PSI && PSI->hasProfileSummary()) ? 4006 &getAnalysis<LazyBlockFrequencyInfoPass>().getBFI() : 4007 nullptr; 4008 4009 return combineInstructionsOverFunction(F, Worklist, AA, AC, TLI, TTI, DT, ORE, 4010 BFI, PSI, MaxIterations, LI); 4011 } 4012 4013 char InstructionCombiningPass::ID = 0; 4014 4015 InstructionCombiningPass::InstructionCombiningPass() 4016 : FunctionPass(ID), MaxIterations(InstCombineDefaultMaxIterations) { 4017 initializeInstructionCombiningPassPass(*PassRegistry::getPassRegistry()); 4018 } 4019 4020 InstructionCombiningPass::InstructionCombiningPass(unsigned MaxIterations) 4021 : FunctionPass(ID), MaxIterations(MaxIterations) { 4022 initializeInstructionCombiningPassPass(*PassRegistry::getPassRegistry()); 4023 } 4024 4025 INITIALIZE_PASS_BEGIN(InstructionCombiningPass, "instcombine", 4026 "Combine redundant instructions", false, false) 4027 INITIALIZE_PASS_DEPENDENCY(AssumptionCacheTracker) 4028 INITIALIZE_PASS_DEPENDENCY(TargetLibraryInfoWrapperPass) 4029 INITIALIZE_PASS_DEPENDENCY(TargetTransformInfoWrapperPass) 4030 INITIALIZE_PASS_DEPENDENCY(DominatorTreeWrapperPass) 4031 INITIALIZE_PASS_DEPENDENCY(AAResultsWrapperPass) 4032 INITIALIZE_PASS_DEPENDENCY(GlobalsAAWrapperPass) 4033 INITIALIZE_PASS_DEPENDENCY(OptimizationRemarkEmitterWrapperPass) 4034 INITIALIZE_PASS_DEPENDENCY(LazyBlockFrequencyInfoPass) 4035 INITIALIZE_PASS_DEPENDENCY(ProfileSummaryInfoWrapperPass) 4036 INITIALIZE_PASS_END(InstructionCombiningPass, "instcombine", 4037 "Combine redundant instructions", false, false) 4038 4039 // Initialization Routines 4040 void llvm::initializeInstCombine(PassRegistry &Registry) { 4041 initializeInstructionCombiningPassPass(Registry); 4042 } 4043 4044 void LLVMInitializeInstCombine(LLVMPassRegistryRef R) { 4045 initializeInstructionCombiningPassPass(*unwrap(R)); 4046 } 4047 4048 FunctionPass *llvm::createInstructionCombiningPass() { 4049 return new InstructionCombiningPass(); 4050 } 4051 4052 FunctionPass *llvm::createInstructionCombiningPass(unsigned MaxIterations) { 4053 return new InstructionCombiningPass(MaxIterations); 4054 } 4055 4056 void LLVMAddInstructionCombiningPass(LLVMPassManagerRef PM) { 4057 unwrap(PM)->add(createInstructionCombiningPass()); 4058 } 4059