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