LLVM  mainline
InstCombinePHI.cpp
Go to the documentation of this file.
00001 //===- InstCombinePHI.cpp -------------------------------------------------===//
00002 //
00003 //                     The LLVM Compiler Infrastructure
00004 //
00005 // This file is distributed under the University of Illinois Open Source
00006 // License. See LICENSE.TXT for details.
00007 //
00008 //===----------------------------------------------------------------------===//
00009 //
00010 // This file implements the visitPHINode function.
00011 //
00012 //===----------------------------------------------------------------------===//
00013 
00014 #include "InstCombineInternal.h"
00015 #include "llvm/ADT/STLExtras.h"
00016 #include "llvm/ADT/SmallPtrSet.h"
00017 #include "llvm/Analysis/InstructionSimplify.h"
00018 using namespace llvm;
00019 
00020 #define DEBUG_TYPE "instcombine"
00021 
00022 /// FoldPHIArgBinOpIntoPHI - If we have something like phi [add (a,b), add(a,c)]
00023 /// and if a/b/c and the add's all have a single use, turn this into a phi
00024 /// and a single binop.
00025 Instruction *InstCombiner::FoldPHIArgBinOpIntoPHI(PHINode &PN) {
00026   Instruction *FirstInst = cast<Instruction>(PN.getIncomingValue(0));
00027   assert(isa<BinaryOperator>(FirstInst) || isa<CmpInst>(FirstInst));
00028   unsigned Opc = FirstInst->getOpcode();
00029   Value *LHSVal = FirstInst->getOperand(0);
00030   Value *RHSVal = FirstInst->getOperand(1);
00031 
00032   Type *LHSType = LHSVal->getType();
00033   Type *RHSType = RHSVal->getType();
00034 
00035   bool isNUW = false, isNSW = false, isExact = false;
00036   if (OverflowingBinaryOperator *BO =
00037         dyn_cast<OverflowingBinaryOperator>(FirstInst)) {
00038     isNUW = BO->hasNoUnsignedWrap();
00039     isNSW = BO->hasNoSignedWrap();
00040   } else if (PossiblyExactOperator *PEO =
00041                dyn_cast<PossiblyExactOperator>(FirstInst))
00042     isExact = PEO->isExact();
00043 
00044   // Scan to see if all operands are the same opcode, and all have one use.
00045   for (unsigned i = 1; i != PN.getNumIncomingValues(); ++i) {
00046     Instruction *I = dyn_cast<Instruction>(PN.getIncomingValue(i));
00047     if (!I || I->getOpcode() != Opc || !I->hasOneUse() ||
00048         // Verify type of the LHS matches so we don't fold cmp's of different
00049         // types.
00050         I->getOperand(0)->getType() != LHSType ||
00051         I->getOperand(1)->getType() != RHSType)
00052       return nullptr;
00053 
00054     // If they are CmpInst instructions, check their predicates
00055     if (CmpInst *CI = dyn_cast<CmpInst>(I))
00056       if (CI->getPredicate() != cast<CmpInst>(FirstInst)->getPredicate())
00057         return nullptr;
00058 
00059     if (isNUW)
00060       isNUW = cast<OverflowingBinaryOperator>(I)->hasNoUnsignedWrap();
00061     if (isNSW)
00062       isNSW = cast<OverflowingBinaryOperator>(I)->hasNoSignedWrap();
00063     if (isExact)
00064       isExact = cast<PossiblyExactOperator>(I)->isExact();
00065 
00066     // Keep track of which operand needs a phi node.
00067     if (I->getOperand(0) != LHSVal) LHSVal = nullptr;
00068     if (I->getOperand(1) != RHSVal) RHSVal = nullptr;
00069   }
00070 
00071   // If both LHS and RHS would need a PHI, don't do this transformation,
00072   // because it would increase the number of PHIs entering the block,
00073   // which leads to higher register pressure. This is especially
00074   // bad when the PHIs are in the header of a loop.
00075   if (!LHSVal && !RHSVal)
00076     return nullptr;
00077 
00078   // Otherwise, this is safe to transform!
00079 
00080   Value *InLHS = FirstInst->getOperand(0);
00081   Value *InRHS = FirstInst->getOperand(1);
00082   PHINode *NewLHS = nullptr, *NewRHS = nullptr;
00083   if (!LHSVal) {
00084     NewLHS = PHINode::Create(LHSType, PN.getNumIncomingValues(),
00085                              FirstInst->getOperand(0)->getName() + ".pn");
00086     NewLHS->addIncoming(InLHS, PN.getIncomingBlock(0));
00087     InsertNewInstBefore(NewLHS, PN);
00088     LHSVal = NewLHS;
00089   }
00090 
00091   if (!RHSVal) {
00092     NewRHS = PHINode::Create(RHSType, PN.getNumIncomingValues(),
00093                              FirstInst->getOperand(1)->getName() + ".pn");
00094     NewRHS->addIncoming(InRHS, PN.getIncomingBlock(0));
00095     InsertNewInstBefore(NewRHS, PN);
00096     RHSVal = NewRHS;
00097   }
00098 
00099   // Add all operands to the new PHIs.
00100   if (NewLHS || NewRHS) {
00101     for (unsigned i = 1, e = PN.getNumIncomingValues(); i != e; ++i) {
00102       Instruction *InInst = cast<Instruction>(PN.getIncomingValue(i));
00103       if (NewLHS) {
00104         Value *NewInLHS = InInst->getOperand(0);
00105         NewLHS->addIncoming(NewInLHS, PN.getIncomingBlock(i));
00106       }
00107       if (NewRHS) {
00108         Value *NewInRHS = InInst->getOperand(1);
00109         NewRHS->addIncoming(NewInRHS, PN.getIncomingBlock(i));
00110       }
00111     }
00112   }
00113 
00114   if (CmpInst *CIOp = dyn_cast<CmpInst>(FirstInst)) {
00115     CmpInst *NewCI = CmpInst::Create(CIOp->getOpcode(), CIOp->getPredicate(),
00116                                      LHSVal, RHSVal);
00117     NewCI->setDebugLoc(FirstInst->getDebugLoc());
00118     return NewCI;
00119   }
00120 
00121   BinaryOperator *BinOp = cast<BinaryOperator>(FirstInst);
00122   BinaryOperator *NewBinOp =
00123     BinaryOperator::Create(BinOp->getOpcode(), LHSVal, RHSVal);
00124   if (isNUW) NewBinOp->setHasNoUnsignedWrap();
00125   if (isNSW) NewBinOp->setHasNoSignedWrap();
00126   if (isExact) NewBinOp->setIsExact();
00127   NewBinOp->setDebugLoc(FirstInst->getDebugLoc());
00128   return NewBinOp;
00129 }
00130 
00131 Instruction *InstCombiner::FoldPHIArgGEPIntoPHI(PHINode &PN) {
00132   GetElementPtrInst *FirstInst =cast<GetElementPtrInst>(PN.getIncomingValue(0));
00133 
00134   SmallVector<Value*, 16> FixedOperands(FirstInst->op_begin(),
00135                                         FirstInst->op_end());
00136   // This is true if all GEP bases are allocas and if all indices into them are
00137   // constants.
00138   bool AllBasePointersAreAllocas = true;
00139 
00140   // We don't want to replace this phi if the replacement would require
00141   // more than one phi, which leads to higher register pressure. This is
00142   // especially bad when the PHIs are in the header of a loop.
00143   bool NeededPhi = false;
00144 
00145   bool AllInBounds = true;
00146 
00147   // Scan to see if all operands are the same opcode, and all have one use.
00148   for (unsigned i = 1; i != PN.getNumIncomingValues(); ++i) {
00149     GetElementPtrInst *GEP= dyn_cast<GetElementPtrInst>(PN.getIncomingValue(i));
00150     if (!GEP || !GEP->hasOneUse() || GEP->getType() != FirstInst->getType() ||
00151       GEP->getNumOperands() != FirstInst->getNumOperands())
00152       return nullptr;
00153 
00154     AllInBounds &= GEP->isInBounds();
00155 
00156     // Keep track of whether or not all GEPs are of alloca pointers.
00157     if (AllBasePointersAreAllocas &&
00158         (!isa<AllocaInst>(GEP->getOperand(0)) ||
00159          !GEP->hasAllConstantIndices()))
00160       AllBasePointersAreAllocas = false;
00161 
00162     // Compare the operand lists.
00163     for (unsigned op = 0, e = FirstInst->getNumOperands(); op != e; ++op) {
00164       if (FirstInst->getOperand(op) == GEP->getOperand(op))
00165         continue;
00166 
00167       // Don't merge two GEPs when two operands differ (introducing phi nodes)
00168       // if one of the PHIs has a constant for the index.  The index may be
00169       // substantially cheaper to compute for the constants, so making it a
00170       // variable index could pessimize the path.  This also handles the case
00171       // for struct indices, which must always be constant.
00172       if (isa<ConstantInt>(FirstInst->getOperand(op)) ||
00173           isa<ConstantInt>(GEP->getOperand(op)))
00174         return nullptr;
00175 
00176       if (FirstInst->getOperand(op)->getType() !=GEP->getOperand(op)->getType())
00177         return nullptr;
00178 
00179       // If we already needed a PHI for an earlier operand, and another operand
00180       // also requires a PHI, we'd be introducing more PHIs than we're
00181       // eliminating, which increases register pressure on entry to the PHI's
00182       // block.
00183       if (NeededPhi)
00184         return nullptr;
00185 
00186       FixedOperands[op] = nullptr;  // Needs a PHI.
00187       NeededPhi = true;
00188     }
00189   }
00190 
00191   // If all of the base pointers of the PHI'd GEPs are from allocas, don't
00192   // bother doing this transformation.  At best, this will just save a bit of
00193   // offset calculation, but all the predecessors will have to materialize the
00194   // stack address into a register anyway.  We'd actually rather *clone* the
00195   // load up into the predecessors so that we have a load of a gep of an alloca,
00196   // which can usually all be folded into the load.
00197   if (AllBasePointersAreAllocas)
00198     return nullptr;
00199 
00200   // Otherwise, this is safe to transform.  Insert PHI nodes for each operand
00201   // that is variable.
00202   SmallVector<PHINode*, 16> OperandPhis(FixedOperands.size());
00203 
00204   bool HasAnyPHIs = false;
00205   for (unsigned i = 0, e = FixedOperands.size(); i != e; ++i) {
00206     if (FixedOperands[i]) continue;  // operand doesn't need a phi.
00207     Value *FirstOp = FirstInst->getOperand(i);
00208     PHINode *NewPN = PHINode::Create(FirstOp->getType(), e,
00209                                      FirstOp->getName()+".pn");
00210     InsertNewInstBefore(NewPN, PN);
00211 
00212     NewPN->addIncoming(FirstOp, PN.getIncomingBlock(0));
00213     OperandPhis[i] = NewPN;
00214     FixedOperands[i] = NewPN;
00215     HasAnyPHIs = true;
00216   }
00217 
00218 
00219   // Add all operands to the new PHIs.
00220   if (HasAnyPHIs) {
00221     for (unsigned i = 1, e = PN.getNumIncomingValues(); i != e; ++i) {
00222       GetElementPtrInst *InGEP =cast<GetElementPtrInst>(PN.getIncomingValue(i));
00223       BasicBlock *InBB = PN.getIncomingBlock(i);
00224 
00225       for (unsigned op = 0, e = OperandPhis.size(); op != e; ++op)
00226         if (PHINode *OpPhi = OperandPhis[op])
00227           OpPhi->addIncoming(InGEP->getOperand(op), InBB);
00228     }
00229   }
00230 
00231   Value *Base = FixedOperands[0];
00232   GetElementPtrInst *NewGEP =
00233       GetElementPtrInst::Create(FirstInst->getSourceElementType(), Base,
00234                                 makeArrayRef(FixedOperands).slice(1));
00235   if (AllInBounds) NewGEP->setIsInBounds();
00236   NewGEP->setDebugLoc(FirstInst->getDebugLoc());
00237   return NewGEP;
00238 }
00239 
00240 
00241 /// isSafeAndProfitableToSinkLoad - Return true if we know that it is safe to
00242 /// sink the load out of the block that defines it.  This means that it must be
00243 /// obvious the value of the load is not changed from the point of the load to
00244 /// the end of the block it is in.
00245 ///
00246 /// Finally, it is safe, but not profitable, to sink a load targeting a
00247 /// non-address-taken alloca.  Doing so will cause us to not promote the alloca
00248 /// to a register.
00249 static bool isSafeAndProfitableToSinkLoad(LoadInst *L) {
00250   BasicBlock::iterator BBI = L, E = L->getParent()->end();
00251 
00252   for (++BBI; BBI != E; ++BBI)
00253     if (BBI->mayWriteToMemory())
00254       return false;
00255 
00256   // Check for non-address taken alloca.  If not address-taken already, it isn't
00257   // profitable to do this xform.
00258   if (AllocaInst *AI = dyn_cast<AllocaInst>(L->getOperand(0))) {
00259     bool isAddressTaken = false;
00260     for (User *U : AI->users()) {
00261       if (isa<LoadInst>(U)) continue;
00262       if (StoreInst *SI = dyn_cast<StoreInst>(U)) {
00263         // If storing TO the alloca, then the address isn't taken.
00264         if (SI->getOperand(1) == AI) continue;
00265       }
00266       isAddressTaken = true;
00267       break;
00268     }
00269 
00270     if (!isAddressTaken && AI->isStaticAlloca())
00271       return false;
00272   }
00273 
00274   // If this load is a load from a GEP with a constant offset from an alloca,
00275   // then we don't want to sink it.  In its present form, it will be
00276   // load [constant stack offset].  Sinking it will cause us to have to
00277   // materialize the stack addresses in each predecessor in a register only to
00278   // do a shared load from register in the successor.
00279   if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(L->getOperand(0)))
00280     if (AllocaInst *AI = dyn_cast<AllocaInst>(GEP->getOperand(0)))
00281       if (AI->isStaticAlloca() && GEP->hasAllConstantIndices())
00282         return false;
00283 
00284   return true;
00285 }
00286 
00287 Instruction *InstCombiner::FoldPHIArgLoadIntoPHI(PHINode &PN) {
00288   LoadInst *FirstLI = cast<LoadInst>(PN.getIncomingValue(0));
00289 
00290   // FIXME: This is overconservative; this transform is allowed in some cases
00291   // for atomic operations.
00292   if (FirstLI->isAtomic())
00293     return nullptr;
00294 
00295   // When processing loads, we need to propagate two bits of information to the
00296   // sunk load: whether it is volatile, and what its alignment is.  We currently
00297   // don't sink loads when some have their alignment specified and some don't.
00298   // visitLoadInst will propagate an alignment onto the load when TD is around,
00299   // and if TD isn't around, we can't handle the mixed case.
00300   bool isVolatile = FirstLI->isVolatile();
00301   unsigned LoadAlignment = FirstLI->getAlignment();
00302   unsigned LoadAddrSpace = FirstLI->getPointerAddressSpace();
00303 
00304   // We can't sink the load if the loaded value could be modified between the
00305   // load and the PHI.
00306   if (FirstLI->getParent() != PN.getIncomingBlock(0) ||
00307       !isSafeAndProfitableToSinkLoad(FirstLI))
00308     return nullptr;
00309 
00310   // If the PHI is of volatile loads and the load block has multiple
00311   // successors, sinking it would remove a load of the volatile value from
00312   // the path through the other successor.
00313   if (isVolatile &&
00314       FirstLI->getParent()->getTerminator()->getNumSuccessors() != 1)
00315     return nullptr;
00316 
00317   // Check to see if all arguments are the same operation.
00318   for (unsigned i = 1, e = PN.getNumIncomingValues(); i != e; ++i) {
00319     LoadInst *LI = dyn_cast<LoadInst>(PN.getIncomingValue(i));
00320     if (!LI || !LI->hasOneUse())
00321       return nullptr;
00322 
00323     // We can't sink the load if the loaded value could be modified between
00324     // the load and the PHI.
00325     if (LI->isVolatile() != isVolatile ||
00326         LI->getParent() != PN.getIncomingBlock(i) ||
00327         LI->getPointerAddressSpace() != LoadAddrSpace ||
00328         !isSafeAndProfitableToSinkLoad(LI))
00329       return nullptr;
00330 
00331     // If some of the loads have an alignment specified but not all of them,
00332     // we can't do the transformation.
00333     if ((LoadAlignment != 0) != (LI->getAlignment() != 0))
00334       return nullptr;
00335 
00336     LoadAlignment = std::min(LoadAlignment, LI->getAlignment());
00337 
00338     // If the PHI is of volatile loads and the load block has multiple
00339     // successors, sinking it would remove a load of the volatile value from
00340     // the path through the other successor.
00341     if (isVolatile &&
00342         LI->getParent()->getTerminator()->getNumSuccessors() != 1)
00343       return nullptr;
00344   }
00345 
00346   // Okay, they are all the same operation.  Create a new PHI node of the
00347   // correct type, and PHI together all of the LHS's of the instructions.
00348   PHINode *NewPN = PHINode::Create(FirstLI->getOperand(0)->getType(),
00349                                    PN.getNumIncomingValues(),
00350                                    PN.getName()+".in");
00351 
00352   Value *InVal = FirstLI->getOperand(0);
00353   NewPN->addIncoming(InVal, PN.getIncomingBlock(0));
00354 
00355   // Add all operands to the new PHI.
00356   for (unsigned i = 1, e = PN.getNumIncomingValues(); i != e; ++i) {
00357     Value *NewInVal = cast<LoadInst>(PN.getIncomingValue(i))->getOperand(0);
00358     if (NewInVal != InVal)
00359       InVal = nullptr;
00360     NewPN->addIncoming(NewInVal, PN.getIncomingBlock(i));
00361   }
00362 
00363   Value *PhiVal;
00364   if (InVal) {
00365     // The new PHI unions all of the same values together.  This is really
00366     // common, so we handle it intelligently here for compile-time speed.
00367     PhiVal = InVal;
00368     delete NewPN;
00369   } else {
00370     InsertNewInstBefore(NewPN, PN);
00371     PhiVal = NewPN;
00372   }
00373 
00374   // If this was a volatile load that we are merging, make sure to loop through
00375   // and mark all the input loads as non-volatile.  If we don't do this, we will
00376   // insert a new volatile load and the old ones will not be deletable.
00377   if (isVolatile)
00378     for (Value *IncValue : PN.incoming_values())
00379       cast<LoadInst>(IncValue)->setVolatile(false);
00380 
00381   LoadInst *NewLI = new LoadInst(PhiVal, "", isVolatile, LoadAlignment);
00382   NewLI->setDebugLoc(FirstLI->getDebugLoc());
00383   return NewLI;
00384 }
00385 
00386 
00387 
00388 /// FoldPHIArgOpIntoPHI - If all operands to a PHI node are the same "unary"
00389 /// operator and they all are only used by the PHI, PHI together their
00390 /// inputs, and do the operation once, to the result of the PHI.
00391 Instruction *InstCombiner::FoldPHIArgOpIntoPHI(PHINode &PN) {
00392   Instruction *FirstInst = cast<Instruction>(PN.getIncomingValue(0));
00393 
00394   if (isa<GetElementPtrInst>(FirstInst))
00395     return FoldPHIArgGEPIntoPHI(PN);
00396   if (isa<LoadInst>(FirstInst))
00397     return FoldPHIArgLoadIntoPHI(PN);
00398 
00399   // Scan the instruction, looking for input operations that can be folded away.
00400   // If all input operands to the phi are the same instruction (e.g. a cast from
00401   // the same type or "+42") we can pull the operation through the PHI, reducing
00402   // code size and simplifying code.
00403   Constant *ConstantOp = nullptr;
00404   Type *CastSrcTy = nullptr;
00405   bool isNUW = false, isNSW = false, isExact = false;
00406 
00407   if (isa<CastInst>(FirstInst)) {
00408     CastSrcTy = FirstInst->getOperand(0)->getType();
00409 
00410     // Be careful about transforming integer PHIs.  We don't want to pessimize
00411     // the code by turning an i32 into an i1293.
00412     if (PN.getType()->isIntegerTy() && CastSrcTy->isIntegerTy()) {
00413       if (!ShouldChangeType(PN.getType(), CastSrcTy))
00414         return nullptr;
00415     }
00416   } else if (isa<BinaryOperator>(FirstInst) || isa<CmpInst>(FirstInst)) {
00417     // Can fold binop, compare or shift here if the RHS is a constant,
00418     // otherwise call FoldPHIArgBinOpIntoPHI.
00419     ConstantOp = dyn_cast<Constant>(FirstInst->getOperand(1));
00420     if (!ConstantOp)
00421       return FoldPHIArgBinOpIntoPHI(PN);
00422 
00423     if (OverflowingBinaryOperator *BO =
00424         dyn_cast<OverflowingBinaryOperator>(FirstInst)) {
00425       isNUW = BO->hasNoUnsignedWrap();
00426       isNSW = BO->hasNoSignedWrap();
00427     } else if (PossiblyExactOperator *PEO =
00428                dyn_cast<PossiblyExactOperator>(FirstInst))
00429       isExact = PEO->isExact();
00430   } else {
00431     return nullptr;  // Cannot fold this operation.
00432   }
00433 
00434   // Check to see if all arguments are the same operation.
00435   for (unsigned i = 1, e = PN.getNumIncomingValues(); i != e; ++i) {
00436     Instruction *I = dyn_cast<Instruction>(PN.getIncomingValue(i));
00437     if (!I || !I->hasOneUse() || !I->isSameOperationAs(FirstInst))
00438       return nullptr;
00439     if (CastSrcTy) {
00440       if (I->getOperand(0)->getType() != CastSrcTy)
00441         return nullptr;  // Cast operation must match.
00442     } else if (I->getOperand(1) != ConstantOp) {
00443       return nullptr;
00444     }
00445 
00446     if (isNUW)
00447       isNUW = cast<OverflowingBinaryOperator>(I)->hasNoUnsignedWrap();
00448     if (isNSW)
00449       isNSW = cast<OverflowingBinaryOperator>(I)->hasNoSignedWrap();
00450     if (isExact)
00451       isExact = cast<PossiblyExactOperator>(I)->isExact();
00452   }
00453 
00454   // Okay, they are all the same operation.  Create a new PHI node of the
00455   // correct type, and PHI together all of the LHS's of the instructions.
00456   PHINode *NewPN = PHINode::Create(FirstInst->getOperand(0)->getType(),
00457                                    PN.getNumIncomingValues(),
00458                                    PN.getName()+".in");
00459 
00460   Value *InVal = FirstInst->getOperand(0);
00461   NewPN->addIncoming(InVal, PN.getIncomingBlock(0));
00462 
00463   // Add all operands to the new PHI.
00464   for (unsigned i = 1, e = PN.getNumIncomingValues(); i != e; ++i) {
00465     Value *NewInVal = cast<Instruction>(PN.getIncomingValue(i))->getOperand(0);
00466     if (NewInVal != InVal)
00467       InVal = nullptr;
00468     NewPN->addIncoming(NewInVal, PN.getIncomingBlock(i));
00469   }
00470 
00471   Value *PhiVal;
00472   if (InVal) {
00473     // The new PHI unions all of the same values together.  This is really
00474     // common, so we handle it intelligently here for compile-time speed.
00475     PhiVal = InVal;
00476     delete NewPN;
00477   } else {
00478     InsertNewInstBefore(NewPN, PN);
00479     PhiVal = NewPN;
00480   }
00481 
00482   // Insert and return the new operation.
00483   if (CastInst *FirstCI = dyn_cast<CastInst>(FirstInst)) {
00484     CastInst *NewCI = CastInst::Create(FirstCI->getOpcode(), PhiVal,
00485                                        PN.getType());
00486     NewCI->setDebugLoc(FirstInst->getDebugLoc());
00487     return NewCI;
00488   }
00489 
00490   if (BinaryOperator *BinOp = dyn_cast<BinaryOperator>(FirstInst)) {
00491     BinOp = BinaryOperator::Create(BinOp->getOpcode(), PhiVal, ConstantOp);
00492     if (isNUW) BinOp->setHasNoUnsignedWrap();
00493     if (isNSW) BinOp->setHasNoSignedWrap();
00494     if (isExact) BinOp->setIsExact();
00495     BinOp->setDebugLoc(FirstInst->getDebugLoc());
00496     return BinOp;
00497   }
00498 
00499   CmpInst *CIOp = cast<CmpInst>(FirstInst);
00500   CmpInst *NewCI = CmpInst::Create(CIOp->getOpcode(), CIOp->getPredicate(),
00501                                    PhiVal, ConstantOp);
00502   NewCI->setDebugLoc(FirstInst->getDebugLoc());
00503   return NewCI;
00504 }
00505 
00506 /// DeadPHICycle - Return true if this PHI node is only used by a PHI node cycle
00507 /// that is dead.
00508 static bool DeadPHICycle(PHINode *PN,
00509                          SmallPtrSetImpl<PHINode*> &PotentiallyDeadPHIs) {
00510   if (PN->use_empty()) return true;
00511   if (!PN->hasOneUse()) return false;
00512 
00513   // Remember this node, and if we find the cycle, return.
00514   if (!PotentiallyDeadPHIs.insert(PN).second)
00515     return true;
00516 
00517   // Don't scan crazily complex things.
00518   if (PotentiallyDeadPHIs.size() == 16)
00519     return false;
00520 
00521   if (PHINode *PU = dyn_cast<PHINode>(PN->user_back()))
00522     return DeadPHICycle(PU, PotentiallyDeadPHIs);
00523 
00524   return false;
00525 }
00526 
00527 /// PHIsEqualValue - Return true if this phi node is always equal to
00528 /// NonPhiInVal.  This happens with mutually cyclic phi nodes like:
00529 ///   z = some value; x = phi (y, z); y = phi (x, z)
00530 static bool PHIsEqualValue(PHINode *PN, Value *NonPhiInVal,
00531                            SmallPtrSetImpl<PHINode*> &ValueEqualPHIs) {
00532   // See if we already saw this PHI node.
00533   if (!ValueEqualPHIs.insert(PN).second)
00534     return true;
00535 
00536   // Don't scan crazily complex things.
00537   if (ValueEqualPHIs.size() == 16)
00538     return false;
00539 
00540   // Scan the operands to see if they are either phi nodes or are equal to
00541   // the value.
00542   for (Value *Op : PN->incoming_values()) {
00543     if (PHINode *OpPN = dyn_cast<PHINode>(Op)) {
00544       if (!PHIsEqualValue(OpPN, NonPhiInVal, ValueEqualPHIs))
00545         return false;
00546     } else if (Op != NonPhiInVal)
00547       return false;
00548   }
00549 
00550   return true;
00551 }
00552 
00553 
00554 namespace {
00555 struct PHIUsageRecord {
00556   unsigned PHIId;     // The ID # of the PHI (something determinstic to sort on)
00557   unsigned Shift;     // The amount shifted.
00558   Instruction *Inst;  // The trunc instruction.
00559 
00560   PHIUsageRecord(unsigned pn, unsigned Sh, Instruction *User)
00561     : PHIId(pn), Shift(Sh), Inst(User) {}
00562 
00563   bool operator<(const PHIUsageRecord &RHS) const {
00564     if (PHIId < RHS.PHIId) return true;
00565     if (PHIId > RHS.PHIId) return false;
00566     if (Shift < RHS.Shift) return true;
00567     if (Shift > RHS.Shift) return false;
00568     return Inst->getType()->getPrimitiveSizeInBits() <
00569            RHS.Inst->getType()->getPrimitiveSizeInBits();
00570   }
00571 };
00572 
00573 struct LoweredPHIRecord {
00574   PHINode *PN;        // The PHI that was lowered.
00575   unsigned Shift;     // The amount shifted.
00576   unsigned Width;     // The width extracted.
00577 
00578   LoweredPHIRecord(PHINode *pn, unsigned Sh, Type *Ty)
00579     : PN(pn), Shift(Sh), Width(Ty->getPrimitiveSizeInBits()) {}
00580 
00581   // Ctor form used by DenseMap.
00582   LoweredPHIRecord(PHINode *pn, unsigned Sh)
00583     : PN(pn), Shift(Sh), Width(0) {}
00584 };
00585 }
00586 
00587 namespace llvm {
00588   template<>
00589   struct DenseMapInfo<LoweredPHIRecord> {
00590     static inline LoweredPHIRecord getEmptyKey() {
00591       return LoweredPHIRecord(nullptr, 0);
00592     }
00593     static inline LoweredPHIRecord getTombstoneKey() {
00594       return LoweredPHIRecord(nullptr, 1);
00595     }
00596     static unsigned getHashValue(const LoweredPHIRecord &Val) {
00597       return DenseMapInfo<PHINode*>::getHashValue(Val.PN) ^ (Val.Shift>>3) ^
00598              (Val.Width>>3);
00599     }
00600     static bool isEqual(const LoweredPHIRecord &LHS,
00601                         const LoweredPHIRecord &RHS) {
00602       return LHS.PN == RHS.PN && LHS.Shift == RHS.Shift &&
00603              LHS.Width == RHS.Width;
00604     }
00605   };
00606 }
00607 
00608 
00609 /// SliceUpIllegalIntegerPHI - This is an integer PHI and we know that it has an
00610 /// illegal type: see if it is only used by trunc or trunc(lshr) operations.  If
00611 /// so, we split the PHI into the various pieces being extracted.  This sort of
00612 /// thing is introduced when SROA promotes an aggregate to large integer values.
00613 ///
00614 /// TODO: The user of the trunc may be an bitcast to float/double/vector or an
00615 /// inttoptr.  We should produce new PHIs in the right type.
00616 ///
00617 Instruction *InstCombiner::SliceUpIllegalIntegerPHI(PHINode &FirstPhi) {
00618   // PHIUsers - Keep track of all of the truncated values extracted from a set
00619   // of PHIs, along with their offset.  These are the things we want to rewrite.
00620   SmallVector<PHIUsageRecord, 16> PHIUsers;
00621 
00622   // PHIs are often mutually cyclic, so we keep track of a whole set of PHI
00623   // nodes which are extracted from. PHIsToSlice is a set we use to avoid
00624   // revisiting PHIs, PHIsInspected is a ordered list of PHIs that we need to
00625   // check the uses of (to ensure they are all extracts).
00626   SmallVector<PHINode*, 8> PHIsToSlice;
00627   SmallPtrSet<PHINode*, 8> PHIsInspected;
00628 
00629   PHIsToSlice.push_back(&FirstPhi);
00630   PHIsInspected.insert(&FirstPhi);
00631 
00632   for (unsigned PHIId = 0; PHIId != PHIsToSlice.size(); ++PHIId) {
00633     PHINode *PN = PHIsToSlice[PHIId];
00634 
00635     // Scan the input list of the PHI.  If any input is an invoke, and if the
00636     // input is defined in the predecessor, then we won't be split the critical
00637     // edge which is required to insert a truncate.  Because of this, we have to
00638     // bail out.
00639     for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) {
00640       InvokeInst *II = dyn_cast<InvokeInst>(PN->getIncomingValue(i));
00641       if (!II) continue;
00642       if (II->getParent() != PN->getIncomingBlock(i))
00643         continue;
00644 
00645       // If we have a phi, and if it's directly in the predecessor, then we have
00646       // a critical edge where we need to put the truncate.  Since we can't
00647       // split the edge in instcombine, we have to bail out.
00648       return nullptr;
00649     }
00650 
00651     for (User *U : PN->users()) {
00652       Instruction *UserI = cast<Instruction>(U);
00653 
00654       // If the user is a PHI, inspect its uses recursively.
00655       if (PHINode *UserPN = dyn_cast<PHINode>(UserI)) {
00656         if (PHIsInspected.insert(UserPN).second)
00657           PHIsToSlice.push_back(UserPN);
00658         continue;
00659       }
00660 
00661       // Truncates are always ok.
00662       if (isa<TruncInst>(UserI)) {
00663         PHIUsers.push_back(PHIUsageRecord(PHIId, 0, UserI));
00664         continue;
00665       }
00666 
00667       // Otherwise it must be a lshr which can only be used by one trunc.
00668       if (UserI->getOpcode() != Instruction::LShr ||
00669           !UserI->hasOneUse() || !isa<TruncInst>(UserI->user_back()) ||
00670           !isa<ConstantInt>(UserI->getOperand(1)))
00671         return nullptr;
00672 
00673       unsigned Shift = cast<ConstantInt>(UserI->getOperand(1))->getZExtValue();
00674       PHIUsers.push_back(PHIUsageRecord(PHIId, Shift, UserI->user_back()));
00675     }
00676   }
00677 
00678   // If we have no users, they must be all self uses, just nuke the PHI.
00679   if (PHIUsers.empty())
00680     return ReplaceInstUsesWith(FirstPhi, UndefValue::get(FirstPhi.getType()));
00681 
00682   // If this phi node is transformable, create new PHIs for all the pieces
00683   // extracted out of it.  First, sort the users by their offset and size.
00684   array_pod_sort(PHIUsers.begin(), PHIUsers.end());
00685 
00686   DEBUG(dbgs() << "SLICING UP PHI: " << FirstPhi << '\n';
00687         for (unsigned i = 1, e = PHIsToSlice.size(); i != e; ++i)
00688           dbgs() << "AND USER PHI #" << i << ": " << *PHIsToSlice[i] << '\n';
00689     );
00690 
00691   // PredValues - This is a temporary used when rewriting PHI nodes.  It is
00692   // hoisted out here to avoid construction/destruction thrashing.
00693   DenseMap<BasicBlock*, Value*> PredValues;
00694 
00695   // ExtractedVals - Each new PHI we introduce is saved here so we don't
00696   // introduce redundant PHIs.
00697   DenseMap<LoweredPHIRecord, PHINode*> ExtractedVals;
00698 
00699   for (unsigned UserI = 0, UserE = PHIUsers.size(); UserI != UserE; ++UserI) {
00700     unsigned PHIId = PHIUsers[UserI].PHIId;
00701     PHINode *PN = PHIsToSlice[PHIId];
00702     unsigned Offset = PHIUsers[UserI].Shift;
00703     Type *Ty = PHIUsers[UserI].Inst->getType();
00704 
00705     PHINode *EltPHI;
00706 
00707     // If we've already lowered a user like this, reuse the previously lowered
00708     // value.
00709     if ((EltPHI = ExtractedVals[LoweredPHIRecord(PN, Offset, Ty)]) == nullptr) {
00710 
00711       // Otherwise, Create the new PHI node for this user.
00712       EltPHI = PHINode::Create(Ty, PN->getNumIncomingValues(),
00713                                PN->getName()+".off"+Twine(Offset), PN);
00714       assert(EltPHI->getType() != PN->getType() &&
00715              "Truncate didn't shrink phi?");
00716 
00717       for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) {
00718         BasicBlock *Pred = PN->getIncomingBlock(i);
00719         Value *&PredVal = PredValues[Pred];
00720 
00721         // If we already have a value for this predecessor, reuse it.
00722         if (PredVal) {
00723           EltPHI->addIncoming(PredVal, Pred);
00724           continue;
00725         }
00726 
00727         // Handle the PHI self-reuse case.
00728         Value *InVal = PN->getIncomingValue(i);
00729         if (InVal == PN) {
00730           PredVal = EltPHI;
00731           EltPHI->addIncoming(PredVal, Pred);
00732           continue;
00733         }
00734 
00735         if (PHINode *InPHI = dyn_cast<PHINode>(PN)) {
00736           // If the incoming value was a PHI, and if it was one of the PHIs we
00737           // already rewrote it, just use the lowered value.
00738           if (Value *Res = ExtractedVals[LoweredPHIRecord(InPHI, Offset, Ty)]) {
00739             PredVal = Res;
00740             EltPHI->addIncoming(PredVal, Pred);
00741             continue;
00742           }
00743         }
00744 
00745         // Otherwise, do an extract in the predecessor.
00746         Builder->SetInsertPoint(Pred, Pred->getTerminator());
00747         Value *Res = InVal;
00748         if (Offset)
00749           Res = Builder->CreateLShr(Res, ConstantInt::get(InVal->getType(),
00750                                                           Offset), "extract");
00751         Res = Builder->CreateTrunc(Res, Ty, "extract.t");
00752         PredVal = Res;
00753         EltPHI->addIncoming(Res, Pred);
00754 
00755         // If the incoming value was a PHI, and if it was one of the PHIs we are
00756         // rewriting, we will ultimately delete the code we inserted.  This
00757         // means we need to revisit that PHI to make sure we extract out the
00758         // needed piece.
00759         if (PHINode *OldInVal = dyn_cast<PHINode>(PN->getIncomingValue(i)))
00760           if (PHIsInspected.count(OldInVal)) {
00761             unsigned RefPHIId = std::find(PHIsToSlice.begin(),PHIsToSlice.end(),
00762                                           OldInVal)-PHIsToSlice.begin();
00763             PHIUsers.push_back(PHIUsageRecord(RefPHIId, Offset,
00764                                               cast<Instruction>(Res)));
00765             ++UserE;
00766           }
00767       }
00768       PredValues.clear();
00769 
00770       DEBUG(dbgs() << "  Made element PHI for offset " << Offset << ": "
00771                    << *EltPHI << '\n');
00772       ExtractedVals[LoweredPHIRecord(PN, Offset, Ty)] = EltPHI;
00773     }
00774 
00775     // Replace the use of this piece with the PHI node.
00776     ReplaceInstUsesWith(*PHIUsers[UserI].Inst, EltPHI);
00777   }
00778 
00779   // Replace all the remaining uses of the PHI nodes (self uses and the lshrs)
00780   // with undefs.
00781   Value *Undef = UndefValue::get(FirstPhi.getType());
00782   for (unsigned i = 1, e = PHIsToSlice.size(); i != e; ++i)
00783     ReplaceInstUsesWith(*PHIsToSlice[i], Undef);
00784   return ReplaceInstUsesWith(FirstPhi, Undef);
00785 }
00786 
00787 // PHINode simplification
00788 //
00789 Instruction *InstCombiner::visitPHINode(PHINode &PN) {
00790   if (Value *V = SimplifyInstruction(&PN, DL, TLI, DT, AC))
00791     return ReplaceInstUsesWith(PN, V);
00792 
00793   // If all PHI operands are the same operation, pull them through the PHI,
00794   // reducing code size.
00795   if (isa<Instruction>(PN.getIncomingValue(0)) &&
00796       isa<Instruction>(PN.getIncomingValue(1)) &&
00797       cast<Instruction>(PN.getIncomingValue(0))->getOpcode() ==
00798       cast<Instruction>(PN.getIncomingValue(1))->getOpcode() &&
00799       // FIXME: The hasOneUse check will fail for PHIs that use the value more
00800       // than themselves more than once.
00801       PN.getIncomingValue(0)->hasOneUse())
00802     if (Instruction *Result = FoldPHIArgOpIntoPHI(PN))
00803       return Result;
00804 
00805   // If this is a trivial cycle in the PHI node graph, remove it.  Basically, if
00806   // this PHI only has a single use (a PHI), and if that PHI only has one use (a
00807   // PHI)... break the cycle.
00808   if (PN.hasOneUse()) {
00809     Instruction *PHIUser = cast<Instruction>(PN.user_back());
00810     if (PHINode *PU = dyn_cast<PHINode>(PHIUser)) {
00811       SmallPtrSet<PHINode*, 16> PotentiallyDeadPHIs;
00812       PotentiallyDeadPHIs.insert(&PN);
00813       if (DeadPHICycle(PU, PotentiallyDeadPHIs))
00814         return ReplaceInstUsesWith(PN, UndefValue::get(PN.getType()));
00815     }
00816 
00817     // If this phi has a single use, and if that use just computes a value for
00818     // the next iteration of a loop, delete the phi.  This occurs with unused
00819     // induction variables, e.g. "for (int j = 0; ; ++j);".  Detecting this
00820     // common case here is good because the only other things that catch this
00821     // are induction variable analysis (sometimes) and ADCE, which is only run
00822     // late.
00823     if (PHIUser->hasOneUse() &&
00824         (isa<BinaryOperator>(PHIUser) || isa<GetElementPtrInst>(PHIUser)) &&
00825         PHIUser->user_back() == &PN) {
00826       return ReplaceInstUsesWith(PN, UndefValue::get(PN.getType()));
00827     }
00828   }
00829 
00830   // We sometimes end up with phi cycles that non-obviously end up being the
00831   // same value, for example:
00832   //   z = some value; x = phi (y, z); y = phi (x, z)
00833   // where the phi nodes don't necessarily need to be in the same block.  Do a
00834   // quick check to see if the PHI node only contains a single non-phi value, if
00835   // so, scan to see if the phi cycle is actually equal to that value.
00836   {
00837     unsigned InValNo = 0, NumIncomingVals = PN.getNumIncomingValues();
00838     // Scan for the first non-phi operand.
00839     while (InValNo != NumIncomingVals &&
00840            isa<PHINode>(PN.getIncomingValue(InValNo)))
00841       ++InValNo;
00842 
00843     if (InValNo != NumIncomingVals) {
00844       Value *NonPhiInVal = PN.getIncomingValue(InValNo);
00845 
00846       // Scan the rest of the operands to see if there are any conflicts, if so
00847       // there is no need to recursively scan other phis.
00848       for (++InValNo; InValNo != NumIncomingVals; ++InValNo) {
00849         Value *OpVal = PN.getIncomingValue(InValNo);
00850         if (OpVal != NonPhiInVal && !isa<PHINode>(OpVal))
00851           break;
00852       }
00853 
00854       // If we scanned over all operands, then we have one unique value plus
00855       // phi values.  Scan PHI nodes to see if they all merge in each other or
00856       // the value.
00857       if (InValNo == NumIncomingVals) {
00858         SmallPtrSet<PHINode*, 16> ValueEqualPHIs;
00859         if (PHIsEqualValue(&PN, NonPhiInVal, ValueEqualPHIs))
00860           return ReplaceInstUsesWith(PN, NonPhiInVal);
00861       }
00862     }
00863   }
00864 
00865   // If there are multiple PHIs, sort their operands so that they all list
00866   // the blocks in the same order. This will help identical PHIs be eliminated
00867   // by other passes. Other passes shouldn't depend on this for correctness
00868   // however.
00869   PHINode *FirstPN = cast<PHINode>(PN.getParent()->begin());
00870   if (&PN != FirstPN)
00871     for (unsigned i = 0, e = FirstPN->getNumIncomingValues(); i != e; ++i) {
00872       BasicBlock *BBA = PN.getIncomingBlock(i);
00873       BasicBlock *BBB = FirstPN->getIncomingBlock(i);
00874       if (BBA != BBB) {
00875         Value *VA = PN.getIncomingValue(i);
00876         unsigned j = PN.getBasicBlockIndex(BBB);
00877         Value *VB = PN.getIncomingValue(j);
00878         PN.setIncomingBlock(i, BBB);
00879         PN.setIncomingValue(i, VB);
00880         PN.setIncomingBlock(j, BBA);
00881         PN.setIncomingValue(j, VA);
00882         // NOTE: Instcombine normally would want us to "return &PN" if we
00883         // modified any of the operands of an instruction.  However, since we
00884         // aren't adding or removing uses (just rearranging them) we don't do
00885         // this in this case.
00886       }
00887     }
00888 
00889   // If this is an integer PHI and we know that it has an illegal type, see if
00890   // it is only used by trunc or trunc(lshr) operations.  If so, we split the
00891   // PHI into the various pieces being extracted.  This sort of thing is
00892   // introduced when SROA promotes an aggregate to a single large integer type.
00893   if (PN.getType()->isIntegerTy() &&
00894       !DL.isLegalInteger(PN.getType()->getPrimitiveSizeInBits()))
00895     if (Instruction *Res = SliceUpIllegalIntegerPHI(PN))
00896       return Res;
00897 
00898   return nullptr;
00899 }