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