InstructionCombining.cpp revision a3c44a5280042dbc0cde995675c225ede4528c6e
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/Transforms/Utils/Local.h" 45#include "llvm/Support/CFG.h" 46#include "llvm/Support/Debug.h" 47#include "llvm/Support/GetElementPtrTypeIterator.h" 48#include "llvm/Support/PatternMatch.h" 49#include "llvm/ADT/SmallPtrSet.h" 50#include "llvm/ADT/Statistic.h" 51#include "llvm-c/Initialization.h" 52#include <algorithm> 53#include <climits> 54using namespace llvm; 55using namespace llvm::PatternMatch; 56 57STATISTIC(NumCombined , "Number of insts combined"); 58STATISTIC(NumConstProp, "Number of constant folds"); 59STATISTIC(NumDeadInst , "Number of dead inst eliminated"); 60STATISTIC(NumSunkInst , "Number of instructions sunk"); 61STATISTIC(NumFactor , "Number of factorizations"); 62STATISTIC(NumReassoc , "Number of reassociations"); 63 64// Initialization Routines 65void llvm::initializeInstCombine(PassRegistry &Registry) { 66 initializeInstCombinerPass(Registry); 67} 68 69void LLVMInitializeInstCombine(LLVMPassRegistryRef R) { 70 initializeInstCombine(*unwrap(R)); 71} 72 73char InstCombiner::ID = 0; 74INITIALIZE_PASS(InstCombiner, "instcombine", 75 "Combine redundant instructions", false, false) 76 77void InstCombiner::getAnalysisUsage(AnalysisUsage &AU) const { 78 AU.addPreservedID(LCSSAID); 79 AU.setPreservesCFG(); 80} 81 82 83/// ShouldChangeType - Return true if it is desirable to convert a computation 84/// from 'From' to 'To'. We don't want to convert from a legal to an illegal 85/// type for example, or from a smaller to a larger illegal type. 86bool InstCombiner::ShouldChangeType(const Type *From, const Type *To) const { 87 assert(From->isIntegerTy() && To->isIntegerTy()); 88 89 // If we don't have TD, we don't know if the source/dest are legal. 90 if (!TD) return false; 91 92 unsigned FromWidth = From->getPrimitiveSizeInBits(); 93 unsigned ToWidth = To->getPrimitiveSizeInBits(); 94 bool FromLegal = TD->isLegalInteger(FromWidth); 95 bool ToLegal = TD->isLegalInteger(ToWidth); 96 97 // If this is a legal integer from type, and the result would be an illegal 98 // type, don't do the transformation. 99 if (FromLegal && !ToLegal) 100 return false; 101 102 // Otherwise, if both are illegal, do not increase the size of the result. We 103 // do allow things like i160 -> i64, but not i64 -> i160. 104 if (!FromLegal && !ToLegal && ToWidth > FromWidth) 105 return false; 106 107 return true; 108} 109 110 111/// SimplifyAssociativeOrCommutative - This performs a few simplifications for 112/// operators which are associative or commutative: 113// 114// Commutative operators: 115// 116// 1. Order operands such that they are listed from right (least complex) to 117// left (most complex). This puts constants before unary operators before 118// binary operators. 119// 120// Associative operators: 121// 122// 2. Transform: "(A op B) op C" ==> "A op (B op C)" if "B op C" simplifies. 123// 3. Transform: "A op (B op C)" ==> "(A op B) op C" if "A op B" simplifies. 124// 125// Associative and commutative operators: 126// 127// 4. Transform: "(A op B) op C" ==> "(C op A) op B" if "C op A" simplifies. 128// 5. Transform: "A op (B op C)" ==> "B op (C op A)" if "C op A" simplifies. 129// 6. Transform: "(A op C1) op (B op C2)" ==> "(A op B) op (C1 op C2)" 130// if C1 and C2 are constants. 131// 132bool InstCombiner::SimplifyAssociativeOrCommutative(BinaryOperator &I) { 133 Instruction::BinaryOps Opcode = I.getOpcode(); 134 bool Changed = false; 135 136 do { 137 // Order operands such that they are listed from right (least complex) to 138 // left (most complex). This puts constants before unary operators before 139 // binary operators. 140 if (I.isCommutative() && getComplexity(I.getOperand(0)) < 141 getComplexity(I.getOperand(1))) 142 Changed = !I.swapOperands(); 143 144 BinaryOperator *Op0 = dyn_cast<BinaryOperator>(I.getOperand(0)); 145 BinaryOperator *Op1 = dyn_cast<BinaryOperator>(I.getOperand(1)); 146 147 if (I.isAssociative()) { 148 // Transform: "(A op B) op C" ==> "A op (B op C)" if "B op C" simplifies. 149 if (Op0 && Op0->getOpcode() == Opcode) { 150 Value *A = Op0->getOperand(0); 151 Value *B = Op0->getOperand(1); 152 Value *C = I.getOperand(1); 153 154 // Does "B op C" simplify? 155 if (Value *V = SimplifyBinOp(Opcode, B, C, TD)) { 156 // It simplifies to V. Form "A op V". 157 I.setOperand(0, A); 158 I.setOperand(1, V); 159 Changed = true; 160 ++NumReassoc; 161 continue; 162 } 163 } 164 165 // Transform: "A op (B op C)" ==> "(A op B) op C" if "A op B" simplifies. 166 if (Op1 && Op1->getOpcode() == Opcode) { 167 Value *A = I.getOperand(0); 168 Value *B = Op1->getOperand(0); 169 Value *C = Op1->getOperand(1); 170 171 // Does "A op B" simplify? 172 if (Value *V = SimplifyBinOp(Opcode, A, B, TD)) { 173 // It simplifies to V. Form "V op C". 174 I.setOperand(0, V); 175 I.setOperand(1, C); 176 Changed = true; 177 ++NumReassoc; 178 continue; 179 } 180 } 181 } 182 183 if (I.isAssociative() && I.isCommutative()) { 184 // Transform: "(A op B) op C" ==> "(C op A) op B" if "C op A" simplifies. 185 if (Op0 && Op0->getOpcode() == Opcode) { 186 Value *A = Op0->getOperand(0); 187 Value *B = Op0->getOperand(1); 188 Value *C = I.getOperand(1); 189 190 // Does "C op A" simplify? 191 if (Value *V = SimplifyBinOp(Opcode, C, A, TD)) { 192 // It simplifies to V. Form "V op B". 193 I.setOperand(0, V); 194 I.setOperand(1, B); 195 Changed = true; 196 ++NumReassoc; 197 continue; 198 } 199 } 200 201 // Transform: "A op (B op C)" ==> "B op (C op A)" if "C op A" simplifies. 202 if (Op1 && Op1->getOpcode() == Opcode) { 203 Value *A = I.getOperand(0); 204 Value *B = Op1->getOperand(0); 205 Value *C = Op1->getOperand(1); 206 207 // Does "C op A" simplify? 208 if (Value *V = SimplifyBinOp(Opcode, C, A, TD)) { 209 // It simplifies to V. Form "B op V". 210 I.setOperand(0, B); 211 I.setOperand(1, V); 212 Changed = true; 213 ++NumReassoc; 214 continue; 215 } 216 } 217 218 // Transform: "(A op C1) op (B op C2)" ==> "(A op B) op (C1 op C2)" 219 // if C1 and C2 are constants. 220 if (Op0 && Op1 && 221 Op0->getOpcode() == Opcode && Op1->getOpcode() == Opcode && 222 isa<Constant>(Op0->getOperand(1)) && 223 isa<Constant>(Op1->getOperand(1)) && 224 Op0->hasOneUse() && Op1->hasOneUse()) { 225 Value *A = Op0->getOperand(0); 226 Constant *C1 = cast<Constant>(Op0->getOperand(1)); 227 Value *B = Op1->getOperand(0); 228 Constant *C2 = cast<Constant>(Op1->getOperand(1)); 229 230 Constant *Folded = ConstantExpr::get(Opcode, C1, C2); 231 Instruction *New = BinaryOperator::Create(Opcode, A, B, Op1->getName(), 232 &I); 233 Worklist.Add(New); 234 I.setOperand(0, New); 235 I.setOperand(1, Folded); 236 Changed = true; 237 continue; 238 } 239 } 240 241 // No further simplifications. 242 return Changed; 243 } while (1); 244} 245 246/// LeftDistributesOverRight - Whether "X LOp (Y ROp Z)" is always equal to 247/// "(X LOp Y) ROp (X LOp Z)". 248static bool LeftDistributesOverRight(Instruction::BinaryOps LOp, 249 Instruction::BinaryOps ROp) { 250 switch (LOp) { 251 default: 252 return false; 253 254 case Instruction::And: 255 // And distributes over Or and Xor. 256 switch (ROp) { 257 default: 258 return false; 259 case Instruction::Or: 260 case Instruction::Xor: 261 return true; 262 } 263 264 case Instruction::Mul: 265 // Multiplication distributes over addition and subtraction. 266 switch (ROp) { 267 default: 268 return false; 269 case Instruction::Add: 270 case Instruction::Sub: 271 return true; 272 } 273 274 case Instruction::Or: 275 // Or distributes over And. 276 switch (ROp) { 277 default: 278 return false; 279 case Instruction::And: 280 return true; 281 } 282 } 283} 284 285/// RightDistributesOverLeft - Whether "(X LOp Y) ROp Z" is always equal to 286/// "(X ROp Z) LOp (Y ROp Z)". 287static bool RightDistributesOverLeft(Instruction::BinaryOps LOp, 288 Instruction::BinaryOps ROp) { 289 if (Instruction::isCommutative(ROp)) 290 return LeftDistributesOverRight(ROp, LOp); 291 // TODO: It would be nice to handle division, aka "(X + Y)/Z = X/Z + Y/Z", 292 // but this requires knowing that the addition does not overflow and other 293 // such subtleties. 294 return false; 295} 296 297/// SimplifyByFactorizing - This tries to simplify binary operations which 298/// some other binary operation distributes over by factorizing out a common 299/// term (eg "(A*B)+(A*C)" -> "A*(B+C)"). Returns the simplified value, or 300/// null if no simplification was performed. 301Instruction *InstCombiner::SimplifyByFactorizing(BinaryOperator &I) { 302 BinaryOperator *Op0 = dyn_cast<BinaryOperator>(I.getOperand(0)); 303 BinaryOperator *Op1 = dyn_cast<BinaryOperator>(I.getOperand(1)); 304 if (!Op0 || !Op1 || Op0->getOpcode() != Op1->getOpcode()) 305 return 0; 306 307 // The instruction has the form "(A op' B) op (C op' D)". 308 Value *A = Op0->getOperand(0); Value *B = Op0->getOperand(1); 309 Value *C = Op1->getOperand(0); Value *D = Op1->getOperand(1); 310 Instruction::BinaryOps OuterOpcode = I.getOpcode(); // op 311 Instruction::BinaryOps InnerOpcode = Op0->getOpcode(); // op' 312 313 // Does "X op' Y" always equal "Y op' X"? 314 bool InnerCommutative = Instruction::isCommutative(InnerOpcode); 315 316 // Does "X op' (Y op Z)" always equal "(X op' Y) op (X op' Z)"? 317 if (LeftDistributesOverRight(InnerOpcode, OuterOpcode)) 318 // Does the instruction have the form "(A op' B) op (A op' D)" or, in the 319 // commutative case, "(A op' B) op (C op' A)"? 320 if (A == C || (InnerCommutative && A == D)) { 321 if (A != C) 322 std::swap(C, D); 323 // Consider forming "A op' (B op D)". 324 // If "B op D" simplifies then it can be formed with no cost. 325 Value *RHS = SimplifyBinOp(OuterOpcode, B, D, TD); 326 // If "B op D" doesn't simplify then only proceed if both of the existing 327 // operations "A op' B" and "C op' D" will be zapped since no longer used. 328 if (!RHS && Op0->hasOneUse() && Op1->hasOneUse()) 329 RHS = Builder->CreateBinOp(OuterOpcode, B, D, Op1->getName()); 330 if (RHS) { 331 ++NumFactor; 332 return BinaryOperator::Create(InnerOpcode, A, RHS); 333 } 334 } 335 336 // Does "(X op Y) op' Z" always equal "(X op' Z) op (Y op' Z)"? 337 if (RightDistributesOverLeft(OuterOpcode, InnerOpcode)) 338 // Does the instruction have the form "(A op' B) op (C op' B)" or, in the 339 // commutative case, "(A op' B) op (B op' D)"? 340 if (B == D || (InnerCommutative && B == C)) { 341 if (B != D) 342 std::swap(C, D); 343 // Consider forming "(A op C) op' B". 344 // If "A op C" simplifies then it can be formed with no cost. 345 Value *LHS = SimplifyBinOp(OuterOpcode, A, C, TD); 346 // If "A op C" doesn't simplify then only proceed if both of the existing 347 // operations "A op' B" and "C op' D" will be zapped since no longer used. 348 if (!LHS && Op0->hasOneUse() && Op1->hasOneUse()) 349 LHS = Builder->CreateBinOp(OuterOpcode, A, C, Op0->getName()); 350 if (LHS) { 351 ++NumFactor; 352 return BinaryOperator::Create(InnerOpcode, LHS, B); 353 } 354 } 355 356 return 0; 357} 358 359// dyn_castNegVal - Given a 'sub' instruction, return the RHS of the instruction 360// if the LHS is a constant zero (which is the 'negate' form). 361// 362Value *InstCombiner::dyn_castNegVal(Value *V) const { 363 if (BinaryOperator::isNeg(V)) 364 return BinaryOperator::getNegArgument(V); 365 366 // Constants can be considered to be negated values if they can be folded. 367 if (ConstantInt *C = dyn_cast<ConstantInt>(V)) 368 return ConstantExpr::getNeg(C); 369 370 if (ConstantVector *C = dyn_cast<ConstantVector>(V)) 371 if (C->getType()->getElementType()->isIntegerTy()) 372 return ConstantExpr::getNeg(C); 373 374 return 0; 375} 376 377// dyn_castFNegVal - Given a 'fsub' instruction, return the RHS of the 378// instruction if the LHS is a constant negative zero (which is the 'negate' 379// form). 380// 381Value *InstCombiner::dyn_castFNegVal(Value *V) const { 382 if (BinaryOperator::isFNeg(V)) 383 return BinaryOperator::getFNegArgument(V); 384 385 // Constants can be considered to be negated values if they can be folded. 386 if (ConstantFP *C = dyn_cast<ConstantFP>(V)) 387 return ConstantExpr::getFNeg(C); 388 389 if (ConstantVector *C = dyn_cast<ConstantVector>(V)) 390 if (C->getType()->getElementType()->isFloatingPointTy()) 391 return ConstantExpr::getFNeg(C); 392 393 return 0; 394} 395 396static Value *FoldOperationIntoSelectOperand(Instruction &I, Value *SO, 397 InstCombiner *IC) { 398 if (CastInst *CI = dyn_cast<CastInst>(&I)) 399 return IC->Builder->CreateCast(CI->getOpcode(), SO, I.getType()); 400 401 // Figure out if the constant is the left or the right argument. 402 bool ConstIsRHS = isa<Constant>(I.getOperand(1)); 403 Constant *ConstOperand = cast<Constant>(I.getOperand(ConstIsRHS)); 404 405 if (Constant *SOC = dyn_cast<Constant>(SO)) { 406 if (ConstIsRHS) 407 return ConstantExpr::get(I.getOpcode(), SOC, ConstOperand); 408 return ConstantExpr::get(I.getOpcode(), ConstOperand, SOC); 409 } 410 411 Value *Op0 = SO, *Op1 = ConstOperand; 412 if (!ConstIsRHS) 413 std::swap(Op0, Op1); 414 415 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(&I)) 416 return IC->Builder->CreateBinOp(BO->getOpcode(), Op0, Op1, 417 SO->getName()+".op"); 418 if (ICmpInst *CI = dyn_cast<ICmpInst>(&I)) 419 return IC->Builder->CreateICmp(CI->getPredicate(), Op0, Op1, 420 SO->getName()+".cmp"); 421 if (FCmpInst *CI = dyn_cast<FCmpInst>(&I)) 422 return IC->Builder->CreateICmp(CI->getPredicate(), Op0, Op1, 423 SO->getName()+".cmp"); 424 llvm_unreachable("Unknown binary instruction type!"); 425} 426 427// FoldOpIntoSelect - Given an instruction with a select as one operand and a 428// constant as the other operand, try to fold the binary operator into the 429// select arguments. This also works for Cast instructions, which obviously do 430// not have a second operand. 431Instruction *InstCombiner::FoldOpIntoSelect(Instruction &Op, SelectInst *SI) { 432 // Don't modify shared select instructions 433 if (!SI->hasOneUse()) return 0; 434 Value *TV = SI->getOperand(1); 435 Value *FV = SI->getOperand(2); 436 437 if (isa<Constant>(TV) || isa<Constant>(FV)) { 438 // Bool selects with constant operands can be folded to logical ops. 439 if (SI->getType()->isIntegerTy(1)) return 0; 440 441 Value *SelectTrueVal = FoldOperationIntoSelectOperand(Op, TV, this); 442 Value *SelectFalseVal = FoldOperationIntoSelectOperand(Op, FV, this); 443 444 return SelectInst::Create(SI->getCondition(), SelectTrueVal, 445 SelectFalseVal); 446 } 447 return 0; 448} 449 450 451/// FoldOpIntoPhi - Given a binary operator, cast instruction, or select which 452/// has a PHI node as operand #0, see if we can fold the instruction into the 453/// PHI (which is only possible if all operands to the PHI are constants). 454/// 455/// If AllowAggressive is true, FoldOpIntoPhi will allow certain transforms 456/// that would normally be unprofitable because they strongly encourage jump 457/// threading. 458Instruction *InstCombiner::FoldOpIntoPhi(Instruction &I, 459 bool AllowAggressive) { 460 AllowAggressive = false; 461 PHINode *PN = cast<PHINode>(I.getOperand(0)); 462 unsigned NumPHIValues = PN->getNumIncomingValues(); 463 if (NumPHIValues == 0 || 464 // We normally only transform phis with a single use, unless we're trying 465 // hard to make jump threading happen. 466 (!PN->hasOneUse() && !AllowAggressive)) 467 return 0; 468 469 470 // Check to see if all of the operands of the PHI are simple constants 471 // (constantint/constantfp/undef). If there is one non-constant value, 472 // remember the BB it is in. If there is more than one or if *it* is a PHI, 473 // bail out. We don't do arbitrary constant expressions here because moving 474 // their computation can be expensive without a cost model. 475 BasicBlock *NonConstBB = 0; 476 for (unsigned i = 0; i != NumPHIValues; ++i) 477 if (!isa<Constant>(PN->getIncomingValue(i)) || 478 isa<ConstantExpr>(PN->getIncomingValue(i))) { 479 if (NonConstBB) return 0; // More than one non-const value. 480 if (isa<PHINode>(PN->getIncomingValue(i))) return 0; // Itself a phi. 481 NonConstBB = PN->getIncomingBlock(i); 482 483 // If the incoming non-constant value is in I's block, we have an infinite 484 // loop. 485 if (NonConstBB == I.getParent()) 486 return 0; 487 } 488 489 // If there is exactly one non-constant value, we can insert a copy of the 490 // operation in that block. However, if this is a critical edge, we would be 491 // inserting the computation one some other paths (e.g. inside a loop). Only 492 // do this if the pred block is unconditionally branching into the phi block. 493 if (NonConstBB != 0 && !AllowAggressive) { 494 BranchInst *BI = dyn_cast<BranchInst>(NonConstBB->getTerminator()); 495 if (!BI || !BI->isUnconditional()) return 0; 496 } 497 498 // Okay, we can do the transformation: create the new PHI node. 499 PHINode *NewPN = PHINode::Create(I.getType(), ""); 500 NewPN->reserveOperandSpace(PN->getNumOperands()/2); 501 InsertNewInstBefore(NewPN, *PN); 502 NewPN->takeName(PN); 503 504 // Next, add all of the operands to the PHI. 505 if (SelectInst *SI = dyn_cast<SelectInst>(&I)) { 506 // We only currently try to fold the condition of a select when it is a phi, 507 // not the true/false values. 508 Value *TrueV = SI->getTrueValue(); 509 Value *FalseV = SI->getFalseValue(); 510 BasicBlock *PhiTransBB = PN->getParent(); 511 for (unsigned i = 0; i != NumPHIValues; ++i) { 512 BasicBlock *ThisBB = PN->getIncomingBlock(i); 513 Value *TrueVInPred = TrueV->DoPHITranslation(PhiTransBB, ThisBB); 514 Value *FalseVInPred = FalseV->DoPHITranslation(PhiTransBB, ThisBB); 515 Value *InV = 0; 516 if (Constant *InC = dyn_cast<Constant>(PN->getIncomingValue(i))) { 517 InV = InC->isNullValue() ? FalseVInPred : TrueVInPred; 518 } else { 519 assert(PN->getIncomingBlock(i) == NonConstBB); 520 InV = SelectInst::Create(PN->getIncomingValue(i), TrueVInPred, 521 FalseVInPred, 522 "phitmp", NonConstBB->getTerminator()); 523 Worklist.Add(cast<Instruction>(InV)); 524 } 525 NewPN->addIncoming(InV, ThisBB); 526 } 527 } else if (I.getNumOperands() == 2) { 528 Constant *C = cast<Constant>(I.getOperand(1)); 529 for (unsigned i = 0; i != NumPHIValues; ++i) { 530 Value *InV = 0; 531 if (Constant *InC = dyn_cast<Constant>(PN->getIncomingValue(i))) { 532 if (CmpInst *CI = dyn_cast<CmpInst>(&I)) 533 InV = ConstantExpr::getCompare(CI->getPredicate(), InC, C); 534 else 535 InV = ConstantExpr::get(I.getOpcode(), InC, C); 536 } else { 537 assert(PN->getIncomingBlock(i) == NonConstBB); 538 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(&I)) 539 InV = BinaryOperator::Create(BO->getOpcode(), 540 PN->getIncomingValue(i), C, "phitmp", 541 NonConstBB->getTerminator()); 542 else if (CmpInst *CI = dyn_cast<CmpInst>(&I)) 543 InV = CmpInst::Create(CI->getOpcode(), 544 CI->getPredicate(), 545 PN->getIncomingValue(i), C, "phitmp", 546 NonConstBB->getTerminator()); 547 else 548 llvm_unreachable("Unknown binop!"); 549 550 Worklist.Add(cast<Instruction>(InV)); 551 } 552 NewPN->addIncoming(InV, PN->getIncomingBlock(i)); 553 } 554 } else { 555 CastInst *CI = cast<CastInst>(&I); 556 const Type *RetTy = CI->getType(); 557 for (unsigned i = 0; i != NumPHIValues; ++i) { 558 Value *InV; 559 if (Constant *InC = dyn_cast<Constant>(PN->getIncomingValue(i))) { 560 InV = ConstantExpr::getCast(CI->getOpcode(), InC, RetTy); 561 } else { 562 assert(PN->getIncomingBlock(i) == NonConstBB); 563 InV = CastInst::Create(CI->getOpcode(), PN->getIncomingValue(i), 564 I.getType(), "phitmp", 565 NonConstBB->getTerminator()); 566 Worklist.Add(cast<Instruction>(InV)); 567 } 568 NewPN->addIncoming(InV, PN->getIncomingBlock(i)); 569 } 570 } 571 return ReplaceInstUsesWith(I, NewPN); 572} 573 574/// FindElementAtOffset - Given a type and a constant offset, determine whether 575/// or not there is a sequence of GEP indices into the type that will land us at 576/// the specified offset. If so, fill them into NewIndices and return the 577/// resultant element type, otherwise return null. 578const Type *InstCombiner::FindElementAtOffset(const Type *Ty, int64_t Offset, 579 SmallVectorImpl<Value*> &NewIndices) { 580 if (!TD) return 0; 581 if (!Ty->isSized()) return 0; 582 583 // Start with the index over the outer type. Note that the type size 584 // might be zero (even if the offset isn't zero) if the indexed type 585 // is something like [0 x {int, int}] 586 const Type *IntPtrTy = TD->getIntPtrType(Ty->getContext()); 587 int64_t FirstIdx = 0; 588 if (int64_t TySize = TD->getTypeAllocSize(Ty)) { 589 FirstIdx = Offset/TySize; 590 Offset -= FirstIdx*TySize; 591 592 // Handle hosts where % returns negative instead of values [0..TySize). 593 if (Offset < 0) { 594 --FirstIdx; 595 Offset += TySize; 596 assert(Offset >= 0); 597 } 598 assert((uint64_t)Offset < (uint64_t)TySize && "Out of range offset"); 599 } 600 601 NewIndices.push_back(ConstantInt::get(IntPtrTy, FirstIdx)); 602 603 // Index into the types. If we fail, set OrigBase to null. 604 while (Offset) { 605 // Indexing into tail padding between struct/array elements. 606 if (uint64_t(Offset*8) >= TD->getTypeSizeInBits(Ty)) 607 return 0; 608 609 if (const StructType *STy = dyn_cast<StructType>(Ty)) { 610 const StructLayout *SL = TD->getStructLayout(STy); 611 assert(Offset < (int64_t)SL->getSizeInBytes() && 612 "Offset must stay within the indexed type"); 613 614 unsigned Elt = SL->getElementContainingOffset(Offset); 615 NewIndices.push_back(ConstantInt::get(Type::getInt32Ty(Ty->getContext()), 616 Elt)); 617 618 Offset -= SL->getElementOffset(Elt); 619 Ty = STy->getElementType(Elt); 620 } else if (const ArrayType *AT = dyn_cast<ArrayType>(Ty)) { 621 uint64_t EltSize = TD->getTypeAllocSize(AT->getElementType()); 622 assert(EltSize && "Cannot index into a zero-sized array"); 623 NewIndices.push_back(ConstantInt::get(IntPtrTy,Offset/EltSize)); 624 Offset %= EltSize; 625 Ty = AT->getElementType(); 626 } else { 627 // Otherwise, we can't index into the middle of this atomic type, bail. 628 return 0; 629 } 630 } 631 632 return Ty; 633} 634 635 636 637Instruction *InstCombiner::visitGetElementPtrInst(GetElementPtrInst &GEP) { 638 SmallVector<Value*, 8> Ops(GEP.op_begin(), GEP.op_end()); 639 640 if (Value *V = SimplifyGEPInst(&Ops[0], Ops.size(), TD)) 641 return ReplaceInstUsesWith(GEP, V); 642 643 Value *PtrOp = GEP.getOperand(0); 644 645 // Eliminate unneeded casts for indices, and replace indices which displace 646 // by multiples of a zero size type with zero. 647 if (TD) { 648 bool MadeChange = false; 649 const Type *IntPtrTy = TD->getIntPtrType(GEP.getContext()); 650 651 gep_type_iterator GTI = gep_type_begin(GEP); 652 for (User::op_iterator I = GEP.op_begin() + 1, E = GEP.op_end(); 653 I != E; ++I, ++GTI) { 654 // Skip indices into struct types. 655 const SequentialType *SeqTy = dyn_cast<SequentialType>(*GTI); 656 if (!SeqTy) continue; 657 658 // If the element type has zero size then any index over it is equivalent 659 // to an index of zero, so replace it with zero if it is not zero already. 660 if (SeqTy->getElementType()->isSized() && 661 TD->getTypeAllocSize(SeqTy->getElementType()) == 0) 662 if (!isa<Constant>(*I) || !cast<Constant>(*I)->isNullValue()) { 663 *I = Constant::getNullValue(IntPtrTy); 664 MadeChange = true; 665 } 666 667 if ((*I)->getType() != IntPtrTy) { 668 // If we are using a wider index than needed for this platform, shrink 669 // it to what we need. If narrower, sign-extend it to what we need. 670 // This explicit cast can make subsequent optimizations more obvious. 671 *I = Builder->CreateIntCast(*I, IntPtrTy, true); 672 MadeChange = true; 673 } 674 } 675 if (MadeChange) return &GEP; 676 } 677 678 // Combine Indices - If the source pointer to this getelementptr instruction 679 // is a getelementptr instruction, combine the indices of the two 680 // getelementptr instructions into a single instruction. 681 // 682 if (GEPOperator *Src = dyn_cast<GEPOperator>(PtrOp)) { 683 // Note that if our source is a gep chain itself that we wait for that 684 // chain to be resolved before we perform this transformation. This 685 // avoids us creating a TON of code in some cases. 686 // 687 if (GetElementPtrInst *SrcGEP = 688 dyn_cast<GetElementPtrInst>(Src->getOperand(0))) 689 if (SrcGEP->getNumOperands() == 2) 690 return 0; // Wait until our source is folded to completion. 691 692 SmallVector<Value*, 8> Indices; 693 694 // Find out whether the last index in the source GEP is a sequential idx. 695 bool EndsWithSequential = false; 696 for (gep_type_iterator I = gep_type_begin(*Src), E = gep_type_end(*Src); 697 I != E; ++I) 698 EndsWithSequential = !(*I)->isStructTy(); 699 700 // Can we combine the two pointer arithmetics offsets? 701 if (EndsWithSequential) { 702 // Replace: gep (gep %P, long B), long A, ... 703 // With: T = long A+B; gep %P, T, ... 704 // 705 Value *Sum; 706 Value *SO1 = Src->getOperand(Src->getNumOperands()-1); 707 Value *GO1 = GEP.getOperand(1); 708 if (SO1 == Constant::getNullValue(SO1->getType())) { 709 Sum = GO1; 710 } else if (GO1 == Constant::getNullValue(GO1->getType())) { 711 Sum = SO1; 712 } else { 713 // If they aren't the same type, then the input hasn't been processed 714 // by the loop above yet (which canonicalizes sequential index types to 715 // intptr_t). Just avoid transforming this until the input has been 716 // normalized. 717 if (SO1->getType() != GO1->getType()) 718 return 0; 719 Sum = Builder->CreateAdd(SO1, GO1, PtrOp->getName()+".sum"); 720 } 721 722 // Update the GEP in place if possible. 723 if (Src->getNumOperands() == 2) { 724 GEP.setOperand(0, Src->getOperand(0)); 725 GEP.setOperand(1, Sum); 726 return &GEP; 727 } 728 Indices.append(Src->op_begin()+1, Src->op_end()-1); 729 Indices.push_back(Sum); 730 Indices.append(GEP.op_begin()+2, GEP.op_end()); 731 } else if (isa<Constant>(*GEP.idx_begin()) && 732 cast<Constant>(*GEP.idx_begin())->isNullValue() && 733 Src->getNumOperands() != 1) { 734 // Otherwise we can do the fold if the first index of the GEP is a zero 735 Indices.append(Src->op_begin()+1, Src->op_end()); 736 Indices.append(GEP.idx_begin()+1, GEP.idx_end()); 737 } 738 739 if (!Indices.empty()) 740 return (GEP.isInBounds() && Src->isInBounds()) ? 741 GetElementPtrInst::CreateInBounds(Src->getOperand(0), Indices.begin(), 742 Indices.end(), GEP.getName()) : 743 GetElementPtrInst::Create(Src->getOperand(0), Indices.begin(), 744 Indices.end(), GEP.getName()); 745 } 746 747 // Handle gep(bitcast x) and gep(gep x, 0, 0, 0). 748 Value *StrippedPtr = PtrOp->stripPointerCasts(); 749 if (StrippedPtr != PtrOp) { 750 const PointerType *StrippedPtrTy =cast<PointerType>(StrippedPtr->getType()); 751 752 bool HasZeroPointerIndex = false; 753 if (ConstantInt *C = dyn_cast<ConstantInt>(GEP.getOperand(1))) 754 HasZeroPointerIndex = C->isZero(); 755 756 // Transform: GEP (bitcast [10 x i8]* X to [0 x i8]*), i32 0, ... 757 // into : GEP [10 x i8]* X, i32 0, ... 758 // 759 // Likewise, transform: GEP (bitcast i8* X to [0 x i8]*), i32 0, ... 760 // into : GEP i8* X, ... 761 // 762 // This occurs when the program declares an array extern like "int X[];" 763 if (HasZeroPointerIndex) { 764 const PointerType *CPTy = cast<PointerType>(PtrOp->getType()); 765 if (const ArrayType *CATy = 766 dyn_cast<ArrayType>(CPTy->getElementType())) { 767 // GEP (bitcast i8* X to [0 x i8]*), i32 0, ... ? 768 if (CATy->getElementType() == StrippedPtrTy->getElementType()) { 769 // -> GEP i8* X, ... 770 SmallVector<Value*, 8> Idx(GEP.idx_begin()+1, GEP.idx_end()); 771 GetElementPtrInst *Res = 772 GetElementPtrInst::Create(StrippedPtr, Idx.begin(), 773 Idx.end(), GEP.getName()); 774 Res->setIsInBounds(GEP.isInBounds()); 775 return Res; 776 } 777 778 if (const ArrayType *XATy = 779 dyn_cast<ArrayType>(StrippedPtrTy->getElementType())){ 780 // GEP (bitcast [10 x i8]* X to [0 x i8]*), i32 0, ... ? 781 if (CATy->getElementType() == XATy->getElementType()) { 782 // -> GEP [10 x i8]* X, i32 0, ... 783 // At this point, we know that the cast source type is a pointer 784 // to an array of the same type as the destination pointer 785 // array. Because the array type is never stepped over (there 786 // is a leading zero) we can fold the cast into this GEP. 787 GEP.setOperand(0, StrippedPtr); 788 return &GEP; 789 } 790 } 791 } 792 } else if (GEP.getNumOperands() == 2) { 793 // Transform things like: 794 // %t = getelementptr i32* bitcast ([2 x i32]* %str to i32*), i32 %V 795 // into: %t1 = getelementptr [2 x i32]* %str, i32 0, i32 %V; bitcast 796 const Type *SrcElTy = StrippedPtrTy->getElementType(); 797 const Type *ResElTy=cast<PointerType>(PtrOp->getType())->getElementType(); 798 if (TD && SrcElTy->isArrayTy() && 799 TD->getTypeAllocSize(cast<ArrayType>(SrcElTy)->getElementType()) == 800 TD->getTypeAllocSize(ResElTy)) { 801 Value *Idx[2]; 802 Idx[0] = Constant::getNullValue(Type::getInt32Ty(GEP.getContext())); 803 Idx[1] = GEP.getOperand(1); 804 Value *NewGEP = GEP.isInBounds() ? 805 Builder->CreateInBoundsGEP(StrippedPtr, Idx, Idx + 2, GEP.getName()) : 806 Builder->CreateGEP(StrippedPtr, Idx, Idx + 2, GEP.getName()); 807 // V and GEP are both pointer types --> BitCast 808 return new BitCastInst(NewGEP, GEP.getType()); 809 } 810 811 // Transform things like: 812 // getelementptr i8* bitcast ([100 x double]* X to i8*), i32 %tmp 813 // (where tmp = 8*tmp2) into: 814 // getelementptr [100 x double]* %arr, i32 0, i32 %tmp2; bitcast 815 816 if (TD && SrcElTy->isArrayTy() && ResElTy->isIntegerTy(8)) { 817 uint64_t ArrayEltSize = 818 TD->getTypeAllocSize(cast<ArrayType>(SrcElTy)->getElementType()); 819 820 // Check to see if "tmp" is a scale by a multiple of ArrayEltSize. We 821 // allow either a mul, shift, or constant here. 822 Value *NewIdx = 0; 823 ConstantInt *Scale = 0; 824 if (ArrayEltSize == 1) { 825 NewIdx = GEP.getOperand(1); 826 Scale = ConstantInt::get(cast<IntegerType>(NewIdx->getType()), 1); 827 } else if (ConstantInt *CI = dyn_cast<ConstantInt>(GEP.getOperand(1))) { 828 NewIdx = ConstantInt::get(CI->getType(), 1); 829 Scale = CI; 830 } else if (Instruction *Inst =dyn_cast<Instruction>(GEP.getOperand(1))){ 831 if (Inst->getOpcode() == Instruction::Shl && 832 isa<ConstantInt>(Inst->getOperand(1))) { 833 ConstantInt *ShAmt = cast<ConstantInt>(Inst->getOperand(1)); 834 uint32_t ShAmtVal = ShAmt->getLimitedValue(64); 835 Scale = ConstantInt::get(cast<IntegerType>(Inst->getType()), 836 1ULL << ShAmtVal); 837 NewIdx = Inst->getOperand(0); 838 } else if (Inst->getOpcode() == Instruction::Mul && 839 isa<ConstantInt>(Inst->getOperand(1))) { 840 Scale = cast<ConstantInt>(Inst->getOperand(1)); 841 NewIdx = Inst->getOperand(0); 842 } 843 } 844 845 // If the index will be to exactly the right offset with the scale taken 846 // out, perform the transformation. Note, we don't know whether Scale is 847 // signed or not. We'll use unsigned version of division/modulo 848 // operation after making sure Scale doesn't have the sign bit set. 849 if (ArrayEltSize && Scale && Scale->getSExtValue() >= 0LL && 850 Scale->getZExtValue() % ArrayEltSize == 0) { 851 Scale = ConstantInt::get(Scale->getType(), 852 Scale->getZExtValue() / ArrayEltSize); 853 if (Scale->getZExtValue() != 1) { 854 Constant *C = ConstantExpr::getIntegerCast(Scale, NewIdx->getType(), 855 false /*ZExt*/); 856 NewIdx = Builder->CreateMul(NewIdx, C, "idxscale"); 857 } 858 859 // Insert the new GEP instruction. 860 Value *Idx[2]; 861 Idx[0] = Constant::getNullValue(Type::getInt32Ty(GEP.getContext())); 862 Idx[1] = NewIdx; 863 Value *NewGEP = GEP.isInBounds() ? 864 Builder->CreateInBoundsGEP(StrippedPtr, Idx, Idx + 2,GEP.getName()): 865 Builder->CreateGEP(StrippedPtr, Idx, Idx + 2, GEP.getName()); 866 // The NewGEP must be pointer typed, so must the old one -> BitCast 867 return new BitCastInst(NewGEP, GEP.getType()); 868 } 869 } 870 } 871 } 872 873 /// See if we can simplify: 874 /// X = bitcast A* to B* 875 /// Y = gep X, <...constant indices...> 876 /// into a gep of the original struct. This is important for SROA and alias 877 /// analysis of unions. If "A" is also a bitcast, wait for A/X to be merged. 878 if (BitCastInst *BCI = dyn_cast<BitCastInst>(PtrOp)) { 879 if (TD && 880 !isa<BitCastInst>(BCI->getOperand(0)) && GEP.hasAllConstantIndices()) { 881 // Determine how much the GEP moves the pointer. We are guaranteed to get 882 // a constant back from EmitGEPOffset. 883 ConstantInt *OffsetV = cast<ConstantInt>(EmitGEPOffset(&GEP)); 884 int64_t Offset = OffsetV->getSExtValue(); 885 886 // If this GEP instruction doesn't move the pointer, just replace the GEP 887 // with a bitcast of the real input to the dest type. 888 if (Offset == 0) { 889 // If the bitcast is of an allocation, and the allocation will be 890 // converted to match the type of the cast, don't touch this. 891 if (isa<AllocaInst>(BCI->getOperand(0)) || 892 isMalloc(BCI->getOperand(0))) { 893 // See if the bitcast simplifies, if so, don't nuke this GEP yet. 894 if (Instruction *I = visitBitCast(*BCI)) { 895 if (I != BCI) { 896 I->takeName(BCI); 897 BCI->getParent()->getInstList().insert(BCI, I); 898 ReplaceInstUsesWith(*BCI, I); 899 } 900 return &GEP; 901 } 902 } 903 return new BitCastInst(BCI->getOperand(0), GEP.getType()); 904 } 905 906 // Otherwise, if the offset is non-zero, we need to find out if there is a 907 // field at Offset in 'A's type. If so, we can pull the cast through the 908 // GEP. 909 SmallVector<Value*, 8> NewIndices; 910 const Type *InTy = 911 cast<PointerType>(BCI->getOperand(0)->getType())->getElementType(); 912 if (FindElementAtOffset(InTy, Offset, NewIndices)) { 913 Value *NGEP = GEP.isInBounds() ? 914 Builder->CreateInBoundsGEP(BCI->getOperand(0), NewIndices.begin(), 915 NewIndices.end()) : 916 Builder->CreateGEP(BCI->getOperand(0), NewIndices.begin(), 917 NewIndices.end()); 918 919 if (NGEP->getType() == GEP.getType()) 920 return ReplaceInstUsesWith(GEP, NGEP); 921 NGEP->takeName(&GEP); 922 return new BitCastInst(NGEP, GEP.getType()); 923 } 924 } 925 } 926 927 return 0; 928} 929 930 931 932static bool IsOnlyNullComparedAndFreed(const Value &V) { 933 for (Value::const_use_iterator UI = V.use_begin(), UE = V.use_end(); 934 UI != UE; ++UI) { 935 const User *U = *UI; 936 if (isFreeCall(U)) 937 continue; 938 if (const ICmpInst *ICI = dyn_cast<ICmpInst>(U)) 939 if (ICI->isEquality() && isa<ConstantPointerNull>(ICI->getOperand(1))) 940 continue; 941 return false; 942 } 943 return true; 944} 945 946Instruction *InstCombiner::visitMalloc(Instruction &MI) { 947 // If we have a malloc call which is only used in any amount of comparisons 948 // to null and free calls, delete the calls and replace the comparisons with 949 // true or false as appropriate. 950 if (IsOnlyNullComparedAndFreed(MI)) { 951 for (Value::use_iterator UI = MI.use_begin(), UE = MI.use_end(); 952 UI != UE;) { 953 // We can assume that every remaining use is a free call or an icmp eq/ne 954 // to null, so the cast is safe. 955 Instruction *I = cast<Instruction>(*UI); 956 957 // Early increment here, as we're about to get rid of the user. 958 ++UI; 959 960 if (isFreeCall(I)) { 961 EraseInstFromFunction(*cast<CallInst>(I)); 962 continue; 963 } 964 // Again, the cast is safe. 965 ICmpInst *C = cast<ICmpInst>(I); 966 ReplaceInstUsesWith(*C, ConstantInt::get(Type::getInt1Ty(C->getContext()), 967 C->isFalseWhenEqual())); 968 EraseInstFromFunction(*C); 969 } 970 return EraseInstFromFunction(MI); 971 } 972 return 0; 973} 974 975 976 977Instruction *InstCombiner::visitFree(CallInst &FI) { 978 Value *Op = FI.getArgOperand(0); 979 980 // free undef -> unreachable. 981 if (isa<UndefValue>(Op)) { 982 // Insert a new store to null because we cannot modify the CFG here. 983 new StoreInst(ConstantInt::getTrue(FI.getContext()), 984 UndefValue::get(Type::getInt1PtrTy(FI.getContext())), &FI); 985 return EraseInstFromFunction(FI); 986 } 987 988 // If we have 'free null' delete the instruction. This can happen in stl code 989 // when lots of inlining happens. 990 if (isa<ConstantPointerNull>(Op)) 991 return EraseInstFromFunction(FI); 992 993 return 0; 994} 995 996 997 998Instruction *InstCombiner::visitBranchInst(BranchInst &BI) { 999 // Change br (not X), label True, label False to: br X, label False, True 1000 Value *X = 0; 1001 BasicBlock *TrueDest; 1002 BasicBlock *FalseDest; 1003 if (match(&BI, m_Br(m_Not(m_Value(X)), TrueDest, FalseDest)) && 1004 !isa<Constant>(X)) { 1005 // Swap Destinations and condition... 1006 BI.setCondition(X); 1007 BI.setSuccessor(0, FalseDest); 1008 BI.setSuccessor(1, TrueDest); 1009 return &BI; 1010 } 1011 1012 // Cannonicalize fcmp_one -> fcmp_oeq 1013 FCmpInst::Predicate FPred; Value *Y; 1014 if (match(&BI, m_Br(m_FCmp(FPred, m_Value(X), m_Value(Y)), 1015 TrueDest, FalseDest)) && 1016 BI.getCondition()->hasOneUse()) 1017 if (FPred == FCmpInst::FCMP_ONE || FPred == FCmpInst::FCMP_OLE || 1018 FPred == FCmpInst::FCMP_OGE) { 1019 FCmpInst *Cond = cast<FCmpInst>(BI.getCondition()); 1020 Cond->setPredicate(FCmpInst::getInversePredicate(FPred)); 1021 1022 // Swap Destinations and condition. 1023 BI.setSuccessor(0, FalseDest); 1024 BI.setSuccessor(1, TrueDest); 1025 Worklist.Add(Cond); 1026 return &BI; 1027 } 1028 1029 // Cannonicalize icmp_ne -> icmp_eq 1030 ICmpInst::Predicate IPred; 1031 if (match(&BI, m_Br(m_ICmp(IPred, m_Value(X), m_Value(Y)), 1032 TrueDest, FalseDest)) && 1033 BI.getCondition()->hasOneUse()) 1034 if (IPred == ICmpInst::ICMP_NE || IPred == ICmpInst::ICMP_ULE || 1035 IPred == ICmpInst::ICMP_SLE || IPred == ICmpInst::ICMP_UGE || 1036 IPred == ICmpInst::ICMP_SGE) { 1037 ICmpInst *Cond = cast<ICmpInst>(BI.getCondition()); 1038 Cond->setPredicate(ICmpInst::getInversePredicate(IPred)); 1039 // Swap Destinations and condition. 1040 BI.setSuccessor(0, FalseDest); 1041 BI.setSuccessor(1, TrueDest); 1042 Worklist.Add(Cond); 1043 return &BI; 1044 } 1045 1046 return 0; 1047} 1048 1049Instruction *InstCombiner::visitSwitchInst(SwitchInst &SI) { 1050 Value *Cond = SI.getCondition(); 1051 if (Instruction *I = dyn_cast<Instruction>(Cond)) { 1052 if (I->getOpcode() == Instruction::Add) 1053 if (ConstantInt *AddRHS = dyn_cast<ConstantInt>(I->getOperand(1))) { 1054 // change 'switch (X+4) case 1:' into 'switch (X) case -3' 1055 for (unsigned i = 2, e = SI.getNumOperands(); i != e; i += 2) 1056 SI.setOperand(i, 1057 ConstantExpr::getSub(cast<Constant>(SI.getOperand(i)), 1058 AddRHS)); 1059 SI.setOperand(0, I->getOperand(0)); 1060 Worklist.Add(I); 1061 return &SI; 1062 } 1063 } 1064 return 0; 1065} 1066 1067Instruction *InstCombiner::visitExtractValueInst(ExtractValueInst &EV) { 1068 Value *Agg = EV.getAggregateOperand(); 1069 1070 if (!EV.hasIndices()) 1071 return ReplaceInstUsesWith(EV, Agg); 1072 1073 if (Constant *C = dyn_cast<Constant>(Agg)) { 1074 if (isa<UndefValue>(C)) 1075 return ReplaceInstUsesWith(EV, UndefValue::get(EV.getType())); 1076 1077 if (isa<ConstantAggregateZero>(C)) 1078 return ReplaceInstUsesWith(EV, Constant::getNullValue(EV.getType())); 1079 1080 if (isa<ConstantArray>(C) || isa<ConstantStruct>(C)) { 1081 // Extract the element indexed by the first index out of the constant 1082 Value *V = C->getOperand(*EV.idx_begin()); 1083 if (EV.getNumIndices() > 1) 1084 // Extract the remaining indices out of the constant indexed by the 1085 // first index 1086 return ExtractValueInst::Create(V, EV.idx_begin() + 1, EV.idx_end()); 1087 else 1088 return ReplaceInstUsesWith(EV, V); 1089 } 1090 return 0; // Can't handle other constants 1091 } 1092 if (InsertValueInst *IV = dyn_cast<InsertValueInst>(Agg)) { 1093 // We're extracting from an insertvalue instruction, compare the indices 1094 const unsigned *exti, *exte, *insi, *inse; 1095 for (exti = EV.idx_begin(), insi = IV->idx_begin(), 1096 exte = EV.idx_end(), inse = IV->idx_end(); 1097 exti != exte && insi != inse; 1098 ++exti, ++insi) { 1099 if (*insi != *exti) 1100 // The insert and extract both reference distinctly different elements. 1101 // This means the extract is not influenced by the insert, and we can 1102 // replace the aggregate operand of the extract with the aggregate 1103 // operand of the insert. i.e., replace 1104 // %I = insertvalue { i32, { i32 } } %A, { i32 } { i32 42 }, 1 1105 // %E = extractvalue { i32, { i32 } } %I, 0 1106 // with 1107 // %E = extractvalue { i32, { i32 } } %A, 0 1108 return ExtractValueInst::Create(IV->getAggregateOperand(), 1109 EV.idx_begin(), EV.idx_end()); 1110 } 1111 if (exti == exte && insi == inse) 1112 // Both iterators are at the end: Index lists are identical. Replace 1113 // %B = insertvalue { i32, { i32 } } %A, i32 42, 1, 0 1114 // %C = extractvalue { i32, { i32 } } %B, 1, 0 1115 // with "i32 42" 1116 return ReplaceInstUsesWith(EV, IV->getInsertedValueOperand()); 1117 if (exti == exte) { 1118 // The extract list is a prefix of the insert list. i.e. replace 1119 // %I = insertvalue { i32, { i32 } } %A, i32 42, 1, 0 1120 // %E = extractvalue { i32, { i32 } } %I, 1 1121 // with 1122 // %X = extractvalue { i32, { i32 } } %A, 1 1123 // %E = insertvalue { i32 } %X, i32 42, 0 1124 // by switching the order of the insert and extract (though the 1125 // insertvalue should be left in, since it may have other uses). 1126 Value *NewEV = Builder->CreateExtractValue(IV->getAggregateOperand(), 1127 EV.idx_begin(), EV.idx_end()); 1128 return InsertValueInst::Create(NewEV, IV->getInsertedValueOperand(), 1129 insi, inse); 1130 } 1131 if (insi == inse) 1132 // The insert list is a prefix of the extract list 1133 // We can simply remove the common indices from the extract and make it 1134 // operate on the inserted value instead of the insertvalue result. 1135 // i.e., replace 1136 // %I = insertvalue { i32, { i32 } } %A, { i32 } { i32 42 }, 1 1137 // %E = extractvalue { i32, { i32 } } %I, 1, 0 1138 // with 1139 // %E extractvalue { i32 } { i32 42 }, 0 1140 return ExtractValueInst::Create(IV->getInsertedValueOperand(), 1141 exti, exte); 1142 } 1143 if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(Agg)) { 1144 // We're extracting from an intrinsic, see if we're the only user, which 1145 // allows us to simplify multiple result intrinsics to simpler things that 1146 // just get one value. 1147 if (II->hasOneUse()) { 1148 // Check if we're grabbing the overflow bit or the result of a 'with 1149 // overflow' intrinsic. If it's the latter we can remove the intrinsic 1150 // and replace it with a traditional binary instruction. 1151 switch (II->getIntrinsicID()) { 1152 case Intrinsic::uadd_with_overflow: 1153 case Intrinsic::sadd_with_overflow: 1154 if (*EV.idx_begin() == 0) { // Normal result. 1155 Value *LHS = II->getArgOperand(0), *RHS = II->getArgOperand(1); 1156 II->replaceAllUsesWith(UndefValue::get(II->getType())); 1157 EraseInstFromFunction(*II); 1158 return BinaryOperator::CreateAdd(LHS, RHS); 1159 } 1160 1161 // If the normal result of the add is dead, and the RHS is a constant, 1162 // we can transform this into a range comparison. 1163 // overflow = uadd a, -4 --> overflow = icmp ugt a, 3 1164 if (II->getIntrinsicID() == Intrinsic::uadd_with_overflow) 1165 if (ConstantInt *CI = dyn_cast<ConstantInt>(II->getArgOperand(1))) 1166 return new ICmpInst(ICmpInst::ICMP_UGT, II->getArgOperand(0), 1167 ConstantExpr::getNot(CI)); 1168 break; 1169 case Intrinsic::usub_with_overflow: 1170 case Intrinsic::ssub_with_overflow: 1171 if (*EV.idx_begin() == 0) { // Normal result. 1172 Value *LHS = II->getArgOperand(0), *RHS = II->getArgOperand(1); 1173 II->replaceAllUsesWith(UndefValue::get(II->getType())); 1174 EraseInstFromFunction(*II); 1175 return BinaryOperator::CreateSub(LHS, RHS); 1176 } 1177 break; 1178 case Intrinsic::umul_with_overflow: 1179 case Intrinsic::smul_with_overflow: 1180 if (*EV.idx_begin() == 0) { // Normal result. 1181 Value *LHS = II->getArgOperand(0), *RHS = II->getArgOperand(1); 1182 II->replaceAllUsesWith(UndefValue::get(II->getType())); 1183 EraseInstFromFunction(*II); 1184 return BinaryOperator::CreateMul(LHS, RHS); 1185 } 1186 break; 1187 default: 1188 break; 1189 } 1190 } 1191 } 1192 if (LoadInst *L = dyn_cast<LoadInst>(Agg)) 1193 // If the (non-volatile) load only has one use, we can rewrite this to a 1194 // load from a GEP. This reduces the size of the load. 1195 // FIXME: If a load is used only by extractvalue instructions then this 1196 // could be done regardless of having multiple uses. 1197 if (!L->isVolatile() && L->hasOneUse()) { 1198 // extractvalue has integer indices, getelementptr has Value*s. Convert. 1199 SmallVector<Value*, 4> Indices; 1200 // Prefix an i32 0 since we need the first element. 1201 Indices.push_back(Builder->getInt32(0)); 1202 for (ExtractValueInst::idx_iterator I = EV.idx_begin(), E = EV.idx_end(); 1203 I != E; ++I) 1204 Indices.push_back(Builder->getInt32(*I)); 1205 1206 // We need to insert these at the location of the old load, not at that of 1207 // the extractvalue. 1208 Builder->SetInsertPoint(L->getParent(), L); 1209 Value *GEP = Builder->CreateInBoundsGEP(L->getPointerOperand(), 1210 Indices.begin(), Indices.end()); 1211 // Returning the load directly will cause the main loop to insert it in 1212 // the wrong spot, so use ReplaceInstUsesWith(). 1213 return ReplaceInstUsesWith(EV, Builder->CreateLoad(GEP)); 1214 } 1215 // We could simplify extracts from other values. Note that nested extracts may 1216 // already be simplified implicitly by the above: extract (extract (insert) ) 1217 // will be translated into extract ( insert ( extract ) ) first and then just 1218 // the value inserted, if appropriate. Similarly for extracts from single-use 1219 // loads: extract (extract (load)) will be translated to extract (load (gep)) 1220 // and if again single-use then via load (gep (gep)) to load (gep). 1221 // However, double extracts from e.g. function arguments or return values 1222 // aren't handled yet. 1223 return 0; 1224} 1225 1226 1227 1228 1229/// TryToSinkInstruction - Try to move the specified instruction from its 1230/// current block into the beginning of DestBlock, which can only happen if it's 1231/// safe to move the instruction past all of the instructions between it and the 1232/// end of its block. 1233static bool TryToSinkInstruction(Instruction *I, BasicBlock *DestBlock) { 1234 assert(I->hasOneUse() && "Invariants didn't hold!"); 1235 1236 // Cannot move control-flow-involving, volatile loads, vaarg, etc. 1237 if (isa<PHINode>(I) || I->mayHaveSideEffects() || isa<TerminatorInst>(I)) 1238 return false; 1239 1240 // Do not sink alloca instructions out of the entry block. 1241 if (isa<AllocaInst>(I) && I->getParent() == 1242 &DestBlock->getParent()->getEntryBlock()) 1243 return false; 1244 1245 // We can only sink load instructions if there is nothing between the load and 1246 // the end of block that could change the value. 1247 if (I->mayReadFromMemory()) { 1248 for (BasicBlock::iterator Scan = I, E = I->getParent()->end(); 1249 Scan != E; ++Scan) 1250 if (Scan->mayWriteToMemory()) 1251 return false; 1252 } 1253 1254 BasicBlock::iterator InsertPos = DestBlock->getFirstNonPHI(); 1255 1256 I->moveBefore(InsertPos); 1257 ++NumSunkInst; 1258 return true; 1259} 1260 1261 1262/// AddReachableCodeToWorklist - Walk the function in depth-first order, adding 1263/// all reachable code to the worklist. 1264/// 1265/// This has a couple of tricks to make the code faster and more powerful. In 1266/// particular, we constant fold and DCE instructions as we go, to avoid adding 1267/// them to the worklist (this significantly speeds up instcombine on code where 1268/// many instructions are dead or constant). Additionally, if we find a branch 1269/// whose condition is a known constant, we only visit the reachable successors. 1270/// 1271static bool AddReachableCodeToWorklist(BasicBlock *BB, 1272 SmallPtrSet<BasicBlock*, 64> &Visited, 1273 InstCombiner &IC, 1274 const TargetData *TD) { 1275 bool MadeIRChange = false; 1276 SmallVector<BasicBlock*, 256> Worklist; 1277 Worklist.push_back(BB); 1278 1279 SmallVector<Instruction*, 128> InstrsForInstCombineWorklist; 1280 SmallPtrSet<ConstantExpr*, 64> FoldedConstants; 1281 1282 do { 1283 BB = Worklist.pop_back_val(); 1284 1285 // We have now visited this block! If we've already been here, ignore it. 1286 if (!Visited.insert(BB)) continue; 1287 1288 for (BasicBlock::iterator BBI = BB->begin(), E = BB->end(); BBI != E; ) { 1289 Instruction *Inst = BBI++; 1290 1291 // DCE instruction if trivially dead. 1292 if (isInstructionTriviallyDead(Inst)) { 1293 ++NumDeadInst; 1294 DEBUG(errs() << "IC: DCE: " << *Inst << '\n'); 1295 Inst->eraseFromParent(); 1296 continue; 1297 } 1298 1299 // ConstantProp instruction if trivially constant. 1300 if (!Inst->use_empty() && isa<Constant>(Inst->getOperand(0))) 1301 if (Constant *C = ConstantFoldInstruction(Inst, TD)) { 1302 DEBUG(errs() << "IC: ConstFold to: " << *C << " from: " 1303 << *Inst << '\n'); 1304 Inst->replaceAllUsesWith(C); 1305 ++NumConstProp; 1306 Inst->eraseFromParent(); 1307 continue; 1308 } 1309 1310 if (TD) { 1311 // See if we can constant fold its operands. 1312 for (User::op_iterator i = Inst->op_begin(), e = Inst->op_end(); 1313 i != e; ++i) { 1314 ConstantExpr *CE = dyn_cast<ConstantExpr>(i); 1315 if (CE == 0) continue; 1316 1317 // If we already folded this constant, don't try again. 1318 if (!FoldedConstants.insert(CE)) 1319 continue; 1320 1321 Constant *NewC = ConstantFoldConstantExpression(CE, TD); 1322 if (NewC && NewC != CE) { 1323 *i = NewC; 1324 MadeIRChange = true; 1325 } 1326 } 1327 } 1328 1329 InstrsForInstCombineWorklist.push_back(Inst); 1330 } 1331 1332 // Recursively visit successors. If this is a branch or switch on a 1333 // constant, only visit the reachable successor. 1334 TerminatorInst *TI = BB->getTerminator(); 1335 if (BranchInst *BI = dyn_cast<BranchInst>(TI)) { 1336 if (BI->isConditional() && isa<ConstantInt>(BI->getCondition())) { 1337 bool CondVal = cast<ConstantInt>(BI->getCondition())->getZExtValue(); 1338 BasicBlock *ReachableBB = BI->getSuccessor(!CondVal); 1339 Worklist.push_back(ReachableBB); 1340 continue; 1341 } 1342 } else if (SwitchInst *SI = dyn_cast<SwitchInst>(TI)) { 1343 if (ConstantInt *Cond = dyn_cast<ConstantInt>(SI->getCondition())) { 1344 // See if this is an explicit destination. 1345 for (unsigned i = 1, e = SI->getNumSuccessors(); i != e; ++i) 1346 if (SI->getCaseValue(i) == Cond) { 1347 BasicBlock *ReachableBB = SI->getSuccessor(i); 1348 Worklist.push_back(ReachableBB); 1349 continue; 1350 } 1351 1352 // Otherwise it is the default destination. 1353 Worklist.push_back(SI->getSuccessor(0)); 1354 continue; 1355 } 1356 } 1357 1358 for (unsigned i = 0, e = TI->getNumSuccessors(); i != e; ++i) 1359 Worklist.push_back(TI->getSuccessor(i)); 1360 } while (!Worklist.empty()); 1361 1362 // Once we've found all of the instructions to add to instcombine's worklist, 1363 // add them in reverse order. This way instcombine will visit from the top 1364 // of the function down. This jives well with the way that it adds all uses 1365 // of instructions to the worklist after doing a transformation, thus avoiding 1366 // some N^2 behavior in pathological cases. 1367 IC.Worklist.AddInitialGroup(&InstrsForInstCombineWorklist[0], 1368 InstrsForInstCombineWorklist.size()); 1369 1370 return MadeIRChange; 1371} 1372 1373bool InstCombiner::DoOneIteration(Function &F, unsigned Iteration) { 1374 MadeIRChange = false; 1375 1376 DEBUG(errs() << "\n\nINSTCOMBINE ITERATION #" << Iteration << " on " 1377 << F.getNameStr() << "\n"); 1378 1379 { 1380 // Do a depth-first traversal of the function, populate the worklist with 1381 // the reachable instructions. Ignore blocks that are not reachable. Keep 1382 // track of which blocks we visit. 1383 SmallPtrSet<BasicBlock*, 64> Visited; 1384 MadeIRChange |= AddReachableCodeToWorklist(F.begin(), Visited, *this, TD); 1385 1386 // Do a quick scan over the function. If we find any blocks that are 1387 // unreachable, remove any instructions inside of them. This prevents 1388 // the instcombine code from having to deal with some bad special cases. 1389 for (Function::iterator BB = F.begin(), E = F.end(); BB != E; ++BB) 1390 if (!Visited.count(BB)) { 1391 Instruction *Term = BB->getTerminator(); 1392 while (Term != BB->begin()) { // Remove instrs bottom-up 1393 BasicBlock::iterator I = Term; --I; 1394 1395 DEBUG(errs() << "IC: DCE: " << *I << '\n'); 1396 // A debug intrinsic shouldn't force another iteration if we weren't 1397 // going to do one without it. 1398 if (!isa<DbgInfoIntrinsic>(I)) { 1399 ++NumDeadInst; 1400 MadeIRChange = true; 1401 } 1402 1403 // If I is not void type then replaceAllUsesWith undef. 1404 // This allows ValueHandlers and custom metadata to adjust itself. 1405 if (!I->getType()->isVoidTy()) 1406 I->replaceAllUsesWith(UndefValue::get(I->getType())); 1407 I->eraseFromParent(); 1408 } 1409 } 1410 } 1411 1412 while (!Worklist.isEmpty()) { 1413 Instruction *I = Worklist.RemoveOne(); 1414 if (I == 0) continue; // skip null values. 1415 1416 // Check to see if we can DCE the instruction. 1417 if (isInstructionTriviallyDead(I)) { 1418 DEBUG(errs() << "IC: DCE: " << *I << '\n'); 1419 EraseInstFromFunction(*I); 1420 ++NumDeadInst; 1421 MadeIRChange = true; 1422 continue; 1423 } 1424 1425 // Instruction isn't dead, see if we can constant propagate it. 1426 if (!I->use_empty() && isa<Constant>(I->getOperand(0))) 1427 if (Constant *C = ConstantFoldInstruction(I, TD)) { 1428 DEBUG(errs() << "IC: ConstFold to: " << *C << " from: " << *I << '\n'); 1429 1430 // Add operands to the worklist. 1431 ReplaceInstUsesWith(*I, C); 1432 ++NumConstProp; 1433 EraseInstFromFunction(*I); 1434 MadeIRChange = true; 1435 continue; 1436 } 1437 1438 // See if we can trivially sink this instruction to a successor basic block. 1439 if (I->hasOneUse()) { 1440 BasicBlock *BB = I->getParent(); 1441 Instruction *UserInst = cast<Instruction>(I->use_back()); 1442 BasicBlock *UserParent; 1443 1444 // Get the block the use occurs in. 1445 if (PHINode *PN = dyn_cast<PHINode>(UserInst)) 1446 UserParent = PN->getIncomingBlock(I->use_begin().getUse()); 1447 else 1448 UserParent = UserInst->getParent(); 1449 1450 if (UserParent != BB) { 1451 bool UserIsSuccessor = false; 1452 // See if the user is one of our successors. 1453 for (succ_iterator SI = succ_begin(BB), E = succ_end(BB); SI != E; ++SI) 1454 if (*SI == UserParent) { 1455 UserIsSuccessor = true; 1456 break; 1457 } 1458 1459 // If the user is one of our immediate successors, and if that successor 1460 // only has us as a predecessors (we'd have to split the critical edge 1461 // otherwise), we can keep going. 1462 if (UserIsSuccessor && UserParent->getSinglePredecessor()) 1463 // Okay, the CFG is simple enough, try to sink this instruction. 1464 MadeIRChange |= TryToSinkInstruction(I, UserParent); 1465 } 1466 } 1467 1468 // Now that we have an instruction, try combining it to simplify it. 1469 Builder->SetInsertPoint(I->getParent(), I); 1470 1471#ifndef NDEBUG 1472 std::string OrigI; 1473#endif 1474 DEBUG(raw_string_ostream SS(OrigI); I->print(SS); OrigI = SS.str();); 1475 DEBUG(errs() << "IC: Visiting: " << OrigI << '\n'); 1476 1477 if (Instruction *Result = visit(*I)) { 1478 ++NumCombined; 1479 // Should we replace the old instruction with a new one? 1480 if (Result != I) { 1481 DEBUG(errs() << "IC: Old = " << *I << '\n' 1482 << " New = " << *Result << '\n'); 1483 1484 // Everything uses the new instruction now. 1485 I->replaceAllUsesWith(Result); 1486 1487 // Push the new instruction and any users onto the worklist. 1488 Worklist.Add(Result); 1489 Worklist.AddUsersToWorkList(*Result); 1490 1491 // Move the name to the new instruction first. 1492 Result->takeName(I); 1493 1494 // Insert the new instruction into the basic block... 1495 BasicBlock *InstParent = I->getParent(); 1496 BasicBlock::iterator InsertPos = I; 1497 1498 if (!isa<PHINode>(Result)) // If combining a PHI, don't insert 1499 while (isa<PHINode>(InsertPos)) // middle of a block of PHIs. 1500 ++InsertPos; 1501 1502 InstParent->getInstList().insert(InsertPos, Result); 1503 1504 EraseInstFromFunction(*I); 1505 } else { 1506#ifndef NDEBUG 1507 DEBUG(errs() << "IC: Mod = " << OrigI << '\n' 1508 << " New = " << *I << '\n'); 1509#endif 1510 1511 // If the instruction was modified, it's possible that it is now dead. 1512 // if so, remove it. 1513 if (isInstructionTriviallyDead(I)) { 1514 EraseInstFromFunction(*I); 1515 } else { 1516 Worklist.Add(I); 1517 Worklist.AddUsersToWorkList(*I); 1518 } 1519 } 1520 MadeIRChange = true; 1521 } 1522 } 1523 1524 Worklist.Zap(); 1525 return MadeIRChange; 1526} 1527 1528 1529bool InstCombiner::runOnFunction(Function &F) { 1530 MustPreserveLCSSA = mustPreserveAnalysisID(LCSSAID); 1531 TD = getAnalysisIfAvailable<TargetData>(); 1532 1533 1534 /// Builder - This is an IRBuilder that automatically inserts new 1535 /// instructions into the worklist when they are created. 1536 IRBuilder<true, TargetFolder, InstCombineIRInserter> 1537 TheBuilder(F.getContext(), TargetFolder(TD), 1538 InstCombineIRInserter(Worklist)); 1539 Builder = &TheBuilder; 1540 1541 bool EverMadeChange = false; 1542 1543 // Iterate while there is work to do. 1544 unsigned Iteration = 0; 1545 while (DoOneIteration(F, Iteration++)) 1546 EverMadeChange = true; 1547 1548 Builder = 0; 1549 return EverMadeChange; 1550} 1551 1552FunctionPass *llvm::createInstructionCombiningPass() { 1553 return new InstCombiner(); 1554} 1555