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