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