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