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 #include "llvm/Transforms/Utils/Local.h"
00019 using namespace llvm;
00020 
00021 #define DEBUG_TYPE "instcombine"
00022 
00023 /// If we have something like phi [add (a,b), add(a,c)] and if a/b/c and the
00024 /// adds all have a single use, turn this into a phi 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 /// Return true if we know that it is safe to sink the load out of the block
00242 /// that defines it. This means that it must be obvious the value of the load is
00243 /// not changed from the point of the load to the end of the block it is in.
00244 ///
00245 /// Finally, it is safe, but not profitable, to sink a load targeting a
00246 /// non-address-taken alloca.  Doing so will cause us to not promote the alloca
00247 /// to a register.
00248 static bool isSafeAndProfitableToSinkLoad(LoadInst *L) {
00249   BasicBlock::iterator BBI = L->getIterator(), E = L->getParent()->end();
00250 
00251   for (++BBI; BBI != E; ++BBI)
00252     if (BBI->mayWriteToMemory())
00253       return false;
00254 
00255   // Check for non-address taken alloca.  If not address-taken already, it isn't
00256   // profitable to do this xform.
00257   if (AllocaInst *AI = dyn_cast<AllocaInst>(L->getOperand(0))) {
00258     bool isAddressTaken = false;
00259     for (User *U : AI->users()) {
00260       if (isa<LoadInst>(U)) continue;
00261       if (StoreInst *SI = dyn_cast<StoreInst>(U)) {
00262         // If storing TO the alloca, then the address isn't taken.
00263         if (SI->getOperand(1) == AI) continue;
00264       }
00265       isAddressTaken = true;
00266       break;
00267     }
00268 
00269     if (!isAddressTaken && AI->isStaticAlloca())
00270       return false;
00271   }
00272 
00273   // If this load is a load from a GEP with a constant offset from an alloca,
00274   // then we don't want to sink it.  In its present form, it will be
00275   // load [constant stack offset].  Sinking it will cause us to have to
00276   // materialize the stack addresses in each predecessor in a register only to
00277   // do a shared load from register in the successor.
00278   if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(L->getOperand(0)))
00279     if (AllocaInst *AI = dyn_cast<AllocaInst>(GEP->getOperand(0)))
00280       if (AI->isStaticAlloca() && GEP->hasAllConstantIndices())
00281         return false;
00282 
00283   return true;
00284 }
00285 
00286 Instruction *InstCombiner::FoldPHIArgLoadIntoPHI(PHINode &PN) {
00287   LoadInst *FirstLI = cast<LoadInst>(PN.getIncomingValue(0));
00288 
00289   // FIXME: This is overconservative; this transform is allowed in some cases
00290   // for atomic operations.
00291   if (FirstLI->isAtomic())
00292     return nullptr;
00293 
00294   // When processing loads, we need to propagate two bits of information to the
00295   // sunk load: whether it is volatile, and what its alignment is.  We currently
00296   // don't sink loads when some have their alignment specified and some don't.
00297   // visitLoadInst will propagate an alignment onto the load when TD is around,
00298   // and if TD isn't around, we can't handle the mixed case.
00299   bool isVolatile = FirstLI->isVolatile();
00300   unsigned LoadAlignment = FirstLI->getAlignment();
00301   unsigned LoadAddrSpace = FirstLI->getPointerAddressSpace();
00302 
00303   // We can't sink the load if the loaded value could be modified between the
00304   // load and the PHI.
00305   if (FirstLI->getParent() != PN.getIncomingBlock(0) ||
00306       !isSafeAndProfitableToSinkLoad(FirstLI))
00307     return nullptr;
00308 
00309   // If the PHI is of volatile loads and the load block has multiple
00310   // successors, sinking it would remove a load of the volatile value from
00311   // the path through the other successor.
00312   if (isVolatile &&
00313       FirstLI->getParent()->getTerminator()->getNumSuccessors() != 1)
00314     return nullptr;
00315 
00316   // Check to see if all arguments are the same operation.
00317   for (unsigned i = 1, e = PN.getNumIncomingValues(); i != e; ++i) {
00318     LoadInst *LI = dyn_cast<LoadInst>(PN.getIncomingValue(i));
00319     if (!LI || !LI->hasOneUse())
00320       return nullptr;
00321 
00322     // We can't sink the load if the loaded value could be modified between
00323     // the load and the PHI.
00324     if (LI->isVolatile() != isVolatile ||
00325         LI->getParent() != PN.getIncomingBlock(i) ||
00326         LI->getPointerAddressSpace() != LoadAddrSpace ||
00327         !isSafeAndProfitableToSinkLoad(LI))
00328       return nullptr;
00329 
00330     // If some of the loads have an alignment specified but not all of them,
00331     // we can't do the transformation.
00332     if ((LoadAlignment != 0) != (LI->getAlignment() != 0))
00333       return nullptr;
00334 
00335     LoadAlignment = std::min(LoadAlignment, LI->getAlignment());
00336 
00337     // If the PHI is of volatile loads and the load block has multiple
00338     // successors, sinking it would remove a load of the volatile value from
00339     // the path through the other successor.
00340     if (isVolatile &&
00341         LI->getParent()->getTerminator()->getNumSuccessors() != 1)
00342       return nullptr;
00343   }
00344 
00345   // Okay, they are all the same operation.  Create a new PHI node of the
00346   // correct type, and PHI together all of the LHS's of the instructions.
00347   PHINode *NewPN = PHINode::Create(FirstLI->getOperand(0)->getType(),
00348                                    PN.getNumIncomingValues(),
00349                                    PN.getName()+".in");
00350 
00351   Value *InVal = FirstLI->getOperand(0);
00352   NewPN->addIncoming(InVal, PN.getIncomingBlock(0));
00353   LoadInst *NewLI = new LoadInst(NewPN, "", isVolatile, LoadAlignment);
00354 
00355   unsigned KnownIDs[] = {
00356     LLVMContext::MD_tbaa,
00357     LLVMContext::MD_range,
00358     LLVMContext::MD_invariant_load,
00359     LLVMContext::MD_alias_scope,
00360     LLVMContext::MD_noalias,
00361     LLVMContext::MD_nonnull,
00362     LLVMContext::MD_align,
00363     LLVMContext::MD_dereferenceable,
00364     LLVMContext::MD_dereferenceable_or_null,
00365   };
00366 
00367   for (unsigned ID : KnownIDs)
00368     NewLI->setMetadata(ID, FirstLI->getMetadata(ID));
00369 
00370   // Add all operands to the new PHI and combine TBAA metadata.
00371   for (unsigned i = 1, e = PN.getNumIncomingValues(); i != e; ++i) {
00372     LoadInst *LI = cast<LoadInst>(PN.getIncomingValue(i));
00373     combineMetadata(NewLI, LI, KnownIDs);
00374     Value *NewInVal = LI->getOperand(0);
00375     if (NewInVal != InVal)
00376       InVal = nullptr;
00377     NewPN->addIncoming(NewInVal, PN.getIncomingBlock(i));
00378   }
00379 
00380   if (InVal) {
00381     // The new PHI unions all of the same values together.  This is really
00382     // common, so we handle it intelligently here for compile-time speed.
00383     NewLI->setOperand(0, InVal);
00384     delete NewPN;
00385   } else {
00386     InsertNewInstBefore(NewPN, PN);
00387   }
00388 
00389   // If this was a volatile load that we are merging, make sure to loop through
00390   // and mark all the input loads as non-volatile.  If we don't do this, we will
00391   // insert a new volatile load and the old ones will not be deletable.
00392   if (isVolatile)
00393     for (Value *IncValue : PN.incoming_values())
00394       cast<LoadInst>(IncValue)->setVolatile(false);
00395 
00396   NewLI->setDebugLoc(FirstLI->getDebugLoc());
00397   return NewLI;
00398 }
00399 
00400 /// TODO: This function could handle other cast types, but then it might
00401 /// require special-casing a cast from the 'i1' type. See the comment in
00402 /// FoldPHIArgOpIntoPHI() about pessimizing illegal integer types.
00403 Instruction *InstCombiner::FoldPHIArgZextsIntoPHI(PHINode &Phi) {
00404   // We cannot create a new instruction after the PHI if the terminator is an
00405   // EHPad because there is no valid insertion point.
00406   if (TerminatorInst *TI = Phi.getParent()->getTerminator())
00407     if (TI->isEHPad())
00408       return nullptr;
00409 
00410   // Early exit for the common case of a phi with two operands. These are
00411   // handled elsewhere. See the comment below where we check the count of zexts
00412   // and constants for more details.
00413   unsigned NumIncomingValues = Phi.getNumIncomingValues();
00414   if (NumIncomingValues < 3)
00415     return nullptr;
00416 
00417   // Find the narrower type specified by the first zext.
00418   Type *NarrowType = nullptr;
00419   for (Value *V : Phi.incoming_values()) {
00420     if (auto *Zext = dyn_cast<ZExtInst>(V)) {
00421       NarrowType = Zext->getSrcTy();
00422       break;
00423     }
00424   }
00425   if (!NarrowType)
00426     return nullptr;
00427 
00428   // Walk the phi operands checking that we only have zexts or constants that
00429   // we can shrink for free. Store the new operands for the new phi.
00430   SmallVector<Value *, 4> NewIncoming;
00431   unsigned NumZexts = 0;
00432   unsigned NumConsts = 0;
00433   for (Value *V : Phi.incoming_values()) {
00434     if (auto *Zext = dyn_cast<ZExtInst>(V)) {
00435       // All zexts must be identical and have one use.
00436       if (Zext->getSrcTy() != NarrowType || !Zext->hasOneUse())
00437         return nullptr;
00438       NewIncoming.push_back(Zext->getOperand(0));
00439       NumZexts++;
00440     } else if (auto *C = dyn_cast<Constant>(V)) {
00441       // Make sure that constants can fit in the new type.
00442       Constant *Trunc = ConstantExpr::getTrunc(C, NarrowType);
00443       if (ConstantExpr::getZExt(Trunc, C->getType()) != C)
00444         return nullptr;
00445       NewIncoming.push_back(Trunc);
00446       NumConsts++;
00447     } else {
00448       // If it's not a cast or a constant, bail out.
00449       return nullptr;
00450     }
00451   }
00452 
00453   // The more common cases of a phi with no constant operands or just one
00454   // variable operand are handled by FoldPHIArgOpIntoPHI() and FoldOpIntoPhi()
00455   // respectively. FoldOpIntoPhi() wants to do the opposite transform that is
00456   // performed here. It tries to replicate a cast in the phi operand's basic
00457   // block to expose other folding opportunities. Thus, InstCombine will
00458   // infinite loop without this check.
00459   if (NumConsts == 0 || NumZexts < 2)
00460     return nullptr;
00461 
00462   // All incoming values are zexts or constants that are safe to truncate.
00463   // Create a new phi node of the narrow type, phi together all of the new
00464   // operands, and zext the result back to the original type.
00465   PHINode *NewPhi = PHINode::Create(NarrowType, NumIncomingValues,
00466                                     Phi.getName() + ".shrunk");
00467   for (unsigned i = 0; i != NumIncomingValues; ++i)
00468     NewPhi->addIncoming(NewIncoming[i], Phi.getIncomingBlock(i));
00469 
00470   InsertNewInstBefore(NewPhi, Phi);
00471   return CastInst::CreateZExtOrBitCast(NewPhi, Phi.getType());
00472 }
00473 
00474 /// If all operands to a PHI node are the same "unary" operator and they all are
00475 /// only used by the PHI, PHI together their inputs, and do the operation once,
00476 /// to the result of the PHI.
00477 Instruction *InstCombiner::FoldPHIArgOpIntoPHI(PHINode &PN) {
00478   // We cannot create a new instruction after the PHI if the terminator is an
00479   // EHPad because there is no valid insertion point.
00480   if (TerminatorInst *TI = PN.getParent()->getTerminator())
00481     if (TI->isEHPad())
00482       return nullptr;
00483 
00484   Instruction *FirstInst = cast<Instruction>(PN.getIncomingValue(0));
00485 
00486   if (isa<GetElementPtrInst>(FirstInst))
00487     return FoldPHIArgGEPIntoPHI(PN);
00488   if (isa<LoadInst>(FirstInst))
00489     return FoldPHIArgLoadIntoPHI(PN);
00490 
00491   // Scan the instruction, looking for input operations that can be folded away.
00492   // If all input operands to the phi are the same instruction (e.g. a cast from
00493   // the same type or "+42") we can pull the operation through the PHI, reducing
00494   // code size and simplifying code.
00495   Constant *ConstantOp = nullptr;
00496   Type *CastSrcTy = nullptr;
00497   bool isNUW = false, isNSW = false, isExact = false;
00498 
00499   if (isa<CastInst>(FirstInst)) {
00500     CastSrcTy = FirstInst->getOperand(0)->getType();
00501 
00502     // Be careful about transforming integer PHIs.  We don't want to pessimize
00503     // the code by turning an i32 into an i1293.
00504     if (PN.getType()->isIntegerTy() && CastSrcTy->isIntegerTy()) {
00505       if (!ShouldChangeType(PN.getType(), CastSrcTy))
00506         return nullptr;
00507     }
00508   } else if (isa<BinaryOperator>(FirstInst) || isa<CmpInst>(FirstInst)) {
00509     // Can fold binop, compare or shift here if the RHS is a constant,
00510     // otherwise call FoldPHIArgBinOpIntoPHI.
00511     ConstantOp = dyn_cast<Constant>(FirstInst->getOperand(1));
00512     if (!ConstantOp)
00513       return FoldPHIArgBinOpIntoPHI(PN);
00514 
00515     if (OverflowingBinaryOperator *BO =
00516         dyn_cast<OverflowingBinaryOperator>(FirstInst)) {
00517       isNUW = BO->hasNoUnsignedWrap();
00518       isNSW = BO->hasNoSignedWrap();
00519     } else if (PossiblyExactOperator *PEO =
00520                dyn_cast<PossiblyExactOperator>(FirstInst))
00521       isExact = PEO->isExact();
00522   } else {
00523     return nullptr;  // Cannot fold this operation.
00524   }
00525 
00526   // Check to see if all arguments are the same operation.
00527   for (unsigned i = 1, e = PN.getNumIncomingValues(); i != e; ++i) {
00528     Instruction *I = dyn_cast<Instruction>(PN.getIncomingValue(i));
00529     if (!I || !I->hasOneUse() || !I->isSameOperationAs(FirstInst))
00530       return nullptr;
00531     if (CastSrcTy) {
00532       if (I->getOperand(0)->getType() != CastSrcTy)
00533         return nullptr;  // Cast operation must match.
00534     } else if (I->getOperand(1) != ConstantOp) {
00535       return nullptr;
00536     }
00537 
00538     if (isNUW)
00539       isNUW = cast<OverflowingBinaryOperator>(I)->hasNoUnsignedWrap();
00540     if (isNSW)
00541       isNSW = cast<OverflowingBinaryOperator>(I)->hasNoSignedWrap();
00542     if (isExact)
00543       isExact = cast<PossiblyExactOperator>(I)->isExact();
00544   }
00545 
00546   // Okay, they are all the same operation.  Create a new PHI node of the
00547   // correct type, and PHI together all of the LHS's of the instructions.
00548   PHINode *NewPN = PHINode::Create(FirstInst->getOperand(0)->getType(),
00549                                    PN.getNumIncomingValues(),
00550                                    PN.getName()+".in");
00551 
00552   Value *InVal = FirstInst->getOperand(0);
00553   NewPN->addIncoming(InVal, PN.getIncomingBlock(0));
00554 
00555   // Add all operands to the new PHI.
00556   for (unsigned i = 1, e = PN.getNumIncomingValues(); i != e; ++i) {
00557     Value *NewInVal = cast<Instruction>(PN.getIncomingValue(i))->getOperand(0);
00558     if (NewInVal != InVal)
00559       InVal = nullptr;
00560     NewPN->addIncoming(NewInVal, PN.getIncomingBlock(i));
00561   }
00562 
00563   Value *PhiVal;
00564   if (InVal) {
00565     // The new PHI unions all of the same values together.  This is really
00566     // common, so we handle it intelligently here for compile-time speed.
00567     PhiVal = InVal;
00568     delete NewPN;
00569   } else {
00570     InsertNewInstBefore(NewPN, PN);
00571     PhiVal = NewPN;
00572   }
00573 
00574   // Insert and return the new operation.
00575   if (CastInst *FirstCI = dyn_cast<CastInst>(FirstInst)) {
00576     CastInst *NewCI = CastInst::Create(FirstCI->getOpcode(), PhiVal,
00577                                        PN.getType());
00578     NewCI->setDebugLoc(FirstInst->getDebugLoc());
00579     return NewCI;
00580   }
00581 
00582   if (BinaryOperator *BinOp = dyn_cast<BinaryOperator>(FirstInst)) {
00583     BinOp = BinaryOperator::Create(BinOp->getOpcode(), PhiVal, ConstantOp);
00584     if (isNUW) BinOp->setHasNoUnsignedWrap();
00585     if (isNSW) BinOp->setHasNoSignedWrap();
00586     if (isExact) BinOp->setIsExact();
00587     BinOp->setDebugLoc(FirstInst->getDebugLoc());
00588     return BinOp;
00589   }
00590 
00591   CmpInst *CIOp = cast<CmpInst>(FirstInst);
00592   CmpInst *NewCI = CmpInst::Create(CIOp->getOpcode(), CIOp->getPredicate(),
00593                                    PhiVal, ConstantOp);
00594   NewCI->setDebugLoc(FirstInst->getDebugLoc());
00595   return NewCI;
00596 }
00597 
00598 /// Return true if this PHI node is only used by a PHI node cycle that is dead.
00599 static bool DeadPHICycle(PHINode *PN,
00600                          SmallPtrSetImpl<PHINode*> &PotentiallyDeadPHIs) {
00601   if (PN->use_empty()) return true;
00602   if (!PN->hasOneUse()) return false;
00603 
00604   // Remember this node, and if we find the cycle, return.
00605   if (!PotentiallyDeadPHIs.insert(PN).second)
00606     return true;
00607 
00608   // Don't scan crazily complex things.
00609   if (PotentiallyDeadPHIs.size() == 16)
00610     return false;
00611 
00612   if (PHINode *PU = dyn_cast<PHINode>(PN->user_back()))
00613     return DeadPHICycle(PU, PotentiallyDeadPHIs);
00614 
00615   return false;
00616 }
00617 
00618 /// Return true if this phi node is always equal to NonPhiInVal.
00619 /// This happens with mutually cyclic phi nodes like:
00620 ///   z = some value; x = phi (y, z); y = phi (x, z)
00621 static bool PHIsEqualValue(PHINode *PN, Value *NonPhiInVal,
00622                            SmallPtrSetImpl<PHINode*> &ValueEqualPHIs) {
00623   // See if we already saw this PHI node.
00624   if (!ValueEqualPHIs.insert(PN).second)
00625     return true;
00626 
00627   // Don't scan crazily complex things.
00628   if (ValueEqualPHIs.size() == 16)
00629     return false;
00630 
00631   // Scan the operands to see if they are either phi nodes or are equal to
00632   // the value.
00633   for (Value *Op : PN->incoming_values()) {
00634     if (PHINode *OpPN = dyn_cast<PHINode>(Op)) {
00635       if (!PHIsEqualValue(OpPN, NonPhiInVal, ValueEqualPHIs))
00636         return false;
00637     } else if (Op != NonPhiInVal)
00638       return false;
00639   }
00640 
00641   return true;
00642 }
00643 
00644 
00645 namespace {
00646 struct PHIUsageRecord {
00647   unsigned PHIId;     // The ID # of the PHI (something determinstic to sort on)
00648   unsigned Shift;     // The amount shifted.
00649   Instruction *Inst;  // The trunc instruction.
00650 
00651   PHIUsageRecord(unsigned pn, unsigned Sh, Instruction *User)
00652     : PHIId(pn), Shift(Sh), Inst(User) {}
00653 
00654   bool operator<(const PHIUsageRecord &RHS) const {
00655     if (PHIId < RHS.PHIId) return true;
00656     if (PHIId > RHS.PHIId) return false;
00657     if (Shift < RHS.Shift) return true;
00658     if (Shift > RHS.Shift) return false;
00659     return Inst->getType()->getPrimitiveSizeInBits() <
00660            RHS.Inst->getType()->getPrimitiveSizeInBits();
00661   }
00662 };
00663 
00664 struct LoweredPHIRecord {
00665   PHINode *PN;        // The PHI that was lowered.
00666   unsigned Shift;     // The amount shifted.
00667   unsigned Width;     // The width extracted.
00668 
00669   LoweredPHIRecord(PHINode *pn, unsigned Sh, Type *Ty)
00670     : PN(pn), Shift(Sh), Width(Ty->getPrimitiveSizeInBits()) {}
00671 
00672   // Ctor form used by DenseMap.
00673   LoweredPHIRecord(PHINode *pn, unsigned Sh)
00674     : PN(pn), Shift(Sh), Width(0) {}
00675 };
00676 }
00677 
00678 namespace llvm {
00679   template<>
00680   struct DenseMapInfo<LoweredPHIRecord> {
00681     static inline LoweredPHIRecord getEmptyKey() {
00682       return LoweredPHIRecord(nullptr, 0);
00683     }
00684     static inline LoweredPHIRecord getTombstoneKey() {
00685       return LoweredPHIRecord(nullptr, 1);
00686     }
00687     static unsigned getHashValue(const LoweredPHIRecord &Val) {
00688       return DenseMapInfo<PHINode*>::getHashValue(Val.PN) ^ (Val.Shift>>3) ^
00689              (Val.Width>>3);
00690     }
00691     static bool isEqual(const LoweredPHIRecord &LHS,
00692                         const LoweredPHIRecord &RHS) {
00693       return LHS.PN == RHS.PN && LHS.Shift == RHS.Shift &&
00694              LHS.Width == RHS.Width;
00695     }
00696   };
00697 }
00698 
00699 
00700 /// This is an integer PHI and we know that it has an illegal type: see if it is
00701 /// only used by trunc or trunc(lshr) operations. If so, we split the PHI into
00702 /// the various pieces being extracted. This sort of thing is introduced when
00703 /// SROA promotes an aggregate to large integer values.
00704 ///
00705 /// TODO: The user of the trunc may be an bitcast to float/double/vector or an
00706 /// inttoptr.  We should produce new PHIs in the right type.
00707 ///
00708 Instruction *InstCombiner::SliceUpIllegalIntegerPHI(PHINode &FirstPhi) {
00709   // PHIUsers - Keep track of all of the truncated values extracted from a set
00710   // of PHIs, along with their offset.  These are the things we want to rewrite.
00711   SmallVector<PHIUsageRecord, 16> PHIUsers;
00712 
00713   // PHIs are often mutually cyclic, so we keep track of a whole set of PHI
00714   // nodes which are extracted from. PHIsToSlice is a set we use to avoid
00715   // revisiting PHIs, PHIsInspected is a ordered list of PHIs that we need to
00716   // check the uses of (to ensure they are all extracts).
00717   SmallVector<PHINode*, 8> PHIsToSlice;
00718   SmallPtrSet<PHINode*, 8> PHIsInspected;
00719 
00720   PHIsToSlice.push_back(&FirstPhi);
00721   PHIsInspected.insert(&FirstPhi);
00722 
00723   for (unsigned PHIId = 0; PHIId != PHIsToSlice.size(); ++PHIId) {
00724     PHINode *PN = PHIsToSlice[PHIId];
00725 
00726     // Scan the input list of the PHI.  If any input is an invoke, and if the
00727     // input is defined in the predecessor, then we won't be split the critical
00728     // edge which is required to insert a truncate.  Because of this, we have to
00729     // bail out.
00730     for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) {
00731       InvokeInst *II = dyn_cast<InvokeInst>(PN->getIncomingValue(i));
00732       if (!II) continue;
00733       if (II->getParent() != PN->getIncomingBlock(i))
00734         continue;
00735 
00736       // If we have a phi, and if it's directly in the predecessor, then we have
00737       // a critical edge where we need to put the truncate.  Since we can't
00738       // split the edge in instcombine, we have to bail out.
00739       return nullptr;
00740     }
00741 
00742     for (User *U : PN->users()) {
00743       Instruction *UserI = cast<Instruction>(U);
00744 
00745       // If the user is a PHI, inspect its uses recursively.
00746       if (PHINode *UserPN = dyn_cast<PHINode>(UserI)) {
00747         if (PHIsInspected.insert(UserPN).second)
00748           PHIsToSlice.push_back(UserPN);
00749         continue;
00750       }
00751 
00752       // Truncates are always ok.
00753       if (isa<TruncInst>(UserI)) {
00754         PHIUsers.push_back(PHIUsageRecord(PHIId, 0, UserI));
00755         continue;
00756       }
00757 
00758       // Otherwise it must be a lshr which can only be used by one trunc.
00759       if (UserI->getOpcode() != Instruction::LShr ||
00760           !UserI->hasOneUse() || !isa<TruncInst>(UserI->user_back()) ||
00761           !isa<ConstantInt>(UserI->getOperand(1)))
00762         return nullptr;
00763 
00764       unsigned Shift = cast<ConstantInt>(UserI->getOperand(1))->getZExtValue();
00765       PHIUsers.push_back(PHIUsageRecord(PHIId, Shift, UserI->user_back()));
00766     }
00767   }
00768 
00769   // If we have no users, they must be all self uses, just nuke the PHI.
00770   if (PHIUsers.empty())
00771     return ReplaceInstUsesWith(FirstPhi, UndefValue::get(FirstPhi.getType()));
00772 
00773   // If this phi node is transformable, create new PHIs for all the pieces
00774   // extracted out of it.  First, sort the users by their offset and size.
00775   array_pod_sort(PHIUsers.begin(), PHIUsers.end());
00776 
00777   DEBUG(dbgs() << "SLICING UP PHI: " << FirstPhi << '\n';
00778         for (unsigned i = 1, e = PHIsToSlice.size(); i != e; ++i)
00779           dbgs() << "AND USER PHI #" << i << ": " << *PHIsToSlice[i] << '\n';
00780     );
00781 
00782   // PredValues - This is a temporary used when rewriting PHI nodes.  It is
00783   // hoisted out here to avoid construction/destruction thrashing.
00784   DenseMap<BasicBlock*, Value*> PredValues;
00785 
00786   // ExtractedVals - Each new PHI we introduce is saved here so we don't
00787   // introduce redundant PHIs.
00788   DenseMap<LoweredPHIRecord, PHINode*> ExtractedVals;
00789 
00790   for (unsigned UserI = 0, UserE = PHIUsers.size(); UserI != UserE; ++UserI) {
00791     unsigned PHIId = PHIUsers[UserI].PHIId;
00792     PHINode *PN = PHIsToSlice[PHIId];
00793     unsigned Offset = PHIUsers[UserI].Shift;
00794     Type *Ty = PHIUsers[UserI].Inst->getType();
00795 
00796     PHINode *EltPHI;
00797 
00798     // If we've already lowered a user like this, reuse the previously lowered
00799     // value.
00800     if ((EltPHI = ExtractedVals[LoweredPHIRecord(PN, Offset, Ty)]) == nullptr) {
00801 
00802       // Otherwise, Create the new PHI node for this user.
00803       EltPHI = PHINode::Create(Ty, PN->getNumIncomingValues(),
00804                                PN->getName()+".off"+Twine(Offset), PN);
00805       assert(EltPHI->getType() != PN->getType() &&
00806              "Truncate didn't shrink phi?");
00807 
00808       for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) {
00809         BasicBlock *Pred = PN->getIncomingBlock(i);
00810         Value *&PredVal = PredValues[Pred];
00811 
00812         // If we already have a value for this predecessor, reuse it.
00813         if (PredVal) {
00814           EltPHI->addIncoming(PredVal, Pred);
00815           continue;
00816         }
00817 
00818         // Handle the PHI self-reuse case.
00819         Value *InVal = PN->getIncomingValue(i);
00820         if (InVal == PN) {
00821           PredVal = EltPHI;
00822           EltPHI->addIncoming(PredVal, Pred);
00823           continue;
00824         }
00825 
00826         if (PHINode *InPHI = dyn_cast<PHINode>(PN)) {
00827           // If the incoming value was a PHI, and if it was one of the PHIs we
00828           // already rewrote it, just use the lowered value.
00829           if (Value *Res = ExtractedVals[LoweredPHIRecord(InPHI, Offset, Ty)]) {
00830             PredVal = Res;
00831             EltPHI->addIncoming(PredVal, Pred);
00832             continue;
00833           }
00834         }
00835 
00836         // Otherwise, do an extract in the predecessor.
00837         Builder->SetInsertPoint(Pred->getTerminator());
00838         Value *Res = InVal;
00839         if (Offset)
00840           Res = Builder->CreateLShr(Res, ConstantInt::get(InVal->getType(),
00841                                                           Offset), "extract");
00842         Res = Builder->CreateTrunc(Res, Ty, "extract.t");
00843         PredVal = Res;
00844         EltPHI->addIncoming(Res, Pred);
00845 
00846         // If the incoming value was a PHI, and if it was one of the PHIs we are
00847         // rewriting, we will ultimately delete the code we inserted.  This
00848         // means we need to revisit that PHI to make sure we extract out the
00849         // needed piece.
00850         if (PHINode *OldInVal = dyn_cast<PHINode>(PN->getIncomingValue(i)))
00851           if (PHIsInspected.count(OldInVal)) {
00852             unsigned RefPHIId = std::find(PHIsToSlice.begin(),PHIsToSlice.end(),
00853                                           OldInVal)-PHIsToSlice.begin();
00854             PHIUsers.push_back(PHIUsageRecord(RefPHIId, Offset,
00855                                               cast<Instruction>(Res)));
00856             ++UserE;
00857           }
00858       }
00859       PredValues.clear();
00860 
00861       DEBUG(dbgs() << "  Made element PHI for offset " << Offset << ": "
00862                    << *EltPHI << '\n');
00863       ExtractedVals[LoweredPHIRecord(PN, Offset, Ty)] = EltPHI;
00864     }
00865 
00866     // Replace the use of this piece with the PHI node.
00867     ReplaceInstUsesWith(*PHIUsers[UserI].Inst, EltPHI);
00868   }
00869 
00870   // Replace all the remaining uses of the PHI nodes (self uses and the lshrs)
00871   // with undefs.
00872   Value *Undef = UndefValue::get(FirstPhi.getType());
00873   for (unsigned i = 1, e = PHIsToSlice.size(); i != e; ++i)
00874     ReplaceInstUsesWith(*PHIsToSlice[i], Undef);
00875   return ReplaceInstUsesWith(FirstPhi, Undef);
00876 }
00877 
00878 // PHINode simplification
00879 //
00880 Instruction *InstCombiner::visitPHINode(PHINode &PN) {
00881   if (Value *V = SimplifyInstruction(&PN, DL, TLI, DT, AC))
00882     return ReplaceInstUsesWith(PN, V);
00883 
00884   if (Instruction *Result = FoldPHIArgZextsIntoPHI(PN))
00885     return Result;
00886 
00887   // If all PHI operands are the same operation, pull them through the PHI,
00888   // reducing code size.
00889   if (isa<Instruction>(PN.getIncomingValue(0)) &&
00890       isa<Instruction>(PN.getIncomingValue(1)) &&
00891       cast<Instruction>(PN.getIncomingValue(0))->getOpcode() ==
00892       cast<Instruction>(PN.getIncomingValue(1))->getOpcode() &&
00893       // FIXME: The hasOneUse check will fail for PHIs that use the value more
00894       // than themselves more than once.
00895       PN.getIncomingValue(0)->hasOneUse())
00896     if (Instruction *Result = FoldPHIArgOpIntoPHI(PN))
00897       return Result;
00898 
00899   // If this is a trivial cycle in the PHI node graph, remove it.  Basically, if
00900   // this PHI only has a single use (a PHI), and if that PHI only has one use (a
00901   // PHI)... break the cycle.
00902   if (PN.hasOneUse()) {
00903     Instruction *PHIUser = cast<Instruction>(PN.user_back());
00904     if (PHINode *PU = dyn_cast<PHINode>(PHIUser)) {
00905       SmallPtrSet<PHINode*, 16> PotentiallyDeadPHIs;
00906       PotentiallyDeadPHIs.insert(&PN);
00907       if (DeadPHICycle(PU, PotentiallyDeadPHIs))
00908         return ReplaceInstUsesWith(PN, UndefValue::get(PN.getType()));
00909     }
00910 
00911     // If this phi has a single use, and if that use just computes a value for
00912     // the next iteration of a loop, delete the phi.  This occurs with unused
00913     // induction variables, e.g. "for (int j = 0; ; ++j);".  Detecting this
00914     // common case here is good because the only other things that catch this
00915     // are induction variable analysis (sometimes) and ADCE, which is only run
00916     // late.
00917     if (PHIUser->hasOneUse() &&
00918         (isa<BinaryOperator>(PHIUser) || isa<GetElementPtrInst>(PHIUser)) &&
00919         PHIUser->user_back() == &PN) {
00920       return ReplaceInstUsesWith(PN, UndefValue::get(PN.getType()));
00921     }
00922   }
00923 
00924   // We sometimes end up with phi cycles that non-obviously end up being the
00925   // same value, for example:
00926   //   z = some value; x = phi (y, z); y = phi (x, z)
00927   // where the phi nodes don't necessarily need to be in the same block.  Do a
00928   // quick check to see if the PHI node only contains a single non-phi value, if
00929   // so, scan to see if the phi cycle is actually equal to that value.
00930   {
00931     unsigned InValNo = 0, NumIncomingVals = PN.getNumIncomingValues();
00932     // Scan for the first non-phi operand.
00933     while (InValNo != NumIncomingVals &&
00934            isa<PHINode>(PN.getIncomingValue(InValNo)))
00935       ++InValNo;
00936 
00937     if (InValNo != NumIncomingVals) {
00938       Value *NonPhiInVal = PN.getIncomingValue(InValNo);
00939 
00940       // Scan the rest of the operands to see if there are any conflicts, if so
00941       // there is no need to recursively scan other phis.
00942       for (++InValNo; InValNo != NumIncomingVals; ++InValNo) {
00943         Value *OpVal = PN.getIncomingValue(InValNo);
00944         if (OpVal != NonPhiInVal && !isa<PHINode>(OpVal))
00945           break;
00946       }
00947 
00948       // If we scanned over all operands, then we have one unique value plus
00949       // phi values.  Scan PHI nodes to see if they all merge in each other or
00950       // the value.
00951       if (InValNo == NumIncomingVals) {
00952         SmallPtrSet<PHINode*, 16> ValueEqualPHIs;
00953         if (PHIsEqualValue(&PN, NonPhiInVal, ValueEqualPHIs))
00954           return ReplaceInstUsesWith(PN, NonPhiInVal);
00955       }
00956     }
00957   }
00958 
00959   // If there are multiple PHIs, sort their operands so that they all list
00960   // the blocks in the same order. This will help identical PHIs be eliminated
00961   // by other passes. Other passes shouldn't depend on this for correctness
00962   // however.
00963   PHINode *FirstPN = cast<PHINode>(PN.getParent()->begin());
00964   if (&PN != FirstPN)
00965     for (unsigned i = 0, e = FirstPN->getNumIncomingValues(); i != e; ++i) {
00966       BasicBlock *BBA = PN.getIncomingBlock(i);
00967       BasicBlock *BBB = FirstPN->getIncomingBlock(i);
00968       if (BBA != BBB) {
00969         Value *VA = PN.getIncomingValue(i);
00970         unsigned j = PN.getBasicBlockIndex(BBB);
00971         Value *VB = PN.getIncomingValue(j);
00972         PN.setIncomingBlock(i, BBB);
00973         PN.setIncomingValue(i, VB);
00974         PN.setIncomingBlock(j, BBA);
00975         PN.setIncomingValue(j, VA);
00976         // NOTE: Instcombine normally would want us to "return &PN" if we
00977         // modified any of the operands of an instruction.  However, since we
00978         // aren't adding or removing uses (just rearranging them) we don't do
00979         // this in this case.
00980       }
00981     }
00982 
00983   // If this is an integer PHI and we know that it has an illegal type, see if
00984   // it is only used by trunc or trunc(lshr) operations.  If so, we split the
00985   // PHI into the various pieces being extracted.  This sort of thing is
00986   // introduced when SROA promotes an aggregate to a single large integer type.
00987   if (PN.getType()->isIntegerTy() &&
00988       !DL.isLegalInteger(PN.getType()->getPrimitiveSizeInBits()))
00989     if (Instruction *Res = SliceUpIllegalIntegerPHI(PN))
00990       return Res;
00991 
00992   return nullptr;
00993 }