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