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