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