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