InstructionCombining.cpp revision 239462
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#define DEBUG_TYPE "instcombine" 37#include "llvm/Transforms/Scalar.h" 38#include "InstCombine.h" 39#include "llvm/IntrinsicInst.h" 40#include "llvm/Analysis/ConstantFolding.h" 41#include "llvm/Analysis/InstructionSimplify.h" 42#include "llvm/Analysis/MemoryBuiltins.h" 43#include "llvm/Target/TargetData.h" 44#include "llvm/Target/TargetLibraryInfo.h" 45#include "llvm/Transforms/Utils/Local.h" 46#include "llvm/Support/CFG.h" 47#include "llvm/Support/Debug.h" 48#include "llvm/Support/GetElementPtrTypeIterator.h" 49#include "llvm/Support/PatternMatch.h" 50#include "llvm/Support/ValueHandle.h" 51#include "llvm/ADT/SmallPtrSet.h" 52#include "llvm/ADT/Statistic.h" 53#include "llvm/ADT/StringSwitch.h" 54#include "llvm-c/Initialization.h" 55#include <algorithm> 56#include <climits> 57using namespace llvm; 58using namespace llvm::PatternMatch; 59 60STATISTIC(NumCombined , "Number of insts combined"); 61STATISTIC(NumConstProp, "Number of constant folds"); 62STATISTIC(NumDeadInst , "Number of dead inst eliminated"); 63STATISTIC(NumSunkInst , "Number of instructions sunk"); 64STATISTIC(NumExpand, "Number of expansions"); 65STATISTIC(NumFactor , "Number of factorizations"); 66STATISTIC(NumReassoc , "Number of reassociations"); 67 68// Initialization Routines 69void llvm::initializeInstCombine(PassRegistry &Registry) { 70 initializeInstCombinerPass(Registry); 71} 72 73void LLVMInitializeInstCombine(LLVMPassRegistryRef R) { 74 initializeInstCombine(*unwrap(R)); 75} 76 77char InstCombiner::ID = 0; 78INITIALIZE_PASS_BEGIN(InstCombiner, "instcombine", 79 "Combine redundant instructions", false, false) 80INITIALIZE_PASS_DEPENDENCY(TargetLibraryInfo) 81INITIALIZE_PASS_END(InstCombiner, "instcombine", 82 "Combine redundant instructions", false, false) 83 84void InstCombiner::getAnalysisUsage(AnalysisUsage &AU) const { 85 AU.setPreservesCFG(); 86 AU.addRequired<TargetLibraryInfo>(); 87} 88 89 90Value *InstCombiner::EmitGEPOffset(User *GEP) { 91 return llvm::EmitGEPOffset(Builder, *getTargetData(), GEP); 92} 93 94/// ShouldChangeType - Return true if it is desirable to convert a computation 95/// from 'From' to 'To'. We don't want to convert from a legal to an illegal 96/// type for example, or from a smaller to a larger illegal type. 97bool InstCombiner::ShouldChangeType(Type *From, Type *To) const { 98 assert(From->isIntegerTy() && To->isIntegerTy()); 99 100 // If we don't have TD, we don't know if the source/dest are legal. 101 if (!TD) return false; 102 103 unsigned FromWidth = From->getPrimitiveSizeInBits(); 104 unsigned ToWidth = To->getPrimitiveSizeInBits(); 105 bool FromLegal = TD->isLegalInteger(FromWidth); 106 bool ToLegal = TD->isLegalInteger(ToWidth); 107 108 // If this is a legal integer from type, and the result would be an illegal 109 // type, don't do the transformation. 110 if (FromLegal && !ToLegal) 111 return false; 112 113 // Otherwise, if both are illegal, do not increase the size of the result. We 114 // do allow things like i160 -> i64, but not i64 -> i160. 115 if (!FromLegal && !ToLegal && ToWidth > FromWidth) 116 return false; 117 118 return true; 119} 120 121// Return true, if No Signed Wrap should be maintained for I. 122// The No Signed Wrap flag can be kept if the operation "B (I.getOpcode) C", 123// where both B and C should be ConstantInts, results in a constant that does 124// not overflow. This function only handles the Add and Sub opcodes. For 125// all other opcodes, the function conservatively returns false. 126static bool MaintainNoSignedWrap(BinaryOperator &I, Value *B, Value *C) { 127 OverflowingBinaryOperator *OBO = dyn_cast<OverflowingBinaryOperator>(&I); 128 if (!OBO || !OBO->hasNoSignedWrap()) { 129 return false; 130 } 131 132 // We reason about Add and Sub Only. 133 Instruction::BinaryOps Opcode = I.getOpcode(); 134 if (Opcode != Instruction::Add && 135 Opcode != Instruction::Sub) { 136 return false; 137 } 138 139 ConstantInt *CB = dyn_cast<ConstantInt>(B); 140 ConstantInt *CC = dyn_cast<ConstantInt>(C); 141 142 if (!CB || !CC) { 143 return false; 144 } 145 146 const APInt &BVal = CB->getValue(); 147 const APInt &CVal = CC->getValue(); 148 bool Overflow = false; 149 150 if (Opcode == Instruction::Add) { 151 BVal.sadd_ov(CVal, Overflow); 152 } else { 153 BVal.ssub_ov(CVal, Overflow); 154 } 155 156 return !Overflow; 157} 158 159/// SimplifyAssociativeOrCommutative - This performs a few simplifications for 160/// operators which are associative or commutative: 161// 162// Commutative operators: 163// 164// 1. Order operands such that they are listed from right (least complex) to 165// left (most complex). This puts constants before unary operators before 166// binary operators. 167// 168// Associative operators: 169// 170// 2. Transform: "(A op B) op C" ==> "A op (B op C)" if "B op C" simplifies. 171// 3. Transform: "A op (B op C)" ==> "(A op B) op C" if "A op B" simplifies. 172// 173// Associative and commutative operators: 174// 175// 4. Transform: "(A op B) op C" ==> "(C op A) op B" if "C op A" simplifies. 176// 5. Transform: "A op (B op C)" ==> "B op (C op A)" if "C op A" simplifies. 177// 6. Transform: "(A op C1) op (B op C2)" ==> "(A op B) op (C1 op C2)" 178// if C1 and C2 are constants. 179// 180bool InstCombiner::SimplifyAssociativeOrCommutative(BinaryOperator &I) { 181 Instruction::BinaryOps Opcode = I.getOpcode(); 182 bool Changed = false; 183 184 do { 185 // Order operands such that they are listed from right (least complex) to 186 // left (most complex). This puts constants before unary operators before 187 // binary operators. 188 if (I.isCommutative() && getComplexity(I.getOperand(0)) < 189 getComplexity(I.getOperand(1))) 190 Changed = !I.swapOperands(); 191 192 BinaryOperator *Op0 = dyn_cast<BinaryOperator>(I.getOperand(0)); 193 BinaryOperator *Op1 = dyn_cast<BinaryOperator>(I.getOperand(1)); 194 195 if (I.isAssociative()) { 196 // Transform: "(A op B) op C" ==> "A op (B op C)" if "B op C" simplifies. 197 if (Op0 && Op0->getOpcode() == Opcode) { 198 Value *A = Op0->getOperand(0); 199 Value *B = Op0->getOperand(1); 200 Value *C = I.getOperand(1); 201 202 // Does "B op C" simplify? 203 if (Value *V = SimplifyBinOp(Opcode, B, C, TD)) { 204 // It simplifies to V. Form "A op V". 205 I.setOperand(0, A); 206 I.setOperand(1, V); 207 // Conservatively clear the optional flags, since they may not be 208 // preserved by the reassociation. 209 if (MaintainNoSignedWrap(I, B, C) && 210 (!Op0 || (isa<BinaryOperator>(Op0) && Op0->hasNoSignedWrap()))) { 211 // Note: this is only valid because SimplifyBinOp doesn't look at 212 // the operands to Op0. 213 I.clearSubclassOptionalData(); 214 I.setHasNoSignedWrap(true); 215 } else { 216 I.clearSubclassOptionalData(); 217 } 218 219 Changed = true; 220 ++NumReassoc; 221 continue; 222 } 223 } 224 225 // Transform: "A op (B op C)" ==> "(A op B) op C" if "A op B" simplifies. 226 if (Op1 && Op1->getOpcode() == Opcode) { 227 Value *A = I.getOperand(0); 228 Value *B = Op1->getOperand(0); 229 Value *C = Op1->getOperand(1); 230 231 // Does "A op B" simplify? 232 if (Value *V = SimplifyBinOp(Opcode, A, B, TD)) { 233 // It simplifies to V. Form "V op C". 234 I.setOperand(0, V); 235 I.setOperand(1, C); 236 // Conservatively clear the optional flags, since they may not be 237 // preserved by the reassociation. 238 I.clearSubclassOptionalData(); 239 Changed = true; 240 ++NumReassoc; 241 continue; 242 } 243 } 244 } 245 246 if (I.isAssociative() && I.isCommutative()) { 247 // Transform: "(A op B) op C" ==> "(C op A) op B" if "C op A" simplifies. 248 if (Op0 && Op0->getOpcode() == Opcode) { 249 Value *A = Op0->getOperand(0); 250 Value *B = Op0->getOperand(1); 251 Value *C = I.getOperand(1); 252 253 // Does "C op A" simplify? 254 if (Value *V = SimplifyBinOp(Opcode, C, A, TD)) { 255 // It simplifies to V. Form "V op B". 256 I.setOperand(0, V); 257 I.setOperand(1, B); 258 // Conservatively clear the optional flags, since they may not be 259 // preserved by the reassociation. 260 I.clearSubclassOptionalData(); 261 Changed = true; 262 ++NumReassoc; 263 continue; 264 } 265 } 266 267 // Transform: "A op (B op C)" ==> "B op (C op A)" if "C op A" simplifies. 268 if (Op1 && Op1->getOpcode() == Opcode) { 269 Value *A = I.getOperand(0); 270 Value *B = Op1->getOperand(0); 271 Value *C = Op1->getOperand(1); 272 273 // Does "C op A" simplify? 274 if (Value *V = SimplifyBinOp(Opcode, C, A, TD)) { 275 // It simplifies to V. Form "B op V". 276 I.setOperand(0, B); 277 I.setOperand(1, V); 278 // Conservatively clear the optional flags, since they may not be 279 // preserved by the reassociation. 280 I.clearSubclassOptionalData(); 281 Changed = true; 282 ++NumReassoc; 283 continue; 284 } 285 } 286 287 // Transform: "(A op C1) op (B op C2)" ==> "(A op B) op (C1 op C2)" 288 // if C1 and C2 are constants. 289 if (Op0 && Op1 && 290 Op0->getOpcode() == Opcode && Op1->getOpcode() == Opcode && 291 isa<Constant>(Op0->getOperand(1)) && 292 isa<Constant>(Op1->getOperand(1)) && 293 Op0->hasOneUse() && Op1->hasOneUse()) { 294 Value *A = Op0->getOperand(0); 295 Constant *C1 = cast<Constant>(Op0->getOperand(1)); 296 Value *B = Op1->getOperand(0); 297 Constant *C2 = cast<Constant>(Op1->getOperand(1)); 298 299 Constant *Folded = ConstantExpr::get(Opcode, C1, C2); 300 BinaryOperator *New = BinaryOperator::Create(Opcode, A, B); 301 InsertNewInstWith(New, I); 302 New->takeName(Op1); 303 I.setOperand(0, New); 304 I.setOperand(1, Folded); 305 // Conservatively clear the optional flags, since they may not be 306 // preserved by the reassociation. 307 I.clearSubclassOptionalData(); 308 309 Changed = true; 310 continue; 311 } 312 } 313 314 // No further simplifications. 315 return Changed; 316 } while (1); 317} 318 319/// LeftDistributesOverRight - Whether "X LOp (Y ROp Z)" is always equal to 320/// "(X LOp Y) ROp (X LOp Z)". 321static bool LeftDistributesOverRight(Instruction::BinaryOps LOp, 322 Instruction::BinaryOps ROp) { 323 switch (LOp) { 324 default: 325 return false; 326 327 case Instruction::And: 328 // And distributes over Or and Xor. 329 switch (ROp) { 330 default: 331 return false; 332 case Instruction::Or: 333 case Instruction::Xor: 334 return true; 335 } 336 337 case Instruction::Mul: 338 // Multiplication distributes over addition and subtraction. 339 switch (ROp) { 340 default: 341 return false; 342 case Instruction::Add: 343 case Instruction::Sub: 344 return true; 345 } 346 347 case Instruction::Or: 348 // Or distributes over And. 349 switch (ROp) { 350 default: 351 return false; 352 case Instruction::And: 353 return true; 354 } 355 } 356} 357 358/// RightDistributesOverLeft - Whether "(X LOp Y) ROp Z" is always equal to 359/// "(X ROp Z) LOp (Y ROp Z)". 360static bool RightDistributesOverLeft(Instruction::BinaryOps LOp, 361 Instruction::BinaryOps ROp) { 362 if (Instruction::isCommutative(ROp)) 363 return LeftDistributesOverRight(ROp, LOp); 364 // TODO: It would be nice to handle division, aka "(X + Y)/Z = X/Z + Y/Z", 365 // but this requires knowing that the addition does not overflow and other 366 // such subtleties. 367 return false; 368} 369 370/// SimplifyUsingDistributiveLaws - This tries to simplify binary operations 371/// which some other binary operation distributes over either by factorizing 372/// out common terms (eg "(A*B)+(A*C)" -> "A*(B+C)") or expanding out if this 373/// results in simplifications (eg: "A & (B | C) -> (A&B) | (A&C)" if this is 374/// a win). Returns the simplified value, or null if it didn't simplify. 375Value *InstCombiner::SimplifyUsingDistributiveLaws(BinaryOperator &I) { 376 Value *LHS = I.getOperand(0), *RHS = I.getOperand(1); 377 BinaryOperator *Op0 = dyn_cast<BinaryOperator>(LHS); 378 BinaryOperator *Op1 = dyn_cast<BinaryOperator>(RHS); 379 Instruction::BinaryOps TopLevelOpcode = I.getOpcode(); // op 380 381 // Factorization. 382 if (Op0 && Op1 && Op0->getOpcode() == Op1->getOpcode()) { 383 // The instruction has the form "(A op' B) op (C op' D)". Try to factorize 384 // a common term. 385 Value *A = Op0->getOperand(0), *B = Op0->getOperand(1); 386 Value *C = Op1->getOperand(0), *D = Op1->getOperand(1); 387 Instruction::BinaryOps InnerOpcode = Op0->getOpcode(); // op' 388 389 // Does "X op' Y" always equal "Y op' X"? 390 bool InnerCommutative = Instruction::isCommutative(InnerOpcode); 391 392 // Does "X op' (Y op Z)" always equal "(X op' Y) op (X op' Z)"? 393 if (LeftDistributesOverRight(InnerOpcode, TopLevelOpcode)) 394 // Does the instruction have the form "(A op' B) op (A op' D)" or, in the 395 // commutative case, "(A op' B) op (C op' A)"? 396 if (A == C || (InnerCommutative && A == D)) { 397 if (A != C) 398 std::swap(C, D); 399 // Consider forming "A op' (B op D)". 400 // If "B op D" simplifies then it can be formed with no cost. 401 Value *V = SimplifyBinOp(TopLevelOpcode, B, D, TD); 402 // If "B op D" doesn't simplify then only go on if both of the existing 403 // operations "A op' B" and "C op' D" will be zapped as no longer used. 404 if (!V && Op0->hasOneUse() && Op1->hasOneUse()) 405 V = Builder->CreateBinOp(TopLevelOpcode, B, D, Op1->getName()); 406 if (V) { 407 ++NumFactor; 408 V = Builder->CreateBinOp(InnerOpcode, A, V); 409 V->takeName(&I); 410 return V; 411 } 412 } 413 414 // Does "(X op Y) op' Z" always equal "(X op' Z) op (Y op' Z)"? 415 if (RightDistributesOverLeft(TopLevelOpcode, InnerOpcode)) 416 // Does the instruction have the form "(A op' B) op (C op' B)" or, in the 417 // commutative case, "(A op' B) op (B op' D)"? 418 if (B == D || (InnerCommutative && B == C)) { 419 if (B != D) 420 std::swap(C, D); 421 // Consider forming "(A op C) op' B". 422 // If "A op C" simplifies then it can be formed with no cost. 423 Value *V = SimplifyBinOp(TopLevelOpcode, A, C, TD); 424 // If "A op C" doesn't simplify then only go on if both of the existing 425 // operations "A op' B" and "C op' D" will be zapped as no longer used. 426 if (!V && Op0->hasOneUse() && Op1->hasOneUse()) 427 V = Builder->CreateBinOp(TopLevelOpcode, A, C, Op0->getName()); 428 if (V) { 429 ++NumFactor; 430 V = Builder->CreateBinOp(InnerOpcode, V, B); 431 V->takeName(&I); 432 return V; 433 } 434 } 435 } 436 437 // Expansion. 438 if (Op0 && RightDistributesOverLeft(Op0->getOpcode(), TopLevelOpcode)) { 439 // The instruction has the form "(A op' B) op C". See if expanding it out 440 // to "(A op C) op' (B op C)" results in simplifications. 441 Value *A = Op0->getOperand(0), *B = Op0->getOperand(1), *C = RHS; 442 Instruction::BinaryOps InnerOpcode = Op0->getOpcode(); // op' 443 444 // Do "A op C" and "B op C" both simplify? 445 if (Value *L = SimplifyBinOp(TopLevelOpcode, A, C, TD)) 446 if (Value *R = SimplifyBinOp(TopLevelOpcode, B, C, TD)) { 447 // They do! Return "L op' R". 448 ++NumExpand; 449 // If "L op' R" equals "A op' B" then "L op' R" is just the LHS. 450 if ((L == A && R == B) || 451 (Instruction::isCommutative(InnerOpcode) && L == B && R == A)) 452 return Op0; 453 // Otherwise return "L op' R" if it simplifies. 454 if (Value *V = SimplifyBinOp(InnerOpcode, L, R, TD)) 455 return V; 456 // Otherwise, create a new instruction. 457 C = Builder->CreateBinOp(InnerOpcode, L, R); 458 C->takeName(&I); 459 return C; 460 } 461 } 462 463 if (Op1 && LeftDistributesOverRight(TopLevelOpcode, Op1->getOpcode())) { 464 // The instruction has the form "A op (B op' C)". See if expanding it out 465 // to "(A op B) op' (A op C)" results in simplifications. 466 Value *A = LHS, *B = Op1->getOperand(0), *C = Op1->getOperand(1); 467 Instruction::BinaryOps InnerOpcode = Op1->getOpcode(); // op' 468 469 // Do "A op B" and "A op C" both simplify? 470 if (Value *L = SimplifyBinOp(TopLevelOpcode, A, B, TD)) 471 if (Value *R = SimplifyBinOp(TopLevelOpcode, A, C, TD)) { 472 // They do! Return "L op' R". 473 ++NumExpand; 474 // If "L op' R" equals "B op' C" then "L op' R" is just the RHS. 475 if ((L == B && R == C) || 476 (Instruction::isCommutative(InnerOpcode) && L == C && R == B)) 477 return Op1; 478 // Otherwise return "L op' R" if it simplifies. 479 if (Value *V = SimplifyBinOp(InnerOpcode, L, R, TD)) 480 return V; 481 // Otherwise, create a new instruction. 482 A = Builder->CreateBinOp(InnerOpcode, L, R); 483 A->takeName(&I); 484 return A; 485 } 486 } 487 488 return 0; 489} 490 491// dyn_castNegVal - Given a 'sub' instruction, return the RHS of the instruction 492// if the LHS is a constant zero (which is the 'negate' form). 493// 494Value *InstCombiner::dyn_castNegVal(Value *V) const { 495 if (BinaryOperator::isNeg(V)) 496 return BinaryOperator::getNegArgument(V); 497 498 // Constants can be considered to be negated values if they can be folded. 499 if (ConstantInt *C = dyn_cast<ConstantInt>(V)) 500 return ConstantExpr::getNeg(C); 501 502 if (ConstantDataVector *C = dyn_cast<ConstantDataVector>(V)) 503 if (C->getType()->getElementType()->isIntegerTy()) 504 return ConstantExpr::getNeg(C); 505 506 return 0; 507} 508 509// dyn_castFNegVal - Given a 'fsub' instruction, return the RHS of the 510// instruction if the LHS is a constant negative zero (which is the 'negate' 511// form). 512// 513Value *InstCombiner::dyn_castFNegVal(Value *V) const { 514 if (BinaryOperator::isFNeg(V)) 515 return BinaryOperator::getFNegArgument(V); 516 517 // Constants can be considered to be negated values if they can be folded. 518 if (ConstantFP *C = dyn_cast<ConstantFP>(V)) 519 return ConstantExpr::getFNeg(C); 520 521 if (ConstantDataVector *C = dyn_cast<ConstantDataVector>(V)) 522 if (C->getType()->getElementType()->isFloatingPointTy()) 523 return ConstantExpr::getFNeg(C); 524 525 return 0; 526} 527 528static Value *FoldOperationIntoSelectOperand(Instruction &I, Value *SO, 529 InstCombiner *IC) { 530 if (CastInst *CI = dyn_cast<CastInst>(&I)) { 531 return IC->Builder->CreateCast(CI->getOpcode(), SO, I.getType()); 532 } 533 534 // Figure out if the constant is the left or the right argument. 535 bool ConstIsRHS = isa<Constant>(I.getOperand(1)); 536 Constant *ConstOperand = cast<Constant>(I.getOperand(ConstIsRHS)); 537 538 if (Constant *SOC = dyn_cast<Constant>(SO)) { 539 if (ConstIsRHS) 540 return ConstantExpr::get(I.getOpcode(), SOC, ConstOperand); 541 return ConstantExpr::get(I.getOpcode(), ConstOperand, SOC); 542 } 543 544 Value *Op0 = SO, *Op1 = ConstOperand; 545 if (!ConstIsRHS) 546 std::swap(Op0, Op1); 547 548 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(&I)) 549 return IC->Builder->CreateBinOp(BO->getOpcode(), Op0, Op1, 550 SO->getName()+".op"); 551 if (ICmpInst *CI = dyn_cast<ICmpInst>(&I)) 552 return IC->Builder->CreateICmp(CI->getPredicate(), Op0, Op1, 553 SO->getName()+".cmp"); 554 if (FCmpInst *CI = dyn_cast<FCmpInst>(&I)) 555 return IC->Builder->CreateICmp(CI->getPredicate(), Op0, Op1, 556 SO->getName()+".cmp"); 557 llvm_unreachable("Unknown binary instruction type!"); 558} 559 560// FoldOpIntoSelect - Given an instruction with a select as one operand and a 561// constant as the other operand, try to fold the binary operator into the 562// select arguments. This also works for Cast instructions, which obviously do 563// not have a second operand. 564Instruction *InstCombiner::FoldOpIntoSelect(Instruction &Op, SelectInst *SI) { 565 // Don't modify shared select instructions 566 if (!SI->hasOneUse()) return 0; 567 Value *TV = SI->getOperand(1); 568 Value *FV = SI->getOperand(2); 569 570 if (isa<Constant>(TV) || isa<Constant>(FV)) { 571 // Bool selects with constant operands can be folded to logical ops. 572 if (SI->getType()->isIntegerTy(1)) return 0; 573 574 // If it's a bitcast involving vectors, make sure it has the same number of 575 // elements on both sides. 576 if (BitCastInst *BC = dyn_cast<BitCastInst>(&Op)) { 577 VectorType *DestTy = dyn_cast<VectorType>(BC->getDestTy()); 578 VectorType *SrcTy = dyn_cast<VectorType>(BC->getSrcTy()); 579 580 // Verify that either both or neither are vectors. 581 if ((SrcTy == NULL) != (DestTy == NULL)) return 0; 582 // If vectors, verify that they have the same number of elements. 583 if (SrcTy && SrcTy->getNumElements() != DestTy->getNumElements()) 584 return 0; 585 } 586 587 Value *SelectTrueVal = FoldOperationIntoSelectOperand(Op, TV, this); 588 Value *SelectFalseVal = FoldOperationIntoSelectOperand(Op, FV, this); 589 590 return SelectInst::Create(SI->getCondition(), 591 SelectTrueVal, SelectFalseVal); 592 } 593 return 0; 594} 595 596 597/// FoldOpIntoPhi - Given a binary operator, cast instruction, or select which 598/// has a PHI node as operand #0, see if we can fold the instruction into the 599/// PHI (which is only possible if all operands to the PHI are constants). 600/// 601Instruction *InstCombiner::FoldOpIntoPhi(Instruction &I) { 602 PHINode *PN = cast<PHINode>(I.getOperand(0)); 603 unsigned NumPHIValues = PN->getNumIncomingValues(); 604 if (NumPHIValues == 0) 605 return 0; 606 607 // We normally only transform phis with a single use. However, if a PHI has 608 // multiple uses and they are all the same operation, we can fold *all* of the 609 // uses into the PHI. 610 if (!PN->hasOneUse()) { 611 // Walk the use list for the instruction, comparing them to I. 612 for (Value::use_iterator UI = PN->use_begin(), E = PN->use_end(); 613 UI != E; ++UI) { 614 Instruction *User = cast<Instruction>(*UI); 615 if (User != &I && !I.isIdenticalTo(User)) 616 return 0; 617 } 618 // Otherwise, we can replace *all* users with the new PHI we form. 619 } 620 621 // Check to see if all of the operands of the PHI are simple constants 622 // (constantint/constantfp/undef). If there is one non-constant value, 623 // remember the BB it is in. If there is more than one or if *it* is a PHI, 624 // bail out. We don't do arbitrary constant expressions here because moving 625 // their computation can be expensive without a cost model. 626 BasicBlock *NonConstBB = 0; 627 for (unsigned i = 0; i != NumPHIValues; ++i) { 628 Value *InVal = PN->getIncomingValue(i); 629 if (isa<Constant>(InVal) && !isa<ConstantExpr>(InVal)) 630 continue; 631 632 if (isa<PHINode>(InVal)) return 0; // Itself a phi. 633 if (NonConstBB) return 0; // More than one non-const value. 634 635 NonConstBB = PN->getIncomingBlock(i); 636 637 // If the InVal is an invoke at the end of the pred block, then we can't 638 // insert a computation after it without breaking the edge. 639 if (InvokeInst *II = dyn_cast<InvokeInst>(InVal)) 640 if (II->getParent() == NonConstBB) 641 return 0; 642 643 // If the incoming non-constant value is in I's block, we will remove one 644 // instruction, but insert another equivalent one, leading to infinite 645 // instcombine. 646 if (NonConstBB == I.getParent()) 647 return 0; 648 } 649 650 // If there is exactly one non-constant value, we can insert a copy of the 651 // operation in that block. However, if this is a critical edge, we would be 652 // inserting the computation one some other paths (e.g. inside a loop). Only 653 // do this if the pred block is unconditionally branching into the phi block. 654 if (NonConstBB != 0) { 655 BranchInst *BI = dyn_cast<BranchInst>(NonConstBB->getTerminator()); 656 if (!BI || !BI->isUnconditional()) return 0; 657 } 658 659 // Okay, we can do the transformation: create the new PHI node. 660 PHINode *NewPN = PHINode::Create(I.getType(), PN->getNumIncomingValues()); 661 InsertNewInstBefore(NewPN, *PN); 662 NewPN->takeName(PN); 663 664 // If we are going to have to insert a new computation, do so right before the 665 // predecessors terminator. 666 if (NonConstBB) 667 Builder->SetInsertPoint(NonConstBB->getTerminator()); 668 669 // Next, add all of the operands to the PHI. 670 if (SelectInst *SI = dyn_cast<SelectInst>(&I)) { 671 // We only currently try to fold the condition of a select when it is a phi, 672 // not the true/false values. 673 Value *TrueV = SI->getTrueValue(); 674 Value *FalseV = SI->getFalseValue(); 675 BasicBlock *PhiTransBB = PN->getParent(); 676 for (unsigned i = 0; i != NumPHIValues; ++i) { 677 BasicBlock *ThisBB = PN->getIncomingBlock(i); 678 Value *TrueVInPred = TrueV->DoPHITranslation(PhiTransBB, ThisBB); 679 Value *FalseVInPred = FalseV->DoPHITranslation(PhiTransBB, ThisBB); 680 Value *InV = 0; 681 if (Constant *InC = dyn_cast<Constant>(PN->getIncomingValue(i))) 682 InV = InC->isNullValue() ? FalseVInPred : TrueVInPred; 683 else 684 InV = Builder->CreateSelect(PN->getIncomingValue(i), 685 TrueVInPred, FalseVInPred, "phitmp"); 686 NewPN->addIncoming(InV, ThisBB); 687 } 688 } else if (CmpInst *CI = dyn_cast<CmpInst>(&I)) { 689 Constant *C = cast<Constant>(I.getOperand(1)); 690 for (unsigned i = 0; i != NumPHIValues; ++i) { 691 Value *InV = 0; 692 if (Constant *InC = dyn_cast<Constant>(PN->getIncomingValue(i))) 693 InV = ConstantExpr::getCompare(CI->getPredicate(), InC, C); 694 else if (isa<ICmpInst>(CI)) 695 InV = Builder->CreateICmp(CI->getPredicate(), PN->getIncomingValue(i), 696 C, "phitmp"); 697 else 698 InV = Builder->CreateFCmp(CI->getPredicate(), PN->getIncomingValue(i), 699 C, "phitmp"); 700 NewPN->addIncoming(InV, PN->getIncomingBlock(i)); 701 } 702 } else if (I.getNumOperands() == 2) { 703 Constant *C = cast<Constant>(I.getOperand(1)); 704 for (unsigned i = 0; i != NumPHIValues; ++i) { 705 Value *InV = 0; 706 if (Constant *InC = dyn_cast<Constant>(PN->getIncomingValue(i))) 707 InV = ConstantExpr::get(I.getOpcode(), InC, C); 708 else 709 InV = Builder->CreateBinOp(cast<BinaryOperator>(I).getOpcode(), 710 PN->getIncomingValue(i), C, "phitmp"); 711 NewPN->addIncoming(InV, PN->getIncomingBlock(i)); 712 } 713 } else { 714 CastInst *CI = cast<CastInst>(&I); 715 Type *RetTy = CI->getType(); 716 for (unsigned i = 0; i != NumPHIValues; ++i) { 717 Value *InV; 718 if (Constant *InC = dyn_cast<Constant>(PN->getIncomingValue(i))) 719 InV = ConstantExpr::getCast(CI->getOpcode(), InC, RetTy); 720 else 721 InV = Builder->CreateCast(CI->getOpcode(), 722 PN->getIncomingValue(i), I.getType(), "phitmp"); 723 NewPN->addIncoming(InV, PN->getIncomingBlock(i)); 724 } 725 } 726 727 for (Value::use_iterator UI = PN->use_begin(), E = PN->use_end(); 728 UI != E; ) { 729 Instruction *User = cast<Instruction>(*UI++); 730 if (User == &I) continue; 731 ReplaceInstUsesWith(*User, NewPN); 732 EraseInstFromFunction(*User); 733 } 734 return ReplaceInstUsesWith(I, NewPN); 735} 736 737/// FindElementAtOffset - Given a type and a constant offset, determine whether 738/// or not there is a sequence of GEP indices into the type that will land us at 739/// the specified offset. If so, fill them into NewIndices and return the 740/// resultant element type, otherwise return null. 741Type *InstCombiner::FindElementAtOffset(Type *Ty, int64_t Offset, 742 SmallVectorImpl<Value*> &NewIndices) { 743 if (!TD) return 0; 744 if (!Ty->isSized()) return 0; 745 746 // Start with the index over the outer type. Note that the type size 747 // might be zero (even if the offset isn't zero) if the indexed type 748 // is something like [0 x {int, int}] 749 Type *IntPtrTy = TD->getIntPtrType(Ty->getContext()); 750 int64_t FirstIdx = 0; 751 if (int64_t TySize = TD->getTypeAllocSize(Ty)) { 752 FirstIdx = Offset/TySize; 753 Offset -= FirstIdx*TySize; 754 755 // Handle hosts where % returns negative instead of values [0..TySize). 756 if (Offset < 0) { 757 --FirstIdx; 758 Offset += TySize; 759 assert(Offset >= 0); 760 } 761 assert((uint64_t)Offset < (uint64_t)TySize && "Out of range offset"); 762 } 763 764 NewIndices.push_back(ConstantInt::get(IntPtrTy, FirstIdx)); 765 766 // Index into the types. If we fail, set OrigBase to null. 767 while (Offset) { 768 // Indexing into tail padding between struct/array elements. 769 if (uint64_t(Offset*8) >= TD->getTypeSizeInBits(Ty)) 770 return 0; 771 772 if (StructType *STy = dyn_cast<StructType>(Ty)) { 773 const StructLayout *SL = TD->getStructLayout(STy); 774 assert(Offset < (int64_t)SL->getSizeInBytes() && 775 "Offset must stay within the indexed type"); 776 777 unsigned Elt = SL->getElementContainingOffset(Offset); 778 NewIndices.push_back(ConstantInt::get(Type::getInt32Ty(Ty->getContext()), 779 Elt)); 780 781 Offset -= SL->getElementOffset(Elt); 782 Ty = STy->getElementType(Elt); 783 } else if (ArrayType *AT = dyn_cast<ArrayType>(Ty)) { 784 uint64_t EltSize = TD->getTypeAllocSize(AT->getElementType()); 785 assert(EltSize && "Cannot index into a zero-sized array"); 786 NewIndices.push_back(ConstantInt::get(IntPtrTy,Offset/EltSize)); 787 Offset %= EltSize; 788 Ty = AT->getElementType(); 789 } else { 790 // Otherwise, we can't index into the middle of this atomic type, bail. 791 return 0; 792 } 793 } 794 795 return Ty; 796} 797 798static bool shouldMergeGEPs(GEPOperator &GEP, GEPOperator &Src) { 799 // If this GEP has only 0 indices, it is the same pointer as 800 // Src. If Src is not a trivial GEP too, don't combine 801 // the indices. 802 if (GEP.hasAllZeroIndices() && !Src.hasAllZeroIndices() && 803 !Src.hasOneUse()) 804 return false; 805 return true; 806} 807 808Instruction *InstCombiner::visitGetElementPtrInst(GetElementPtrInst &GEP) { 809 SmallVector<Value*, 8> Ops(GEP.op_begin(), GEP.op_end()); 810 811 if (Value *V = SimplifyGEPInst(Ops, TD)) 812 return ReplaceInstUsesWith(GEP, V); 813 814 Value *PtrOp = GEP.getOperand(0); 815 816 // Eliminate unneeded casts for indices, and replace indices which displace 817 // by multiples of a zero size type with zero. 818 if (TD) { 819 bool MadeChange = false; 820 Type *IntPtrTy = TD->getIntPtrType(GEP.getContext()); 821 822 gep_type_iterator GTI = gep_type_begin(GEP); 823 for (User::op_iterator I = GEP.op_begin() + 1, E = GEP.op_end(); 824 I != E; ++I, ++GTI) { 825 // Skip indices into struct types. 826 SequentialType *SeqTy = dyn_cast<SequentialType>(*GTI); 827 if (!SeqTy) continue; 828 829 // If the element type has zero size then any index over it is equivalent 830 // to an index of zero, so replace it with zero if it is not zero already. 831 if (SeqTy->getElementType()->isSized() && 832 TD->getTypeAllocSize(SeqTy->getElementType()) == 0) 833 if (!isa<Constant>(*I) || !cast<Constant>(*I)->isNullValue()) { 834 *I = Constant::getNullValue(IntPtrTy); 835 MadeChange = true; 836 } 837 838 Type *IndexTy = (*I)->getType(); 839 if (IndexTy != IntPtrTy && !IndexTy->isVectorTy()) { 840 // If we are using a wider index than needed for this platform, shrink 841 // it to what we need. If narrower, sign-extend it to what we need. 842 // This explicit cast can make subsequent optimizations more obvious. 843 *I = Builder->CreateIntCast(*I, IntPtrTy, true); 844 MadeChange = true; 845 } 846 } 847 if (MadeChange) return &GEP; 848 } 849 850 // Combine Indices - If the source pointer to this getelementptr instruction 851 // is a getelementptr instruction, combine the indices of the two 852 // getelementptr instructions into a single instruction. 853 // 854 if (GEPOperator *Src = dyn_cast<GEPOperator>(PtrOp)) { 855 if (!shouldMergeGEPs(*cast<GEPOperator>(&GEP), *Src)) 856 return 0; 857 858 // Note that if our source is a gep chain itself that we wait for that 859 // chain to be resolved before we perform this transformation. This 860 // avoids us creating a TON of code in some cases. 861 if (GEPOperator *SrcGEP = 862 dyn_cast<GEPOperator>(Src->getOperand(0))) 863 if (SrcGEP->getNumOperands() == 2 && shouldMergeGEPs(*Src, *SrcGEP)) 864 return 0; // Wait until our source is folded to completion. 865 866 SmallVector<Value*, 8> Indices; 867 868 // Find out whether the last index in the source GEP is a sequential idx. 869 bool EndsWithSequential = false; 870 for (gep_type_iterator I = gep_type_begin(*Src), E = gep_type_end(*Src); 871 I != E; ++I) 872 EndsWithSequential = !(*I)->isStructTy(); 873 874 // Can we combine the two pointer arithmetics offsets? 875 if (EndsWithSequential) { 876 // Replace: gep (gep %P, long B), long A, ... 877 // With: T = long A+B; gep %P, T, ... 878 // 879 Value *Sum; 880 Value *SO1 = Src->getOperand(Src->getNumOperands()-1); 881 Value *GO1 = GEP.getOperand(1); 882 if (SO1 == Constant::getNullValue(SO1->getType())) { 883 Sum = GO1; 884 } else if (GO1 == Constant::getNullValue(GO1->getType())) { 885 Sum = SO1; 886 } else { 887 // If they aren't the same type, then the input hasn't been processed 888 // by the loop above yet (which canonicalizes sequential index types to 889 // intptr_t). Just avoid transforming this until the input has been 890 // normalized. 891 if (SO1->getType() != GO1->getType()) 892 return 0; 893 Sum = Builder->CreateAdd(SO1, GO1, PtrOp->getName()+".sum"); 894 } 895 896 // Update the GEP in place if possible. 897 if (Src->getNumOperands() == 2) { 898 GEP.setOperand(0, Src->getOperand(0)); 899 GEP.setOperand(1, Sum); 900 return &GEP; 901 } 902 Indices.append(Src->op_begin()+1, Src->op_end()-1); 903 Indices.push_back(Sum); 904 Indices.append(GEP.op_begin()+2, GEP.op_end()); 905 } else if (isa<Constant>(*GEP.idx_begin()) && 906 cast<Constant>(*GEP.idx_begin())->isNullValue() && 907 Src->getNumOperands() != 1) { 908 // Otherwise we can do the fold if the first index of the GEP is a zero 909 Indices.append(Src->op_begin()+1, Src->op_end()); 910 Indices.append(GEP.idx_begin()+1, GEP.idx_end()); 911 } 912 913 if (!Indices.empty()) 914 return (GEP.isInBounds() && Src->isInBounds()) ? 915 GetElementPtrInst::CreateInBounds(Src->getOperand(0), Indices, 916 GEP.getName()) : 917 GetElementPtrInst::Create(Src->getOperand(0), Indices, GEP.getName()); 918 } 919 920 // Handle gep(bitcast x) and gep(gep x, 0, 0, 0). 921 Value *StrippedPtr = PtrOp->stripPointerCasts(); 922 PointerType *StrippedPtrTy = dyn_cast<PointerType>(StrippedPtr->getType()); 923 924 // We do not handle pointer-vector geps here. 925 if (!StrippedPtrTy) 926 return 0; 927 928 if (StrippedPtr != PtrOp && 929 StrippedPtrTy->getAddressSpace() == GEP.getPointerAddressSpace()) { 930 931 bool HasZeroPointerIndex = false; 932 if (ConstantInt *C = dyn_cast<ConstantInt>(GEP.getOperand(1))) 933 HasZeroPointerIndex = C->isZero(); 934 935 // Transform: GEP (bitcast [10 x i8]* X to [0 x i8]*), i32 0, ... 936 // into : GEP [10 x i8]* X, i32 0, ... 937 // 938 // Likewise, transform: GEP (bitcast i8* X to [0 x i8]*), i32 0, ... 939 // into : GEP i8* X, ... 940 // 941 // This occurs when the program declares an array extern like "int X[];" 942 if (HasZeroPointerIndex) { 943 PointerType *CPTy = cast<PointerType>(PtrOp->getType()); 944 if (ArrayType *CATy = 945 dyn_cast<ArrayType>(CPTy->getElementType())) { 946 // GEP (bitcast i8* X to [0 x i8]*), i32 0, ... ? 947 if (CATy->getElementType() == StrippedPtrTy->getElementType()) { 948 // -> GEP i8* X, ... 949 SmallVector<Value*, 8> Idx(GEP.idx_begin()+1, GEP.idx_end()); 950 GetElementPtrInst *Res = 951 GetElementPtrInst::Create(StrippedPtr, Idx, GEP.getName()); 952 Res->setIsInBounds(GEP.isInBounds()); 953 return Res; 954 } 955 956 if (ArrayType *XATy = 957 dyn_cast<ArrayType>(StrippedPtrTy->getElementType())){ 958 // GEP (bitcast [10 x i8]* X to [0 x i8]*), i32 0, ... ? 959 if (CATy->getElementType() == XATy->getElementType()) { 960 // -> GEP [10 x i8]* X, i32 0, ... 961 // At this point, we know that the cast source type is a pointer 962 // to an array of the same type as the destination pointer 963 // array. Because the array type is never stepped over (there 964 // is a leading zero) we can fold the cast into this GEP. 965 GEP.setOperand(0, StrippedPtr); 966 return &GEP; 967 } 968 } 969 } 970 } else if (GEP.getNumOperands() == 2) { 971 // Transform things like: 972 // %t = getelementptr i32* bitcast ([2 x i32]* %str to i32*), i32 %V 973 // into: %t1 = getelementptr [2 x i32]* %str, i32 0, i32 %V; bitcast 974 Type *SrcElTy = StrippedPtrTy->getElementType(); 975 Type *ResElTy=cast<PointerType>(PtrOp->getType())->getElementType(); 976 if (TD && SrcElTy->isArrayTy() && 977 TD->getTypeAllocSize(cast<ArrayType>(SrcElTy)->getElementType()) == 978 TD->getTypeAllocSize(ResElTy)) { 979 Value *Idx[2]; 980 Idx[0] = Constant::getNullValue(Type::getInt32Ty(GEP.getContext())); 981 Idx[1] = GEP.getOperand(1); 982 Value *NewGEP = GEP.isInBounds() ? 983 Builder->CreateInBoundsGEP(StrippedPtr, Idx, GEP.getName()) : 984 Builder->CreateGEP(StrippedPtr, Idx, GEP.getName()); 985 // V and GEP are both pointer types --> BitCast 986 return new BitCastInst(NewGEP, GEP.getType()); 987 } 988 989 // Transform things like: 990 // getelementptr i8* bitcast ([100 x double]* X to i8*), i32 %tmp 991 // (where tmp = 8*tmp2) into: 992 // getelementptr [100 x double]* %arr, i32 0, i32 %tmp2; bitcast 993 994 if (TD && SrcElTy->isArrayTy() && ResElTy->isIntegerTy(8)) { 995 uint64_t ArrayEltSize = 996 TD->getTypeAllocSize(cast<ArrayType>(SrcElTy)->getElementType()); 997 998 // Check to see if "tmp" is a scale by a multiple of ArrayEltSize. We 999 // allow either a mul, shift, or constant here. 1000 Value *NewIdx = 0; 1001 ConstantInt *Scale = 0; 1002 if (ArrayEltSize == 1) { 1003 NewIdx = GEP.getOperand(1); 1004 Scale = ConstantInt::get(cast<IntegerType>(NewIdx->getType()), 1); 1005 } else if (ConstantInt *CI = dyn_cast<ConstantInt>(GEP.getOperand(1))) { 1006 NewIdx = ConstantInt::get(CI->getType(), 1); 1007 Scale = CI; 1008 } else if (Instruction *Inst =dyn_cast<Instruction>(GEP.getOperand(1))){ 1009 if (Inst->getOpcode() == Instruction::Shl && 1010 isa<ConstantInt>(Inst->getOperand(1))) { 1011 ConstantInt *ShAmt = cast<ConstantInt>(Inst->getOperand(1)); 1012 uint32_t ShAmtVal = ShAmt->getLimitedValue(64); 1013 Scale = ConstantInt::get(cast<IntegerType>(Inst->getType()), 1014 1ULL << ShAmtVal); 1015 NewIdx = Inst->getOperand(0); 1016 } else if (Inst->getOpcode() == Instruction::Mul && 1017 isa<ConstantInt>(Inst->getOperand(1))) { 1018 Scale = cast<ConstantInt>(Inst->getOperand(1)); 1019 NewIdx = Inst->getOperand(0); 1020 } 1021 } 1022 1023 // If the index will be to exactly the right offset with the scale taken 1024 // out, perform the transformation. Note, we don't know whether Scale is 1025 // signed or not. We'll use unsigned version of division/modulo 1026 // operation after making sure Scale doesn't have the sign bit set. 1027 if (ArrayEltSize && Scale && Scale->getSExtValue() >= 0LL && 1028 Scale->getZExtValue() % ArrayEltSize == 0) { 1029 Scale = ConstantInt::get(Scale->getType(), 1030 Scale->getZExtValue() / ArrayEltSize); 1031 if (Scale->getZExtValue() != 1) { 1032 Constant *C = ConstantExpr::getIntegerCast(Scale, NewIdx->getType(), 1033 false /*ZExt*/); 1034 NewIdx = Builder->CreateMul(NewIdx, C, "idxscale"); 1035 } 1036 1037 // Insert the new GEP instruction. 1038 Value *Idx[2]; 1039 Idx[0] = Constant::getNullValue(Type::getInt32Ty(GEP.getContext())); 1040 Idx[1] = NewIdx; 1041 Value *NewGEP = GEP.isInBounds() ? 1042 Builder->CreateInBoundsGEP(StrippedPtr, Idx, GEP.getName()): 1043 Builder->CreateGEP(StrippedPtr, Idx, GEP.getName()); 1044 // The NewGEP must be pointer typed, so must the old one -> BitCast 1045 return new BitCastInst(NewGEP, GEP.getType()); 1046 } 1047 } 1048 } 1049 } 1050 1051 /// See if we can simplify: 1052 /// X = bitcast A* to B* 1053 /// Y = gep X, <...constant indices...> 1054 /// into a gep of the original struct. This is important for SROA and alias 1055 /// analysis of unions. If "A" is also a bitcast, wait for A/X to be merged. 1056 if (BitCastInst *BCI = dyn_cast<BitCastInst>(PtrOp)) { 1057 if (TD && 1058 !isa<BitCastInst>(BCI->getOperand(0)) && GEP.hasAllConstantIndices() && 1059 StrippedPtrTy->getAddressSpace() == GEP.getPointerAddressSpace()) { 1060 1061 // Determine how much the GEP moves the pointer. 1062 SmallVector<Value*, 8> Ops(GEP.idx_begin(), GEP.idx_end()); 1063 int64_t Offset = TD->getIndexedOffset(GEP.getPointerOperandType(), Ops); 1064 1065 // If this GEP instruction doesn't move the pointer, just replace the GEP 1066 // with a bitcast of the real input to the dest type. 1067 if (Offset == 0) { 1068 // If the bitcast is of an allocation, and the allocation will be 1069 // converted to match the type of the cast, don't touch this. 1070 if (isa<AllocaInst>(BCI->getOperand(0)) || 1071 isAllocationFn(BCI->getOperand(0))) { 1072 // See if the bitcast simplifies, if so, don't nuke this GEP yet. 1073 if (Instruction *I = visitBitCast(*BCI)) { 1074 if (I != BCI) { 1075 I->takeName(BCI); 1076 BCI->getParent()->getInstList().insert(BCI, I); 1077 ReplaceInstUsesWith(*BCI, I); 1078 } 1079 return &GEP; 1080 } 1081 } 1082 return new BitCastInst(BCI->getOperand(0), GEP.getType()); 1083 } 1084 1085 // Otherwise, if the offset is non-zero, we need to find out if there is a 1086 // field at Offset in 'A's type. If so, we can pull the cast through the 1087 // GEP. 1088 SmallVector<Value*, 8> NewIndices; 1089 Type *InTy = 1090 cast<PointerType>(BCI->getOperand(0)->getType())->getElementType(); 1091 if (FindElementAtOffset(InTy, Offset, NewIndices)) { 1092 Value *NGEP = GEP.isInBounds() ? 1093 Builder->CreateInBoundsGEP(BCI->getOperand(0), NewIndices) : 1094 Builder->CreateGEP(BCI->getOperand(0), NewIndices); 1095 1096 if (NGEP->getType() == GEP.getType()) 1097 return ReplaceInstUsesWith(GEP, NGEP); 1098 NGEP->takeName(&GEP); 1099 return new BitCastInst(NGEP, GEP.getType()); 1100 } 1101 } 1102 } 1103 1104 return 0; 1105} 1106 1107 1108 1109static bool 1110isAllocSiteRemovable(Instruction *AI, SmallVectorImpl<WeakVH> &Users) { 1111 SmallVector<Instruction*, 4> Worklist; 1112 Worklist.push_back(AI); 1113 1114 do { 1115 Instruction *PI = Worklist.pop_back_val(); 1116 for (Value::use_iterator UI = PI->use_begin(), UE = PI->use_end(); UI != UE; 1117 ++UI) { 1118 Instruction *I = cast<Instruction>(*UI); 1119 switch (I->getOpcode()) { 1120 default: 1121 // Give up the moment we see something we can't handle. 1122 return false; 1123 1124 case Instruction::BitCast: 1125 case Instruction::GetElementPtr: 1126 Users.push_back(I); 1127 Worklist.push_back(I); 1128 continue; 1129 1130 case Instruction::ICmp: { 1131 ICmpInst *ICI = cast<ICmpInst>(I); 1132 // We can fold eq/ne comparisons with null to false/true, respectively. 1133 if (!ICI->isEquality() || !isa<ConstantPointerNull>(ICI->getOperand(1))) 1134 return false; 1135 Users.push_back(I); 1136 continue; 1137 } 1138 1139 case Instruction::Call: 1140 // Ignore no-op and store intrinsics. 1141 if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(I)) { 1142 switch (II->getIntrinsicID()) { 1143 default: 1144 return false; 1145 1146 case Intrinsic::memmove: 1147 case Intrinsic::memcpy: 1148 case Intrinsic::memset: { 1149 MemIntrinsic *MI = cast<MemIntrinsic>(II); 1150 if (MI->isVolatile() || MI->getRawDest() != PI) 1151 return false; 1152 } 1153 // fall through 1154 case Intrinsic::dbg_declare: 1155 case Intrinsic::dbg_value: 1156 case Intrinsic::invariant_start: 1157 case Intrinsic::invariant_end: 1158 case Intrinsic::lifetime_start: 1159 case Intrinsic::lifetime_end: 1160 case Intrinsic::objectsize: 1161 Users.push_back(I); 1162 continue; 1163 } 1164 } 1165 1166 if (isFreeCall(I)) { 1167 Users.push_back(I); 1168 continue; 1169 } 1170 return false; 1171 1172 case Instruction::Store: { 1173 StoreInst *SI = cast<StoreInst>(I); 1174 if (SI->isVolatile() || SI->getPointerOperand() != PI) 1175 return false; 1176 Users.push_back(I); 1177 continue; 1178 } 1179 } 1180 llvm_unreachable("missing a return?"); 1181 } 1182 } while (!Worklist.empty()); 1183 return true; 1184} 1185 1186Instruction *InstCombiner::visitAllocSite(Instruction &MI) { 1187 // If we have a malloc call which is only used in any amount of comparisons 1188 // to null and free calls, delete the calls and replace the comparisons with 1189 // true or false as appropriate. 1190 SmallVector<WeakVH, 64> Users; 1191 if (isAllocSiteRemovable(&MI, Users)) { 1192 for (unsigned i = 0, e = Users.size(); i != e; ++i) { 1193 Instruction *I = cast_or_null<Instruction>(&*Users[i]); 1194 if (!I) continue; 1195 1196 if (ICmpInst *C = dyn_cast<ICmpInst>(I)) { 1197 ReplaceInstUsesWith(*C, 1198 ConstantInt::get(Type::getInt1Ty(C->getContext()), 1199 C->isFalseWhenEqual())); 1200 } else if (isa<BitCastInst>(I) || isa<GetElementPtrInst>(I)) { 1201 ReplaceInstUsesWith(*I, UndefValue::get(I->getType())); 1202 } else if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(I)) { 1203 if (II->getIntrinsicID() == Intrinsic::objectsize) { 1204 ConstantInt *CI = cast<ConstantInt>(II->getArgOperand(1)); 1205 uint64_t DontKnow = CI->isZero() ? -1ULL : 0; 1206 ReplaceInstUsesWith(*I, ConstantInt::get(I->getType(), DontKnow)); 1207 } 1208 } 1209 EraseInstFromFunction(*I); 1210 } 1211 1212 if (InvokeInst *II = dyn_cast<InvokeInst>(&MI)) { 1213 // Replace invoke with a NOP intrinsic to maintain the original CFG 1214 Module *M = II->getParent()->getParent()->getParent(); 1215 Function *F = Intrinsic::getDeclaration(M, Intrinsic::donothing); 1216 InvokeInst::Create(F, II->getNormalDest(), II->getUnwindDest(), 1217 ArrayRef<Value *>(), "", II->getParent()); 1218 } 1219 return EraseInstFromFunction(MI); 1220 } 1221 return 0; 1222} 1223 1224 1225 1226Instruction *InstCombiner::visitFree(CallInst &FI) { 1227 Value *Op = FI.getArgOperand(0); 1228 1229 // free undef -> unreachable. 1230 if (isa<UndefValue>(Op)) { 1231 // Insert a new store to null because we cannot modify the CFG here. 1232 Builder->CreateStore(ConstantInt::getTrue(FI.getContext()), 1233 UndefValue::get(Type::getInt1PtrTy(FI.getContext()))); 1234 return EraseInstFromFunction(FI); 1235 } 1236 1237 // If we have 'free null' delete the instruction. This can happen in stl code 1238 // when lots of inlining happens. 1239 if (isa<ConstantPointerNull>(Op)) 1240 return EraseInstFromFunction(FI); 1241 1242 return 0; 1243} 1244 1245 1246 1247Instruction *InstCombiner::visitBranchInst(BranchInst &BI) { 1248 // Change br (not X), label True, label False to: br X, label False, True 1249 Value *X = 0; 1250 BasicBlock *TrueDest; 1251 BasicBlock *FalseDest; 1252 if (match(&BI, m_Br(m_Not(m_Value(X)), TrueDest, FalseDest)) && 1253 !isa<Constant>(X)) { 1254 // Swap Destinations and condition... 1255 BI.setCondition(X); 1256 BI.swapSuccessors(); 1257 return &BI; 1258 } 1259 1260 // Cannonicalize fcmp_one -> fcmp_oeq 1261 FCmpInst::Predicate FPred; Value *Y; 1262 if (match(&BI, m_Br(m_FCmp(FPred, m_Value(X), m_Value(Y)), 1263 TrueDest, FalseDest)) && 1264 BI.getCondition()->hasOneUse()) 1265 if (FPred == FCmpInst::FCMP_ONE || FPred == FCmpInst::FCMP_OLE || 1266 FPred == FCmpInst::FCMP_OGE) { 1267 FCmpInst *Cond = cast<FCmpInst>(BI.getCondition()); 1268 Cond->setPredicate(FCmpInst::getInversePredicate(FPred)); 1269 1270 // Swap Destinations and condition. 1271 BI.swapSuccessors(); 1272 Worklist.Add(Cond); 1273 return &BI; 1274 } 1275 1276 // Cannonicalize icmp_ne -> icmp_eq 1277 ICmpInst::Predicate IPred; 1278 if (match(&BI, m_Br(m_ICmp(IPred, m_Value(X), m_Value(Y)), 1279 TrueDest, FalseDest)) && 1280 BI.getCondition()->hasOneUse()) 1281 if (IPred == ICmpInst::ICMP_NE || IPred == ICmpInst::ICMP_ULE || 1282 IPred == ICmpInst::ICMP_SLE || IPred == ICmpInst::ICMP_UGE || 1283 IPred == ICmpInst::ICMP_SGE) { 1284 ICmpInst *Cond = cast<ICmpInst>(BI.getCondition()); 1285 Cond->setPredicate(ICmpInst::getInversePredicate(IPred)); 1286 // Swap Destinations and condition. 1287 BI.swapSuccessors(); 1288 Worklist.Add(Cond); 1289 return &BI; 1290 } 1291 1292 return 0; 1293} 1294 1295Instruction *InstCombiner::visitSwitchInst(SwitchInst &SI) { 1296 Value *Cond = SI.getCondition(); 1297 if (Instruction *I = dyn_cast<Instruction>(Cond)) { 1298 if (I->getOpcode() == Instruction::Add) 1299 if (ConstantInt *AddRHS = dyn_cast<ConstantInt>(I->getOperand(1))) { 1300 // change 'switch (X+4) case 1:' into 'switch (X) case -3' 1301 // Skip the first item since that's the default case. 1302 for (SwitchInst::CaseIt i = SI.case_begin(), e = SI.case_end(); 1303 i != e; ++i) { 1304 ConstantInt* CaseVal = i.getCaseValue(); 1305 Constant* NewCaseVal = ConstantExpr::getSub(cast<Constant>(CaseVal), 1306 AddRHS); 1307 assert(isa<ConstantInt>(NewCaseVal) && 1308 "Result of expression should be constant"); 1309 i.setValue(cast<ConstantInt>(NewCaseVal)); 1310 } 1311 SI.setCondition(I->getOperand(0)); 1312 Worklist.Add(I); 1313 return &SI; 1314 } 1315 } 1316 return 0; 1317} 1318 1319Instruction *InstCombiner::visitExtractValueInst(ExtractValueInst &EV) { 1320 Value *Agg = EV.getAggregateOperand(); 1321 1322 if (!EV.hasIndices()) 1323 return ReplaceInstUsesWith(EV, Agg); 1324 1325 if (Constant *C = dyn_cast<Constant>(Agg)) { 1326 if (Constant *C2 = C->getAggregateElement(*EV.idx_begin())) { 1327 if (EV.getNumIndices() == 0) 1328 return ReplaceInstUsesWith(EV, C2); 1329 // Extract the remaining indices out of the constant indexed by the 1330 // first index 1331 return ExtractValueInst::Create(C2, EV.getIndices().slice(1)); 1332 } 1333 return 0; // Can't handle other constants 1334 } 1335 1336 if (InsertValueInst *IV = dyn_cast<InsertValueInst>(Agg)) { 1337 // We're extracting from an insertvalue instruction, compare the indices 1338 const unsigned *exti, *exte, *insi, *inse; 1339 for (exti = EV.idx_begin(), insi = IV->idx_begin(), 1340 exte = EV.idx_end(), inse = IV->idx_end(); 1341 exti != exte && insi != inse; 1342 ++exti, ++insi) { 1343 if (*insi != *exti) 1344 // The insert and extract both reference distinctly different elements. 1345 // This means the extract is not influenced by the insert, and we can 1346 // replace the aggregate operand of the extract with the aggregate 1347 // operand of the insert. i.e., replace 1348 // %I = insertvalue { i32, { i32 } } %A, { i32 } { i32 42 }, 1 1349 // %E = extractvalue { i32, { i32 } } %I, 0 1350 // with 1351 // %E = extractvalue { i32, { i32 } } %A, 0 1352 return ExtractValueInst::Create(IV->getAggregateOperand(), 1353 EV.getIndices()); 1354 } 1355 if (exti == exte && insi == inse) 1356 // Both iterators are at the end: Index lists are identical. Replace 1357 // %B = insertvalue { i32, { i32 } } %A, i32 42, 1, 0 1358 // %C = extractvalue { i32, { i32 } } %B, 1, 0 1359 // with "i32 42" 1360 return ReplaceInstUsesWith(EV, IV->getInsertedValueOperand()); 1361 if (exti == exte) { 1362 // The extract list is a prefix of the insert list. i.e. replace 1363 // %I = insertvalue { i32, { i32 } } %A, i32 42, 1, 0 1364 // %E = extractvalue { i32, { i32 } } %I, 1 1365 // with 1366 // %X = extractvalue { i32, { i32 } } %A, 1 1367 // %E = insertvalue { i32 } %X, i32 42, 0 1368 // by switching the order of the insert and extract (though the 1369 // insertvalue should be left in, since it may have other uses). 1370 Value *NewEV = Builder->CreateExtractValue(IV->getAggregateOperand(), 1371 EV.getIndices()); 1372 return InsertValueInst::Create(NewEV, IV->getInsertedValueOperand(), 1373 makeArrayRef(insi, inse)); 1374 } 1375 if (insi == inse) 1376 // The insert list is a prefix of the extract list 1377 // We can simply remove the common indices from the extract and make it 1378 // operate on the inserted value instead of the insertvalue result. 1379 // i.e., replace 1380 // %I = insertvalue { i32, { i32 } } %A, { i32 } { i32 42 }, 1 1381 // %E = extractvalue { i32, { i32 } } %I, 1, 0 1382 // with 1383 // %E extractvalue { i32 } { i32 42 }, 0 1384 return ExtractValueInst::Create(IV->getInsertedValueOperand(), 1385 makeArrayRef(exti, exte)); 1386 } 1387 if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(Agg)) { 1388 // We're extracting from an intrinsic, see if we're the only user, which 1389 // allows us to simplify multiple result intrinsics to simpler things that 1390 // just get one value. 1391 if (II->hasOneUse()) { 1392 // Check if we're grabbing the overflow bit or the result of a 'with 1393 // overflow' intrinsic. If it's the latter we can remove the intrinsic 1394 // and replace it with a traditional binary instruction. 1395 switch (II->getIntrinsicID()) { 1396 case Intrinsic::uadd_with_overflow: 1397 case Intrinsic::sadd_with_overflow: 1398 if (*EV.idx_begin() == 0) { // Normal result. 1399 Value *LHS = II->getArgOperand(0), *RHS = II->getArgOperand(1); 1400 ReplaceInstUsesWith(*II, UndefValue::get(II->getType())); 1401 EraseInstFromFunction(*II); 1402 return BinaryOperator::CreateAdd(LHS, RHS); 1403 } 1404 1405 // If the normal result of the add is dead, and the RHS is a constant, 1406 // we can transform this into a range comparison. 1407 // overflow = uadd a, -4 --> overflow = icmp ugt a, 3 1408 if (II->getIntrinsicID() == Intrinsic::uadd_with_overflow) 1409 if (ConstantInt *CI = dyn_cast<ConstantInt>(II->getArgOperand(1))) 1410 return new ICmpInst(ICmpInst::ICMP_UGT, II->getArgOperand(0), 1411 ConstantExpr::getNot(CI)); 1412 break; 1413 case Intrinsic::usub_with_overflow: 1414 case Intrinsic::ssub_with_overflow: 1415 if (*EV.idx_begin() == 0) { // Normal result. 1416 Value *LHS = II->getArgOperand(0), *RHS = II->getArgOperand(1); 1417 ReplaceInstUsesWith(*II, UndefValue::get(II->getType())); 1418 EraseInstFromFunction(*II); 1419 return BinaryOperator::CreateSub(LHS, RHS); 1420 } 1421 break; 1422 case Intrinsic::umul_with_overflow: 1423 case Intrinsic::smul_with_overflow: 1424 if (*EV.idx_begin() == 0) { // Normal result. 1425 Value *LHS = II->getArgOperand(0), *RHS = II->getArgOperand(1); 1426 ReplaceInstUsesWith(*II, UndefValue::get(II->getType())); 1427 EraseInstFromFunction(*II); 1428 return BinaryOperator::CreateMul(LHS, RHS); 1429 } 1430 break; 1431 default: 1432 break; 1433 } 1434 } 1435 } 1436 if (LoadInst *L = dyn_cast<LoadInst>(Agg)) 1437 // If the (non-volatile) load only has one use, we can rewrite this to a 1438 // load from a GEP. This reduces the size of the load. 1439 // FIXME: If a load is used only by extractvalue instructions then this 1440 // could be done regardless of having multiple uses. 1441 if (L->isSimple() && L->hasOneUse()) { 1442 // extractvalue has integer indices, getelementptr has Value*s. Convert. 1443 SmallVector<Value*, 4> Indices; 1444 // Prefix an i32 0 since we need the first element. 1445 Indices.push_back(Builder->getInt32(0)); 1446 for (ExtractValueInst::idx_iterator I = EV.idx_begin(), E = EV.idx_end(); 1447 I != E; ++I) 1448 Indices.push_back(Builder->getInt32(*I)); 1449 1450 // We need to insert these at the location of the old load, not at that of 1451 // the extractvalue. 1452 Builder->SetInsertPoint(L->getParent(), L); 1453 Value *GEP = Builder->CreateInBoundsGEP(L->getPointerOperand(), Indices); 1454 // Returning the load directly will cause the main loop to insert it in 1455 // the wrong spot, so use ReplaceInstUsesWith(). 1456 return ReplaceInstUsesWith(EV, Builder->CreateLoad(GEP)); 1457 } 1458 // We could simplify extracts from other values. Note that nested extracts may 1459 // already be simplified implicitly by the above: extract (extract (insert) ) 1460 // will be translated into extract ( insert ( extract ) ) first and then just 1461 // the value inserted, if appropriate. Similarly for extracts from single-use 1462 // loads: extract (extract (load)) will be translated to extract (load (gep)) 1463 // and if again single-use then via load (gep (gep)) to load (gep). 1464 // However, double extracts from e.g. function arguments or return values 1465 // aren't handled yet. 1466 return 0; 1467} 1468 1469enum Personality_Type { 1470 Unknown_Personality, 1471 GNU_Ada_Personality, 1472 GNU_CXX_Personality, 1473 GNU_ObjC_Personality 1474}; 1475 1476/// RecognizePersonality - See if the given exception handling personality 1477/// function is one that we understand. If so, return a description of it; 1478/// otherwise return Unknown_Personality. 1479static Personality_Type RecognizePersonality(Value *Pers) { 1480 Function *F = dyn_cast<Function>(Pers->stripPointerCasts()); 1481 if (!F) 1482 return Unknown_Personality; 1483 return StringSwitch<Personality_Type>(F->getName()) 1484 .Case("__gnat_eh_personality", GNU_Ada_Personality) 1485 .Case("__gxx_personality_v0", GNU_CXX_Personality) 1486 .Case("__objc_personality_v0", GNU_ObjC_Personality) 1487 .Default(Unknown_Personality); 1488} 1489 1490/// isCatchAll - Return 'true' if the given typeinfo will match anything. 1491static bool isCatchAll(Personality_Type Personality, Constant *TypeInfo) { 1492 switch (Personality) { 1493 case Unknown_Personality: 1494 return false; 1495 case GNU_Ada_Personality: 1496 // While __gnat_all_others_value will match any Ada exception, it doesn't 1497 // match foreign exceptions (or didn't, before gcc-4.7). 1498 return false; 1499 case GNU_CXX_Personality: 1500 case GNU_ObjC_Personality: 1501 return TypeInfo->isNullValue(); 1502 } 1503 llvm_unreachable("Unknown personality!"); 1504} 1505 1506static bool shorter_filter(const Value *LHS, const Value *RHS) { 1507 return 1508 cast<ArrayType>(LHS->getType())->getNumElements() 1509 < 1510 cast<ArrayType>(RHS->getType())->getNumElements(); 1511} 1512 1513Instruction *InstCombiner::visitLandingPadInst(LandingPadInst &LI) { 1514 // The logic here should be correct for any real-world personality function. 1515 // However if that turns out not to be true, the offending logic can always 1516 // be conditioned on the personality function, like the catch-all logic is. 1517 Personality_Type Personality = RecognizePersonality(LI.getPersonalityFn()); 1518 1519 // Simplify the list of clauses, eg by removing repeated catch clauses 1520 // (these are often created by inlining). 1521 bool MakeNewInstruction = false; // If true, recreate using the following: 1522 SmallVector<Value *, 16> NewClauses; // - Clauses for the new instruction; 1523 bool CleanupFlag = LI.isCleanup(); // - The new instruction is a cleanup. 1524 1525 SmallPtrSet<Value *, 16> AlreadyCaught; // Typeinfos known caught already. 1526 for (unsigned i = 0, e = LI.getNumClauses(); i != e; ++i) { 1527 bool isLastClause = i + 1 == e; 1528 if (LI.isCatch(i)) { 1529 // A catch clause. 1530 Value *CatchClause = LI.getClause(i); 1531 Constant *TypeInfo = cast<Constant>(CatchClause->stripPointerCasts()); 1532 1533 // If we already saw this clause, there is no point in having a second 1534 // copy of it. 1535 if (AlreadyCaught.insert(TypeInfo)) { 1536 // This catch clause was not already seen. 1537 NewClauses.push_back(CatchClause); 1538 } else { 1539 // Repeated catch clause - drop the redundant copy. 1540 MakeNewInstruction = true; 1541 } 1542 1543 // If this is a catch-all then there is no point in keeping any following 1544 // clauses or marking the landingpad as having a cleanup. 1545 if (isCatchAll(Personality, TypeInfo)) { 1546 if (!isLastClause) 1547 MakeNewInstruction = true; 1548 CleanupFlag = false; 1549 break; 1550 } 1551 } else { 1552 // A filter clause. If any of the filter elements were already caught 1553 // then they can be dropped from the filter. It is tempting to try to 1554 // exploit the filter further by saying that any typeinfo that does not 1555 // occur in the filter can't be caught later (and thus can be dropped). 1556 // However this would be wrong, since typeinfos can match without being 1557 // equal (for example if one represents a C++ class, and the other some 1558 // class derived from it). 1559 assert(LI.isFilter(i) && "Unsupported landingpad clause!"); 1560 Value *FilterClause = LI.getClause(i); 1561 ArrayType *FilterType = cast<ArrayType>(FilterClause->getType()); 1562 unsigned NumTypeInfos = FilterType->getNumElements(); 1563 1564 // An empty filter catches everything, so there is no point in keeping any 1565 // following clauses or marking the landingpad as having a cleanup. By 1566 // dealing with this case here the following code is made a bit simpler. 1567 if (!NumTypeInfos) { 1568 NewClauses.push_back(FilterClause); 1569 if (!isLastClause) 1570 MakeNewInstruction = true; 1571 CleanupFlag = false; 1572 break; 1573 } 1574 1575 bool MakeNewFilter = false; // If true, make a new filter. 1576 SmallVector<Constant *, 16> NewFilterElts; // New elements. 1577 if (isa<ConstantAggregateZero>(FilterClause)) { 1578 // Not an empty filter - it contains at least one null typeinfo. 1579 assert(NumTypeInfos > 0 && "Should have handled empty filter already!"); 1580 Constant *TypeInfo = 1581 Constant::getNullValue(FilterType->getElementType()); 1582 // If this typeinfo is a catch-all then the filter can never match. 1583 if (isCatchAll(Personality, TypeInfo)) { 1584 // Throw the filter away. 1585 MakeNewInstruction = true; 1586 continue; 1587 } 1588 1589 // There is no point in having multiple copies of this typeinfo, so 1590 // discard all but the first copy if there is more than one. 1591 NewFilterElts.push_back(TypeInfo); 1592 if (NumTypeInfos > 1) 1593 MakeNewFilter = true; 1594 } else { 1595 ConstantArray *Filter = cast<ConstantArray>(FilterClause); 1596 SmallPtrSet<Value *, 16> SeenInFilter; // For uniquing the elements. 1597 NewFilterElts.reserve(NumTypeInfos); 1598 1599 // Remove any filter elements that were already caught or that already 1600 // occurred in the filter. While there, see if any of the elements are 1601 // catch-alls. If so, the filter can be discarded. 1602 bool SawCatchAll = false; 1603 for (unsigned j = 0; j != NumTypeInfos; ++j) { 1604 Value *Elt = Filter->getOperand(j); 1605 Constant *TypeInfo = cast<Constant>(Elt->stripPointerCasts()); 1606 if (isCatchAll(Personality, TypeInfo)) { 1607 // This element is a catch-all. Bail out, noting this fact. 1608 SawCatchAll = true; 1609 break; 1610 } 1611 if (AlreadyCaught.count(TypeInfo)) 1612 // Already caught by an earlier clause, so having it in the filter 1613 // is pointless. 1614 continue; 1615 // There is no point in having multiple copies of the same typeinfo in 1616 // a filter, so only add it if we didn't already. 1617 if (SeenInFilter.insert(TypeInfo)) 1618 NewFilterElts.push_back(cast<Constant>(Elt)); 1619 } 1620 // A filter containing a catch-all cannot match anything by definition. 1621 if (SawCatchAll) { 1622 // Throw the filter away. 1623 MakeNewInstruction = true; 1624 continue; 1625 } 1626 1627 // If we dropped something from the filter, make a new one. 1628 if (NewFilterElts.size() < NumTypeInfos) 1629 MakeNewFilter = true; 1630 } 1631 if (MakeNewFilter) { 1632 FilterType = ArrayType::get(FilterType->getElementType(), 1633 NewFilterElts.size()); 1634 FilterClause = ConstantArray::get(FilterType, NewFilterElts); 1635 MakeNewInstruction = true; 1636 } 1637 1638 NewClauses.push_back(FilterClause); 1639 1640 // If the new filter is empty then it will catch everything so there is 1641 // no point in keeping any following clauses or marking the landingpad 1642 // as having a cleanup. The case of the original filter being empty was 1643 // already handled above. 1644 if (MakeNewFilter && !NewFilterElts.size()) { 1645 assert(MakeNewInstruction && "New filter but not a new instruction!"); 1646 CleanupFlag = false; 1647 break; 1648 } 1649 } 1650 } 1651 1652 // If several filters occur in a row then reorder them so that the shortest 1653 // filters come first (those with the smallest number of elements). This is 1654 // advantageous because shorter filters are more likely to match, speeding up 1655 // unwinding, but mostly because it increases the effectiveness of the other 1656 // filter optimizations below. 1657 for (unsigned i = 0, e = NewClauses.size(); i + 1 < e; ) { 1658 unsigned j; 1659 // Find the maximal 'j' s.t. the range [i, j) consists entirely of filters. 1660 for (j = i; j != e; ++j) 1661 if (!isa<ArrayType>(NewClauses[j]->getType())) 1662 break; 1663 1664 // Check whether the filters are already sorted by length. We need to know 1665 // if sorting them is actually going to do anything so that we only make a 1666 // new landingpad instruction if it does. 1667 for (unsigned k = i; k + 1 < j; ++k) 1668 if (shorter_filter(NewClauses[k+1], NewClauses[k])) { 1669 // Not sorted, so sort the filters now. Doing an unstable sort would be 1670 // correct too but reordering filters pointlessly might confuse users. 1671 std::stable_sort(NewClauses.begin() + i, NewClauses.begin() + j, 1672 shorter_filter); 1673 MakeNewInstruction = true; 1674 break; 1675 } 1676 1677 // Look for the next batch of filters. 1678 i = j + 1; 1679 } 1680 1681 // If typeinfos matched if and only if equal, then the elements of a filter L 1682 // that occurs later than a filter F could be replaced by the intersection of 1683 // the elements of F and L. In reality two typeinfos can match without being 1684 // equal (for example if one represents a C++ class, and the other some class 1685 // derived from it) so it would be wrong to perform this transform in general. 1686 // However the transform is correct and useful if F is a subset of L. In that 1687 // case L can be replaced by F, and thus removed altogether since repeating a 1688 // filter is pointless. So here we look at all pairs of filters F and L where 1689 // L follows F in the list of clauses, and remove L if every element of F is 1690 // an element of L. This can occur when inlining C++ functions with exception 1691 // specifications. 1692 for (unsigned i = 0; i + 1 < NewClauses.size(); ++i) { 1693 // Examine each filter in turn. 1694 Value *Filter = NewClauses[i]; 1695 ArrayType *FTy = dyn_cast<ArrayType>(Filter->getType()); 1696 if (!FTy) 1697 // Not a filter - skip it. 1698 continue; 1699 unsigned FElts = FTy->getNumElements(); 1700 // Examine each filter following this one. Doing this backwards means that 1701 // we don't have to worry about filters disappearing under us when removed. 1702 for (unsigned j = NewClauses.size() - 1; j != i; --j) { 1703 Value *LFilter = NewClauses[j]; 1704 ArrayType *LTy = dyn_cast<ArrayType>(LFilter->getType()); 1705 if (!LTy) 1706 // Not a filter - skip it. 1707 continue; 1708 // If Filter is a subset of LFilter, i.e. every element of Filter is also 1709 // an element of LFilter, then discard LFilter. 1710 SmallVector<Value *, 16>::iterator J = NewClauses.begin() + j; 1711 // If Filter is empty then it is a subset of LFilter. 1712 if (!FElts) { 1713 // Discard LFilter. 1714 NewClauses.erase(J); 1715 MakeNewInstruction = true; 1716 // Move on to the next filter. 1717 continue; 1718 } 1719 unsigned LElts = LTy->getNumElements(); 1720 // If Filter is longer than LFilter then it cannot be a subset of it. 1721 if (FElts > LElts) 1722 // Move on to the next filter. 1723 continue; 1724 // At this point we know that LFilter has at least one element. 1725 if (isa<ConstantAggregateZero>(LFilter)) { // LFilter only contains zeros. 1726 // Filter is a subset of LFilter iff Filter contains only zeros (as we 1727 // already know that Filter is not longer than LFilter). 1728 if (isa<ConstantAggregateZero>(Filter)) { 1729 assert(FElts <= LElts && "Should have handled this case earlier!"); 1730 // Discard LFilter. 1731 NewClauses.erase(J); 1732 MakeNewInstruction = true; 1733 } 1734 // Move on to the next filter. 1735 continue; 1736 } 1737 ConstantArray *LArray = cast<ConstantArray>(LFilter); 1738 if (isa<ConstantAggregateZero>(Filter)) { // Filter only contains zeros. 1739 // Since Filter is non-empty and contains only zeros, it is a subset of 1740 // LFilter iff LFilter contains a zero. 1741 assert(FElts > 0 && "Should have eliminated the empty filter earlier!"); 1742 for (unsigned l = 0; l != LElts; ++l) 1743 if (LArray->getOperand(l)->isNullValue()) { 1744 // LFilter contains a zero - discard it. 1745 NewClauses.erase(J); 1746 MakeNewInstruction = true; 1747 break; 1748 } 1749 // Move on to the next filter. 1750 continue; 1751 } 1752 // At this point we know that both filters are ConstantArrays. Loop over 1753 // operands to see whether every element of Filter is also an element of 1754 // LFilter. Since filters tend to be short this is probably faster than 1755 // using a method that scales nicely. 1756 ConstantArray *FArray = cast<ConstantArray>(Filter); 1757 bool AllFound = true; 1758 for (unsigned f = 0; f != FElts; ++f) { 1759 Value *FTypeInfo = FArray->getOperand(f)->stripPointerCasts(); 1760 AllFound = false; 1761 for (unsigned l = 0; l != LElts; ++l) { 1762 Value *LTypeInfo = LArray->getOperand(l)->stripPointerCasts(); 1763 if (LTypeInfo == FTypeInfo) { 1764 AllFound = true; 1765 break; 1766 } 1767 } 1768 if (!AllFound) 1769 break; 1770 } 1771 if (AllFound) { 1772 // Discard LFilter. 1773 NewClauses.erase(J); 1774 MakeNewInstruction = true; 1775 } 1776 // Move on to the next filter. 1777 } 1778 } 1779 1780 // If we changed any of the clauses, replace the old landingpad instruction 1781 // with a new one. 1782 if (MakeNewInstruction) { 1783 LandingPadInst *NLI = LandingPadInst::Create(LI.getType(), 1784 LI.getPersonalityFn(), 1785 NewClauses.size()); 1786 for (unsigned i = 0, e = NewClauses.size(); i != e; ++i) 1787 NLI->addClause(NewClauses[i]); 1788 // A landing pad with no clauses must have the cleanup flag set. It is 1789 // theoretically possible, though highly unlikely, that we eliminated all 1790 // clauses. If so, force the cleanup flag to true. 1791 if (NewClauses.empty()) 1792 CleanupFlag = true; 1793 NLI->setCleanup(CleanupFlag); 1794 return NLI; 1795 } 1796 1797 // Even if none of the clauses changed, we may nonetheless have understood 1798 // that the cleanup flag is pointless. Clear it if so. 1799 if (LI.isCleanup() != CleanupFlag) { 1800 assert(!CleanupFlag && "Adding a cleanup, not removing one?!"); 1801 LI.setCleanup(CleanupFlag); 1802 return &LI; 1803 } 1804 1805 return 0; 1806} 1807 1808 1809 1810 1811/// TryToSinkInstruction - Try to move the specified instruction from its 1812/// current block into the beginning of DestBlock, which can only happen if it's 1813/// safe to move the instruction past all of the instructions between it and the 1814/// end of its block. 1815static bool TryToSinkInstruction(Instruction *I, BasicBlock *DestBlock) { 1816 assert(I->hasOneUse() && "Invariants didn't hold!"); 1817 1818 // Cannot move control-flow-involving, volatile loads, vaarg, etc. 1819 if (isa<PHINode>(I) || isa<LandingPadInst>(I) || I->mayHaveSideEffects() || 1820 isa<TerminatorInst>(I)) 1821 return false; 1822 1823 // Do not sink alloca instructions out of the entry block. 1824 if (isa<AllocaInst>(I) && I->getParent() == 1825 &DestBlock->getParent()->getEntryBlock()) 1826 return false; 1827 1828 // We can only sink load instructions if there is nothing between the load and 1829 // the end of block that could change the value. 1830 if (I->mayReadFromMemory()) { 1831 for (BasicBlock::iterator Scan = I, E = I->getParent()->end(); 1832 Scan != E; ++Scan) 1833 if (Scan->mayWriteToMemory()) 1834 return false; 1835 } 1836 1837 BasicBlock::iterator InsertPos = DestBlock->getFirstInsertionPt(); 1838 I->moveBefore(InsertPos); 1839 ++NumSunkInst; 1840 return true; 1841} 1842 1843 1844/// AddReachableCodeToWorklist - Walk the function in depth-first order, adding 1845/// all reachable code to the worklist. 1846/// 1847/// This has a couple of tricks to make the code faster and more powerful. In 1848/// particular, we constant fold and DCE instructions as we go, to avoid adding 1849/// them to the worklist (this significantly speeds up instcombine on code where 1850/// many instructions are dead or constant). Additionally, if we find a branch 1851/// whose condition is a known constant, we only visit the reachable successors. 1852/// 1853static bool AddReachableCodeToWorklist(BasicBlock *BB, 1854 SmallPtrSet<BasicBlock*, 64> &Visited, 1855 InstCombiner &IC, 1856 const TargetData *TD, 1857 const TargetLibraryInfo *TLI) { 1858 bool MadeIRChange = false; 1859 SmallVector<BasicBlock*, 256> Worklist; 1860 Worklist.push_back(BB); 1861 1862 SmallVector<Instruction*, 128> InstrsForInstCombineWorklist; 1863 DenseMap<ConstantExpr*, Constant*> FoldedConstants; 1864 1865 do { 1866 BB = Worklist.pop_back_val(); 1867 1868 // We have now visited this block! If we've already been here, ignore it. 1869 if (!Visited.insert(BB)) continue; 1870 1871 for (BasicBlock::iterator BBI = BB->begin(), E = BB->end(); BBI != E; ) { 1872 Instruction *Inst = BBI++; 1873 1874 // DCE instruction if trivially dead. 1875 if (isInstructionTriviallyDead(Inst)) { 1876 ++NumDeadInst; 1877 DEBUG(errs() << "IC: DCE: " << *Inst << '\n'); 1878 Inst->eraseFromParent(); 1879 continue; 1880 } 1881 1882 // ConstantProp instruction if trivially constant. 1883 if (!Inst->use_empty() && isa<Constant>(Inst->getOperand(0))) 1884 if (Constant *C = ConstantFoldInstruction(Inst, TD, TLI)) { 1885 DEBUG(errs() << "IC: ConstFold to: " << *C << " from: " 1886 << *Inst << '\n'); 1887 Inst->replaceAllUsesWith(C); 1888 ++NumConstProp; 1889 Inst->eraseFromParent(); 1890 continue; 1891 } 1892 1893 if (TD) { 1894 // See if we can constant fold its operands. 1895 for (User::op_iterator i = Inst->op_begin(), e = Inst->op_end(); 1896 i != e; ++i) { 1897 ConstantExpr *CE = dyn_cast<ConstantExpr>(i); 1898 if (CE == 0) continue; 1899 1900 Constant*& FoldRes = FoldedConstants[CE]; 1901 if (!FoldRes) 1902 FoldRes = ConstantFoldConstantExpression(CE, TD, TLI); 1903 if (!FoldRes) 1904 FoldRes = CE; 1905 1906 if (FoldRes != CE) { 1907 *i = FoldRes; 1908 MadeIRChange = true; 1909 } 1910 } 1911 } 1912 1913 InstrsForInstCombineWorklist.push_back(Inst); 1914 } 1915 1916 // Recursively visit successors. If this is a branch or switch on a 1917 // constant, only visit the reachable successor. 1918 TerminatorInst *TI = BB->getTerminator(); 1919 if (BranchInst *BI = dyn_cast<BranchInst>(TI)) { 1920 if (BI->isConditional() && isa<ConstantInt>(BI->getCondition())) { 1921 bool CondVal = cast<ConstantInt>(BI->getCondition())->getZExtValue(); 1922 BasicBlock *ReachableBB = BI->getSuccessor(!CondVal); 1923 Worklist.push_back(ReachableBB); 1924 continue; 1925 } 1926 } else if (SwitchInst *SI = dyn_cast<SwitchInst>(TI)) { 1927 if (ConstantInt *Cond = dyn_cast<ConstantInt>(SI->getCondition())) { 1928 // See if this is an explicit destination. 1929 for (SwitchInst::CaseIt i = SI->case_begin(), e = SI->case_end(); 1930 i != e; ++i) 1931 if (i.getCaseValue() == Cond) { 1932 BasicBlock *ReachableBB = i.getCaseSuccessor(); 1933 Worklist.push_back(ReachableBB); 1934 continue; 1935 } 1936 1937 // Otherwise it is the default destination. 1938 Worklist.push_back(SI->getDefaultDest()); 1939 continue; 1940 } 1941 } 1942 1943 for (unsigned i = 0, e = TI->getNumSuccessors(); i != e; ++i) 1944 Worklist.push_back(TI->getSuccessor(i)); 1945 } while (!Worklist.empty()); 1946 1947 // Once we've found all of the instructions to add to instcombine's worklist, 1948 // add them in reverse order. This way instcombine will visit from the top 1949 // of the function down. This jives well with the way that it adds all uses 1950 // of instructions to the worklist after doing a transformation, thus avoiding 1951 // some N^2 behavior in pathological cases. 1952 IC.Worklist.AddInitialGroup(&InstrsForInstCombineWorklist[0], 1953 InstrsForInstCombineWorklist.size()); 1954 1955 return MadeIRChange; 1956} 1957 1958bool InstCombiner::DoOneIteration(Function &F, unsigned Iteration) { 1959 MadeIRChange = false; 1960 1961 DEBUG(errs() << "\n\nINSTCOMBINE ITERATION #" << Iteration << " on " 1962 << F.getName() << "\n"); 1963 1964 { 1965 // Do a depth-first traversal of the function, populate the worklist with 1966 // the reachable instructions. Ignore blocks that are not reachable. Keep 1967 // track of which blocks we visit. 1968 SmallPtrSet<BasicBlock*, 64> Visited; 1969 MadeIRChange |= AddReachableCodeToWorklist(F.begin(), Visited, *this, TD, 1970 TLI); 1971 1972 // Do a quick scan over the function. If we find any blocks that are 1973 // unreachable, remove any instructions inside of them. This prevents 1974 // the instcombine code from having to deal with some bad special cases. 1975 for (Function::iterator BB = F.begin(), E = F.end(); BB != E; ++BB) { 1976 if (Visited.count(BB)) continue; 1977 1978 // Delete the instructions backwards, as it has a reduced likelihood of 1979 // having to update as many def-use and use-def chains. 1980 Instruction *EndInst = BB->getTerminator(); // Last not to be deleted. 1981 while (EndInst != BB->begin()) { 1982 // Delete the next to last instruction. 1983 BasicBlock::iterator I = EndInst; 1984 Instruction *Inst = --I; 1985 if (!Inst->use_empty()) 1986 Inst->replaceAllUsesWith(UndefValue::get(Inst->getType())); 1987 if (isa<LandingPadInst>(Inst)) { 1988 EndInst = Inst; 1989 continue; 1990 } 1991 if (!isa<DbgInfoIntrinsic>(Inst)) { 1992 ++NumDeadInst; 1993 MadeIRChange = true; 1994 } 1995 Inst->eraseFromParent(); 1996 } 1997 } 1998 } 1999 2000 while (!Worklist.isEmpty()) { 2001 Instruction *I = Worklist.RemoveOne(); 2002 if (I == 0) continue; // skip null values. 2003 2004 // Check to see if we can DCE the instruction. 2005 if (isInstructionTriviallyDead(I)) { 2006 DEBUG(errs() << "IC: DCE: " << *I << '\n'); 2007 EraseInstFromFunction(*I); 2008 ++NumDeadInst; 2009 MadeIRChange = true; 2010 continue; 2011 } 2012 2013 // Instruction isn't dead, see if we can constant propagate it. 2014 if (!I->use_empty() && isa<Constant>(I->getOperand(0))) 2015 if (Constant *C = ConstantFoldInstruction(I, TD, TLI)) { 2016 DEBUG(errs() << "IC: ConstFold to: " << *C << " from: " << *I << '\n'); 2017 2018 // Add operands to the worklist. 2019 ReplaceInstUsesWith(*I, C); 2020 ++NumConstProp; 2021 EraseInstFromFunction(*I); 2022 MadeIRChange = true; 2023 continue; 2024 } 2025 2026 // See if we can trivially sink this instruction to a successor basic block. 2027 if (I->hasOneUse()) { 2028 BasicBlock *BB = I->getParent(); 2029 Instruction *UserInst = cast<Instruction>(I->use_back()); 2030 BasicBlock *UserParent; 2031 2032 // Get the block the use occurs in. 2033 if (PHINode *PN = dyn_cast<PHINode>(UserInst)) 2034 UserParent = PN->getIncomingBlock(I->use_begin().getUse()); 2035 else 2036 UserParent = UserInst->getParent(); 2037 2038 if (UserParent != BB) { 2039 bool UserIsSuccessor = false; 2040 // See if the user is one of our successors. 2041 for (succ_iterator SI = succ_begin(BB), E = succ_end(BB); SI != E; ++SI) 2042 if (*SI == UserParent) { 2043 UserIsSuccessor = true; 2044 break; 2045 } 2046 2047 // If the user is one of our immediate successors, and if that successor 2048 // only has us as a predecessors (we'd have to split the critical edge 2049 // otherwise), we can keep going. 2050 if (UserIsSuccessor && UserParent->getSinglePredecessor()) 2051 // Okay, the CFG is simple enough, try to sink this instruction. 2052 MadeIRChange |= TryToSinkInstruction(I, UserParent); 2053 } 2054 } 2055 2056 // Now that we have an instruction, try combining it to simplify it. 2057 Builder->SetInsertPoint(I->getParent(), I); 2058 Builder->SetCurrentDebugLocation(I->getDebugLoc()); 2059 2060#ifndef NDEBUG 2061 std::string OrigI; 2062#endif 2063 DEBUG(raw_string_ostream SS(OrigI); I->print(SS); OrigI = SS.str();); 2064 DEBUG(errs() << "IC: Visiting: " << OrigI << '\n'); 2065 2066 if (Instruction *Result = visit(*I)) { 2067 ++NumCombined; 2068 // Should we replace the old instruction with a new one? 2069 if (Result != I) { 2070 DEBUG(errs() << "IC: Old = " << *I << '\n' 2071 << " New = " << *Result << '\n'); 2072 2073 if (!I->getDebugLoc().isUnknown()) 2074 Result->setDebugLoc(I->getDebugLoc()); 2075 // Everything uses the new instruction now. 2076 I->replaceAllUsesWith(Result); 2077 2078 // Move the name to the new instruction first. 2079 Result->takeName(I); 2080 2081 // Push the new instruction and any users onto the worklist. 2082 Worklist.Add(Result); 2083 Worklist.AddUsersToWorkList(*Result); 2084 2085 // Insert the new instruction into the basic block... 2086 BasicBlock *InstParent = I->getParent(); 2087 BasicBlock::iterator InsertPos = I; 2088 2089 // If we replace a PHI with something that isn't a PHI, fix up the 2090 // insertion point. 2091 if (!isa<PHINode>(Result) && isa<PHINode>(InsertPos)) 2092 InsertPos = InstParent->getFirstInsertionPt(); 2093 2094 InstParent->getInstList().insert(InsertPos, Result); 2095 2096 EraseInstFromFunction(*I); 2097 } else { 2098#ifndef NDEBUG 2099 DEBUG(errs() << "IC: Mod = " << OrigI << '\n' 2100 << " New = " << *I << '\n'); 2101#endif 2102 2103 // If the instruction was modified, it's possible that it is now dead. 2104 // if so, remove it. 2105 if (isInstructionTriviallyDead(I)) { 2106 EraseInstFromFunction(*I); 2107 } else { 2108 Worklist.Add(I); 2109 Worklist.AddUsersToWorkList(*I); 2110 } 2111 } 2112 MadeIRChange = true; 2113 } 2114 } 2115 2116 Worklist.Zap(); 2117 return MadeIRChange; 2118} 2119 2120 2121bool InstCombiner::runOnFunction(Function &F) { 2122 TD = getAnalysisIfAvailable<TargetData>(); 2123 TLI = &getAnalysis<TargetLibraryInfo>(); 2124 2125 /// Builder - This is an IRBuilder that automatically inserts new 2126 /// instructions into the worklist when they are created. 2127 IRBuilder<true, TargetFolder, InstCombineIRInserter> 2128 TheBuilder(F.getContext(), TargetFolder(TD), 2129 InstCombineIRInserter(Worklist)); 2130 Builder = &TheBuilder; 2131 2132 bool EverMadeChange = false; 2133 2134 // Lower dbg.declare intrinsics otherwise their value may be clobbered 2135 // by instcombiner. 2136 EverMadeChange = LowerDbgDeclare(F); 2137 2138 // Iterate while there is work to do. 2139 unsigned Iteration = 0; 2140 while (DoOneIteration(F, Iteration++)) 2141 EverMadeChange = true; 2142 2143 Builder = 0; 2144 return EverMadeChange; 2145} 2146 2147FunctionPass *llvm::createInstructionCombiningPass() { 2148 return new InstCombiner(); 2149} 2150