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