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