InstCombinePHI.cpp revision 218893
1202375Srdivacky//===- InstCombinePHI.cpp -------------------------------------------------===//
2202375Srdivacky//
3202375Srdivacky//                     The LLVM Compiler Infrastructure
4202375Srdivacky//
5202375Srdivacky// This file is distributed under the University of Illinois Open Source
6202375Srdivacky// License. See LICENSE.TXT for details.
7202375Srdivacky//
8202375Srdivacky//===----------------------------------------------------------------------===//
9202375Srdivacky//
10202375Srdivacky// This file implements the visitPHINode function.
11202375Srdivacky//
12202375Srdivacky//===----------------------------------------------------------------------===//
13202375Srdivacky
14202375Srdivacky#include "InstCombine.h"
15218893Sdim#include "llvm/Analysis/InstructionSimplify.h"
16202375Srdivacky#include "llvm/Target/TargetData.h"
17202375Srdivacky#include "llvm/ADT/SmallPtrSet.h"
18202375Srdivacky#include "llvm/ADT/STLExtras.h"
19202375Srdivackyusing namespace llvm;
20202375Srdivacky
21202375Srdivacky/// FoldPHIArgBinOpIntoPHI - If we have something like phi [add (a,b), add(a,c)]
22202375Srdivacky/// and if a/b/c and the add's all have a single use, turn this into a phi
23202375Srdivacky/// and a single binop.
24202375SrdivackyInstruction *InstCombiner::FoldPHIArgBinOpIntoPHI(PHINode &PN) {
25202375Srdivacky  Instruction *FirstInst = cast<Instruction>(PN.getIncomingValue(0));
26202375Srdivacky  assert(isa<BinaryOperator>(FirstInst) || isa<CmpInst>(FirstInst));
27202375Srdivacky  unsigned Opc = FirstInst->getOpcode();
28202375Srdivacky  Value *LHSVal = FirstInst->getOperand(0);
29202375Srdivacky  Value *RHSVal = FirstInst->getOperand(1);
30202375Srdivacky
31202375Srdivacky  const Type *LHSType = LHSVal->getType();
32202375Srdivacky  const Type *RHSType = RHSVal->getType();
33202375Srdivacky
34218893Sdim  bool isNUW = false, isNSW = false, isExact = false;
35218893Sdim  if (OverflowingBinaryOperator *BO =
36218893Sdim        dyn_cast<OverflowingBinaryOperator>(FirstInst)) {
37218893Sdim    isNUW = BO->hasNoUnsignedWrap();
38218893Sdim    isNSW = BO->hasNoSignedWrap();
39218893Sdim  } else if (PossiblyExactOperator *PEO =
40218893Sdim               dyn_cast<PossiblyExactOperator>(FirstInst))
41218893Sdim    isExact = PEO->isExact();
42218893Sdim
43202375Srdivacky  // Scan to see if all operands are the same opcode, and all have one use.
44202375Srdivacky  for (unsigned i = 1; i != PN.getNumIncomingValues(); ++i) {
45202375Srdivacky    Instruction *I = dyn_cast<Instruction>(PN.getIncomingValue(i));
46202375Srdivacky    if (!I || I->getOpcode() != Opc || !I->hasOneUse() ||
47202375Srdivacky        // Verify type of the LHS matches so we don't fold cmp's of different
48218893Sdim        // types.
49202375Srdivacky        I->getOperand(0)->getType() != LHSType ||
50202375Srdivacky        I->getOperand(1)->getType() != RHSType)
51202375Srdivacky      return 0;
52202375Srdivacky
53202375Srdivacky    // If they are CmpInst instructions, check their predicates
54218893Sdim    if (CmpInst *CI = dyn_cast<CmpInst>(I))
55218893Sdim      if (CI->getPredicate() != cast<CmpInst>(FirstInst)->getPredicate())
56202375Srdivacky        return 0;
57202375Srdivacky
58218893Sdim    if (isNUW)
59218893Sdim      isNUW = cast<OverflowingBinaryOperator>(I)->hasNoUnsignedWrap();
60218893Sdim    if (isNSW)
61218893Sdim      isNSW = cast<OverflowingBinaryOperator>(I)->hasNoSignedWrap();
62218893Sdim    if (isExact)
63218893Sdim      isExact = cast<PossiblyExactOperator>(I)->isExact();
64218893Sdim
65202375Srdivacky    // Keep track of which operand needs a phi node.
66202375Srdivacky    if (I->getOperand(0) != LHSVal) LHSVal = 0;
67202375Srdivacky    if (I->getOperand(1) != RHSVal) RHSVal = 0;
68202375Srdivacky  }
69202375Srdivacky
70202375Srdivacky  // If both LHS and RHS would need a PHI, don't do this transformation,
71202375Srdivacky  // because it would increase the number of PHIs entering the block,
72202375Srdivacky  // which leads to higher register pressure. This is especially
73202375Srdivacky  // bad when the PHIs are in the header of a loop.
74202375Srdivacky  if (!LHSVal && !RHSVal)
75202375Srdivacky    return 0;
76202375Srdivacky
77202375Srdivacky  // Otherwise, this is safe to transform!
78202375Srdivacky
79202375Srdivacky  Value *InLHS = FirstInst->getOperand(0);
80202375Srdivacky  Value *InRHS = FirstInst->getOperand(1);
81202375Srdivacky  PHINode *NewLHS = 0, *NewRHS = 0;
82202375Srdivacky  if (LHSVal == 0) {
83202375Srdivacky    NewLHS = PHINode::Create(LHSType,
84202375Srdivacky                             FirstInst->getOperand(0)->getName() + ".pn");
85202375Srdivacky    NewLHS->reserveOperandSpace(PN.getNumOperands()/2);
86202375Srdivacky    NewLHS->addIncoming(InLHS, PN.getIncomingBlock(0));
87202375Srdivacky    InsertNewInstBefore(NewLHS, PN);
88202375Srdivacky    LHSVal = NewLHS;
89202375Srdivacky  }
90202375Srdivacky
91202375Srdivacky  if (RHSVal == 0) {
92202375Srdivacky    NewRHS = PHINode::Create(RHSType,
93202375Srdivacky                             FirstInst->getOperand(1)->getName() + ".pn");
94202375Srdivacky    NewRHS->reserveOperandSpace(PN.getNumOperands()/2);
95202375Srdivacky    NewRHS->addIncoming(InRHS, PN.getIncomingBlock(0));
96202375Srdivacky    InsertNewInstBefore(NewRHS, PN);
97202375Srdivacky    RHSVal = NewRHS;
98202375Srdivacky  }
99202375Srdivacky
100202375Srdivacky  // Add all operands to the new PHIs.
101202375Srdivacky  if (NewLHS || NewRHS) {
102202375Srdivacky    for (unsigned i = 1, e = PN.getNumIncomingValues(); i != e; ++i) {
103202375Srdivacky      Instruction *InInst = cast<Instruction>(PN.getIncomingValue(i));
104202375Srdivacky      if (NewLHS) {
105202375Srdivacky        Value *NewInLHS = InInst->getOperand(0);
106202375Srdivacky        NewLHS->addIncoming(NewInLHS, PN.getIncomingBlock(i));
107202375Srdivacky      }
108202375Srdivacky      if (NewRHS) {
109202375Srdivacky        Value *NewInRHS = InInst->getOperand(1);
110202375Srdivacky        NewRHS->addIncoming(NewInRHS, PN.getIncomingBlock(i));
111202375Srdivacky      }
112202375Srdivacky    }
113202375Srdivacky  }
114202375Srdivacky
115218893Sdim  if (CmpInst *CIOp = dyn_cast<CmpInst>(FirstInst))
116218893Sdim    return CmpInst::Create(CIOp->getOpcode(), CIOp->getPredicate(),
117218893Sdim                           LHSVal, RHSVal);
118218893Sdim
119218893Sdim  BinaryOperator *BinOp = cast<BinaryOperator>(FirstInst);
120218893Sdim  BinaryOperator *NewBinOp =
121218893Sdim    BinaryOperator::Create(BinOp->getOpcode(), LHSVal, RHSVal);
122218893Sdim  if (isNUW) NewBinOp->setHasNoUnsignedWrap();
123218893Sdim  if (isNSW) NewBinOp->setHasNoSignedWrap();
124218893Sdim  if (isExact) NewBinOp->setIsExact();
125218893Sdim  return NewBinOp;
126202375Srdivacky}
127202375Srdivacky
128202375SrdivackyInstruction *InstCombiner::FoldPHIArgGEPIntoPHI(PHINode &PN) {
129202375Srdivacky  GetElementPtrInst *FirstInst =cast<GetElementPtrInst>(PN.getIncomingValue(0));
130202375Srdivacky
131202375Srdivacky  SmallVector<Value*, 16> FixedOperands(FirstInst->op_begin(),
132202375Srdivacky                                        FirstInst->op_end());
133202375Srdivacky  // This is true if all GEP bases are allocas and if all indices into them are
134202375Srdivacky  // constants.
135202375Srdivacky  bool AllBasePointersAreAllocas = true;
136202375Srdivacky
137202375Srdivacky  // We don't want to replace this phi if the replacement would require
138202375Srdivacky  // more than one phi, which leads to higher register pressure. This is
139202375Srdivacky  // especially bad when the PHIs are in the header of a loop.
140202375Srdivacky  bool NeededPhi = false;
141202375Srdivacky
142218893Sdim  bool AllInBounds = true;
143218893Sdim
144202375Srdivacky  // Scan to see if all operands are the same opcode, and all have one use.
145202375Srdivacky  for (unsigned i = 1; i != PN.getNumIncomingValues(); ++i) {
146202375Srdivacky    GetElementPtrInst *GEP= dyn_cast<GetElementPtrInst>(PN.getIncomingValue(i));
147202375Srdivacky    if (!GEP || !GEP->hasOneUse() || GEP->getType() != FirstInst->getType() ||
148202375Srdivacky      GEP->getNumOperands() != FirstInst->getNumOperands())
149202375Srdivacky      return 0;
150202375Srdivacky
151218893Sdim    AllInBounds &= GEP->isInBounds();
152218893Sdim
153202375Srdivacky    // Keep track of whether or not all GEPs are of alloca pointers.
154202375Srdivacky    if (AllBasePointersAreAllocas &&
155202375Srdivacky        (!isa<AllocaInst>(GEP->getOperand(0)) ||
156202375Srdivacky         !GEP->hasAllConstantIndices()))
157202375Srdivacky      AllBasePointersAreAllocas = false;
158202375Srdivacky
159202375Srdivacky    // Compare the operand lists.
160202375Srdivacky    for (unsigned op = 0, e = FirstInst->getNumOperands(); op != e; ++op) {
161202375Srdivacky      if (FirstInst->getOperand(op) == GEP->getOperand(op))
162202375Srdivacky        continue;
163202375Srdivacky
164202375Srdivacky      // Don't merge two GEPs when two operands differ (introducing phi nodes)
165202375Srdivacky      // if one of the PHIs has a constant for the index.  The index may be
166202375Srdivacky      // substantially cheaper to compute for the constants, so making it a
167202375Srdivacky      // variable index could pessimize the path.  This also handles the case
168202375Srdivacky      // for struct indices, which must always be constant.
169202375Srdivacky      if (isa<ConstantInt>(FirstInst->getOperand(op)) ||
170202375Srdivacky          isa<ConstantInt>(GEP->getOperand(op)))
171202375Srdivacky        return 0;
172202375Srdivacky
173202375Srdivacky      if (FirstInst->getOperand(op)->getType() !=GEP->getOperand(op)->getType())
174202375Srdivacky        return 0;
175202375Srdivacky
176202375Srdivacky      // If we already needed a PHI for an earlier operand, and another operand
177202375Srdivacky      // also requires a PHI, we'd be introducing more PHIs than we're
178202375Srdivacky      // eliminating, which increases register pressure on entry to the PHI's
179202375Srdivacky      // block.
180202375Srdivacky      if (NeededPhi)
181202375Srdivacky        return 0;
182202375Srdivacky
183202375Srdivacky      FixedOperands[op] = 0;  // Needs a PHI.
184202375Srdivacky      NeededPhi = true;
185202375Srdivacky    }
186202375Srdivacky  }
187202375Srdivacky
188202375Srdivacky  // If all of the base pointers of the PHI'd GEPs are from allocas, don't
189202375Srdivacky  // bother doing this transformation.  At best, this will just save a bit of
190202375Srdivacky  // offset calculation, but all the predecessors will have to materialize the
191202375Srdivacky  // stack address into a register anyway.  We'd actually rather *clone* the
192202375Srdivacky  // load up into the predecessors so that we have a load of a gep of an alloca,
193202375Srdivacky  // which can usually all be folded into the load.
194202375Srdivacky  if (AllBasePointersAreAllocas)
195202375Srdivacky    return 0;
196202375Srdivacky
197202375Srdivacky  // Otherwise, this is safe to transform.  Insert PHI nodes for each operand
198202375Srdivacky  // that is variable.
199202375Srdivacky  SmallVector<PHINode*, 16> OperandPhis(FixedOperands.size());
200202375Srdivacky
201202375Srdivacky  bool HasAnyPHIs = false;
202202375Srdivacky  for (unsigned i = 0, e = FixedOperands.size(); i != e; ++i) {
203202375Srdivacky    if (FixedOperands[i]) continue;  // operand doesn't need a phi.
204202375Srdivacky    Value *FirstOp = FirstInst->getOperand(i);
205202375Srdivacky    PHINode *NewPN = PHINode::Create(FirstOp->getType(),
206202375Srdivacky                                     FirstOp->getName()+".pn");
207202375Srdivacky    InsertNewInstBefore(NewPN, PN);
208202375Srdivacky
209202375Srdivacky    NewPN->reserveOperandSpace(e);
210202375Srdivacky    NewPN->addIncoming(FirstOp, PN.getIncomingBlock(0));
211202375Srdivacky    OperandPhis[i] = NewPN;
212202375Srdivacky    FixedOperands[i] = NewPN;
213202375Srdivacky    HasAnyPHIs = true;
214202375Srdivacky  }
215202375Srdivacky
216202375Srdivacky
217202375Srdivacky  // Add all operands to the new PHIs.
218202375Srdivacky  if (HasAnyPHIs) {
219202375Srdivacky    for (unsigned i = 1, e = PN.getNumIncomingValues(); i != e; ++i) {
220202375Srdivacky      GetElementPtrInst *InGEP =cast<GetElementPtrInst>(PN.getIncomingValue(i));
221202375Srdivacky      BasicBlock *InBB = PN.getIncomingBlock(i);
222202375Srdivacky
223202375Srdivacky      for (unsigned op = 0, e = OperandPhis.size(); op != e; ++op)
224202375Srdivacky        if (PHINode *OpPhi = OperandPhis[op])
225202375Srdivacky          OpPhi->addIncoming(InGEP->getOperand(op), InBB);
226202375Srdivacky    }
227202375Srdivacky  }
228202375Srdivacky
229202375Srdivacky  Value *Base = FixedOperands[0];
230218893Sdim  GetElementPtrInst *NewGEP =
231202375Srdivacky    GetElementPtrInst::Create(Base, FixedOperands.begin()+1,
232202375Srdivacky                              FixedOperands.end());
233218893Sdim  if (AllInBounds) NewGEP->setIsInBounds();
234218893Sdim  return NewGEP;
235202375Srdivacky}
236202375Srdivacky
237202375Srdivacky
238202375Srdivacky/// isSafeAndProfitableToSinkLoad - Return true if we know that it is safe to
239202375Srdivacky/// sink the load out of the block that defines it.  This means that it must be
240202375Srdivacky/// obvious the value of the load is not changed from the point of the load to
241202375Srdivacky/// the end of the block it is in.
242202375Srdivacky///
243202375Srdivacky/// Finally, it is safe, but not profitable, to sink a load targetting a
244202375Srdivacky/// non-address-taken alloca.  Doing so will cause us to not promote the alloca
245202375Srdivacky/// to a register.
246202375Srdivackystatic bool isSafeAndProfitableToSinkLoad(LoadInst *L) {
247202375Srdivacky  BasicBlock::iterator BBI = L, E = L->getParent()->end();
248202375Srdivacky
249202375Srdivacky  for (++BBI; BBI != E; ++BBI)
250202375Srdivacky    if (BBI->mayWriteToMemory())
251202375Srdivacky      return false;
252202375Srdivacky
253202375Srdivacky  // Check for non-address taken alloca.  If not address-taken already, it isn't
254202375Srdivacky  // profitable to do this xform.
255202375Srdivacky  if (AllocaInst *AI = dyn_cast<AllocaInst>(L->getOperand(0))) {
256202375Srdivacky    bool isAddressTaken = false;
257202375Srdivacky    for (Value::use_iterator UI = AI->use_begin(), E = AI->use_end();
258202375Srdivacky         UI != E; ++UI) {
259210299Sed      User *U = *UI;
260210299Sed      if (isa<LoadInst>(U)) continue;
261210299Sed      if (StoreInst *SI = dyn_cast<StoreInst>(U)) {
262202375Srdivacky        // If storing TO the alloca, then the address isn't taken.
263202375Srdivacky        if (SI->getOperand(1) == AI) continue;
264202375Srdivacky      }
265202375Srdivacky      isAddressTaken = true;
266202375Srdivacky      break;
267202375Srdivacky    }
268202375Srdivacky
269202375Srdivacky    if (!isAddressTaken && AI->isStaticAlloca())
270202375Srdivacky      return false;
271202375Srdivacky  }
272202375Srdivacky
273202375Srdivacky  // If this load is a load from a GEP with a constant offset from an alloca,
274202375Srdivacky  // then we don't want to sink it.  In its present form, it will be
275202375Srdivacky  // load [constant stack offset].  Sinking it will cause us to have to
276202375Srdivacky  // materialize the stack addresses in each predecessor in a register only to
277202375Srdivacky  // do a shared load from register in the successor.
278202375Srdivacky  if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(L->getOperand(0)))
279202375Srdivacky    if (AllocaInst *AI = dyn_cast<AllocaInst>(GEP->getOperand(0)))
280202375Srdivacky      if (AI->isStaticAlloca() && GEP->hasAllConstantIndices())
281202375Srdivacky        return false;
282202375Srdivacky
283202375Srdivacky  return true;
284202375Srdivacky}
285202375Srdivacky
286202375SrdivackyInstruction *InstCombiner::FoldPHIArgLoadIntoPHI(PHINode &PN) {
287202375Srdivacky  LoadInst *FirstLI = cast<LoadInst>(PN.getIncomingValue(0));
288202375Srdivacky
289202375Srdivacky  // When processing loads, we need to propagate two bits of information to the
290202375Srdivacky  // sunk load: whether it is volatile, and what its alignment is.  We currently
291202375Srdivacky  // don't sink loads when some have their alignment specified and some don't.
292202375Srdivacky  // visitLoadInst will propagate an alignment onto the load when TD is around,
293202375Srdivacky  // and if TD isn't around, we can't handle the mixed case.
294202375Srdivacky  bool isVolatile = FirstLI->isVolatile();
295202375Srdivacky  unsigned LoadAlignment = FirstLI->getAlignment();
296204792Srdivacky  unsigned LoadAddrSpace = FirstLI->getPointerAddressSpace();
297202375Srdivacky
298202375Srdivacky  // We can't sink the load if the loaded value could be modified between the
299202375Srdivacky  // load and the PHI.
300202375Srdivacky  if (FirstLI->getParent() != PN.getIncomingBlock(0) ||
301202375Srdivacky      !isSafeAndProfitableToSinkLoad(FirstLI))
302202375Srdivacky    return 0;
303202375Srdivacky
304202375Srdivacky  // If the PHI is of volatile loads and the load block has multiple
305202375Srdivacky  // successors, sinking it would remove a load of the volatile value from
306202375Srdivacky  // the path through the other successor.
307202375Srdivacky  if (isVolatile &&
308202375Srdivacky      FirstLI->getParent()->getTerminator()->getNumSuccessors() != 1)
309202375Srdivacky    return 0;
310202375Srdivacky
311202375Srdivacky  // Check to see if all arguments are the same operation.
312202375Srdivacky  for (unsigned i = 1, e = PN.getNumIncomingValues(); i != e; ++i) {
313202375Srdivacky    LoadInst *LI = dyn_cast<LoadInst>(PN.getIncomingValue(i));
314202375Srdivacky    if (!LI || !LI->hasOneUse())
315202375Srdivacky      return 0;
316202375Srdivacky
317202375Srdivacky    // We can't sink the load if the loaded value could be modified between
318202375Srdivacky    // the load and the PHI.
319202375Srdivacky    if (LI->isVolatile() != isVolatile ||
320202375Srdivacky        LI->getParent() != PN.getIncomingBlock(i) ||
321204792Srdivacky        LI->getPointerAddressSpace() != LoadAddrSpace ||
322202375Srdivacky        !isSafeAndProfitableToSinkLoad(LI))
323202375Srdivacky      return 0;
324202375Srdivacky
325202375Srdivacky    // If some of the loads have an alignment specified but not all of them,
326202375Srdivacky    // we can't do the transformation.
327202375Srdivacky    if ((LoadAlignment != 0) != (LI->getAlignment() != 0))
328202375Srdivacky      return 0;
329202375Srdivacky
330202375Srdivacky    LoadAlignment = std::min(LoadAlignment, LI->getAlignment());
331202375Srdivacky
332202375Srdivacky    // If the PHI is of volatile loads and the load block has multiple
333202375Srdivacky    // successors, sinking it would remove a load of the volatile value from
334202375Srdivacky    // the path through the other successor.
335202375Srdivacky    if (isVolatile &&
336202375Srdivacky        LI->getParent()->getTerminator()->getNumSuccessors() != 1)
337202375Srdivacky      return 0;
338202375Srdivacky  }
339202375Srdivacky
340202375Srdivacky  // Okay, they are all the same operation.  Create a new PHI node of the
341202375Srdivacky  // correct type, and PHI together all of the LHS's of the instructions.
342202375Srdivacky  PHINode *NewPN = PHINode::Create(FirstLI->getOperand(0)->getType(),
343202375Srdivacky                                   PN.getName()+".in");
344202375Srdivacky  NewPN->reserveOperandSpace(PN.getNumOperands()/2);
345202375Srdivacky
346202375Srdivacky  Value *InVal = FirstLI->getOperand(0);
347202375Srdivacky  NewPN->addIncoming(InVal, PN.getIncomingBlock(0));
348202375Srdivacky
349202375Srdivacky  // Add all operands to the new PHI.
350202375Srdivacky  for (unsigned i = 1, e = PN.getNumIncomingValues(); i != e; ++i) {
351202375Srdivacky    Value *NewInVal = cast<LoadInst>(PN.getIncomingValue(i))->getOperand(0);
352202375Srdivacky    if (NewInVal != InVal)
353202375Srdivacky      InVal = 0;
354202375Srdivacky    NewPN->addIncoming(NewInVal, PN.getIncomingBlock(i));
355202375Srdivacky  }
356202375Srdivacky
357202375Srdivacky  Value *PhiVal;
358202375Srdivacky  if (InVal) {
359202375Srdivacky    // The new PHI unions all of the same values together.  This is really
360202375Srdivacky    // common, so we handle it intelligently here for compile-time speed.
361202375Srdivacky    PhiVal = InVal;
362202375Srdivacky    delete NewPN;
363202375Srdivacky  } else {
364202375Srdivacky    InsertNewInstBefore(NewPN, PN);
365202375Srdivacky    PhiVal = NewPN;
366202375Srdivacky  }
367202375Srdivacky
368202375Srdivacky  // If this was a volatile load that we are merging, make sure to loop through
369202375Srdivacky  // and mark all the input loads as non-volatile.  If we don't do this, we will
370202375Srdivacky  // insert a new volatile load and the old ones will not be deletable.
371202375Srdivacky  if (isVolatile)
372202375Srdivacky    for (unsigned i = 0, e = PN.getNumIncomingValues(); i != e; ++i)
373202375Srdivacky      cast<LoadInst>(PN.getIncomingValue(i))->setVolatile(false);
374202375Srdivacky
375202375Srdivacky  return new LoadInst(PhiVal, "", isVolatile, LoadAlignment);
376202375Srdivacky}
377202375Srdivacky
378202375Srdivacky
379202375Srdivacky
380202375Srdivacky/// FoldPHIArgOpIntoPHI - If all operands to a PHI node are the same "unary"
381202375Srdivacky/// operator and they all are only used by the PHI, PHI together their
382202375Srdivacky/// inputs, and do the operation once, to the result of the PHI.
383202375SrdivackyInstruction *InstCombiner::FoldPHIArgOpIntoPHI(PHINode &PN) {
384202375Srdivacky  Instruction *FirstInst = cast<Instruction>(PN.getIncomingValue(0));
385202375Srdivacky
386202375Srdivacky  if (isa<GetElementPtrInst>(FirstInst))
387202375Srdivacky    return FoldPHIArgGEPIntoPHI(PN);
388202375Srdivacky  if (isa<LoadInst>(FirstInst))
389202375Srdivacky    return FoldPHIArgLoadIntoPHI(PN);
390202375Srdivacky
391202375Srdivacky  // Scan the instruction, looking for input operations that can be folded away.
392202375Srdivacky  // If all input operands to the phi are the same instruction (e.g. a cast from
393202375Srdivacky  // the same type or "+42") we can pull the operation through the PHI, reducing
394202375Srdivacky  // code size and simplifying code.
395202375Srdivacky  Constant *ConstantOp = 0;
396202375Srdivacky  const Type *CastSrcTy = 0;
397218893Sdim  bool isNUW = false, isNSW = false, isExact = false;
398202375Srdivacky
399202375Srdivacky  if (isa<CastInst>(FirstInst)) {
400202375Srdivacky    CastSrcTy = FirstInst->getOperand(0)->getType();
401202375Srdivacky
402202375Srdivacky    // Be careful about transforming integer PHIs.  We don't want to pessimize
403202375Srdivacky    // the code by turning an i32 into an i1293.
404204642Srdivacky    if (PN.getType()->isIntegerTy() && CastSrcTy->isIntegerTy()) {
405202375Srdivacky      if (!ShouldChangeType(PN.getType(), CastSrcTy))
406202375Srdivacky        return 0;
407202375Srdivacky    }
408202375Srdivacky  } else if (isa<BinaryOperator>(FirstInst) || isa<CmpInst>(FirstInst)) {
409202375Srdivacky    // Can fold binop, compare or shift here if the RHS is a constant,
410202375Srdivacky    // otherwise call FoldPHIArgBinOpIntoPHI.
411202375Srdivacky    ConstantOp = dyn_cast<Constant>(FirstInst->getOperand(1));
412202375Srdivacky    if (ConstantOp == 0)
413202375Srdivacky      return FoldPHIArgBinOpIntoPHI(PN);
414218893Sdim
415218893Sdim    if (OverflowingBinaryOperator *BO =
416218893Sdim        dyn_cast<OverflowingBinaryOperator>(FirstInst)) {
417218893Sdim      isNUW = BO->hasNoUnsignedWrap();
418218893Sdim      isNSW = BO->hasNoSignedWrap();
419218893Sdim    } else if (PossiblyExactOperator *PEO =
420218893Sdim               dyn_cast<PossiblyExactOperator>(FirstInst))
421218893Sdim      isExact = PEO->isExact();
422202375Srdivacky  } else {
423202375Srdivacky    return 0;  // Cannot fold this operation.
424202375Srdivacky  }
425202375Srdivacky
426202375Srdivacky  // Check to see if all arguments are the same operation.
427202375Srdivacky  for (unsigned i = 1, e = PN.getNumIncomingValues(); i != e; ++i) {
428202375Srdivacky    Instruction *I = dyn_cast<Instruction>(PN.getIncomingValue(i));
429202375Srdivacky    if (I == 0 || !I->hasOneUse() || !I->isSameOperationAs(FirstInst))
430202375Srdivacky      return 0;
431202375Srdivacky    if (CastSrcTy) {
432202375Srdivacky      if (I->getOperand(0)->getType() != CastSrcTy)
433202375Srdivacky        return 0;  // Cast operation must match.
434202375Srdivacky    } else if (I->getOperand(1) != ConstantOp) {
435202375Srdivacky      return 0;
436202375Srdivacky    }
437218893Sdim
438218893Sdim    if (isNUW)
439218893Sdim      isNUW = cast<OverflowingBinaryOperator>(I)->hasNoUnsignedWrap();
440218893Sdim    if (isNSW)
441218893Sdim      isNSW = cast<OverflowingBinaryOperator>(I)->hasNoSignedWrap();
442218893Sdim    if (isExact)
443218893Sdim      isExact = cast<PossiblyExactOperator>(I)->isExact();
444202375Srdivacky  }
445202375Srdivacky
446202375Srdivacky  // Okay, they are all the same operation.  Create a new PHI node of the
447202375Srdivacky  // correct type, and PHI together all of the LHS's of the instructions.
448202375Srdivacky  PHINode *NewPN = PHINode::Create(FirstInst->getOperand(0)->getType(),
449202375Srdivacky                                   PN.getName()+".in");
450202375Srdivacky  NewPN->reserveOperandSpace(PN.getNumOperands()/2);
451202375Srdivacky
452202375Srdivacky  Value *InVal = FirstInst->getOperand(0);
453202375Srdivacky  NewPN->addIncoming(InVal, PN.getIncomingBlock(0));
454202375Srdivacky
455202375Srdivacky  // Add all operands to the new PHI.
456202375Srdivacky  for (unsigned i = 1, e = PN.getNumIncomingValues(); i != e; ++i) {
457202375Srdivacky    Value *NewInVal = cast<Instruction>(PN.getIncomingValue(i))->getOperand(0);
458202375Srdivacky    if (NewInVal != InVal)
459202375Srdivacky      InVal = 0;
460202375Srdivacky    NewPN->addIncoming(NewInVal, PN.getIncomingBlock(i));
461202375Srdivacky  }
462202375Srdivacky
463202375Srdivacky  Value *PhiVal;
464202375Srdivacky  if (InVal) {
465202375Srdivacky    // The new PHI unions all of the same values together.  This is really
466202375Srdivacky    // common, so we handle it intelligently here for compile-time speed.
467202375Srdivacky    PhiVal = InVal;
468202375Srdivacky    delete NewPN;
469202375Srdivacky  } else {
470202375Srdivacky    InsertNewInstBefore(NewPN, PN);
471202375Srdivacky    PhiVal = NewPN;
472202375Srdivacky  }
473202375Srdivacky
474202375Srdivacky  // Insert and return the new operation.
475202375Srdivacky  if (CastInst *FirstCI = dyn_cast<CastInst>(FirstInst))
476202375Srdivacky    return CastInst::Create(FirstCI->getOpcode(), PhiVal, PN.getType());
477202375Srdivacky
478218893Sdim  if (BinaryOperator *BinOp = dyn_cast<BinaryOperator>(FirstInst)) {
479218893Sdim    BinOp = BinaryOperator::Create(BinOp->getOpcode(), PhiVal, ConstantOp);
480218893Sdim    if (isNUW) BinOp->setHasNoUnsignedWrap();
481218893Sdim    if (isNSW) BinOp->setHasNoSignedWrap();
482218893Sdim    if (isExact) BinOp->setIsExact();
483218893Sdim    return BinOp;
484218893Sdim  }
485202375Srdivacky
486202375Srdivacky  CmpInst *CIOp = cast<CmpInst>(FirstInst);
487202375Srdivacky  return CmpInst::Create(CIOp->getOpcode(), CIOp->getPredicate(),
488202375Srdivacky                         PhiVal, ConstantOp);
489202375Srdivacky}
490202375Srdivacky
491202375Srdivacky/// DeadPHICycle - Return true if this PHI node is only used by a PHI node cycle
492202375Srdivacky/// that is dead.
493202375Srdivackystatic bool DeadPHICycle(PHINode *PN,
494202375Srdivacky                         SmallPtrSet<PHINode*, 16> &PotentiallyDeadPHIs) {
495202375Srdivacky  if (PN->use_empty()) return true;
496202375Srdivacky  if (!PN->hasOneUse()) return false;
497202375Srdivacky
498202375Srdivacky  // Remember this node, and if we find the cycle, return.
499202375Srdivacky  if (!PotentiallyDeadPHIs.insert(PN))
500202375Srdivacky    return true;
501202375Srdivacky
502202375Srdivacky  // Don't scan crazily complex things.
503202375Srdivacky  if (PotentiallyDeadPHIs.size() == 16)
504202375Srdivacky    return false;
505202375Srdivacky
506202375Srdivacky  if (PHINode *PU = dyn_cast<PHINode>(PN->use_back()))
507202375Srdivacky    return DeadPHICycle(PU, PotentiallyDeadPHIs);
508202375Srdivacky
509202375Srdivacky  return false;
510202375Srdivacky}
511202375Srdivacky
512202375Srdivacky/// PHIsEqualValue - Return true if this phi node is always equal to
513202375Srdivacky/// NonPhiInVal.  This happens with mutually cyclic phi nodes like:
514202375Srdivacky///   z = some value; x = phi (y, z); y = phi (x, z)
515202375Srdivackystatic bool PHIsEqualValue(PHINode *PN, Value *NonPhiInVal,
516202375Srdivacky                           SmallPtrSet<PHINode*, 16> &ValueEqualPHIs) {
517202375Srdivacky  // See if we already saw this PHI node.
518202375Srdivacky  if (!ValueEqualPHIs.insert(PN))
519202375Srdivacky    return true;
520202375Srdivacky
521202375Srdivacky  // Don't scan crazily complex things.
522202375Srdivacky  if (ValueEqualPHIs.size() == 16)
523202375Srdivacky    return false;
524202375Srdivacky
525202375Srdivacky  // Scan the operands to see if they are either phi nodes or are equal to
526202375Srdivacky  // the value.
527202375Srdivacky  for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) {
528202375Srdivacky    Value *Op = PN->getIncomingValue(i);
529202375Srdivacky    if (PHINode *OpPN = dyn_cast<PHINode>(Op)) {
530202375Srdivacky      if (!PHIsEqualValue(OpPN, NonPhiInVal, ValueEqualPHIs))
531202375Srdivacky        return false;
532202375Srdivacky    } else if (Op != NonPhiInVal)
533202375Srdivacky      return false;
534202375Srdivacky  }
535202375Srdivacky
536202375Srdivacky  return true;
537202375Srdivacky}
538202375Srdivacky
539202375Srdivacky
540202375Srdivackynamespace {
541202375Srdivackystruct PHIUsageRecord {
542202375Srdivacky  unsigned PHIId;     // The ID # of the PHI (something determinstic to sort on)
543202375Srdivacky  unsigned Shift;     // The amount shifted.
544202375Srdivacky  Instruction *Inst;  // The trunc instruction.
545202375Srdivacky
546202375Srdivacky  PHIUsageRecord(unsigned pn, unsigned Sh, Instruction *User)
547202375Srdivacky    : PHIId(pn), Shift(Sh), Inst(User) {}
548202375Srdivacky
549202375Srdivacky  bool operator<(const PHIUsageRecord &RHS) const {
550202375Srdivacky    if (PHIId < RHS.PHIId) return true;
551202375Srdivacky    if (PHIId > RHS.PHIId) return false;
552202375Srdivacky    if (Shift < RHS.Shift) return true;
553202375Srdivacky    if (Shift > RHS.Shift) return false;
554202375Srdivacky    return Inst->getType()->getPrimitiveSizeInBits() <
555202375Srdivacky           RHS.Inst->getType()->getPrimitiveSizeInBits();
556202375Srdivacky  }
557202375Srdivacky};
558202375Srdivacky
559202375Srdivackystruct LoweredPHIRecord {
560202375Srdivacky  PHINode *PN;        // The PHI that was lowered.
561202375Srdivacky  unsigned Shift;     // The amount shifted.
562202375Srdivacky  unsigned Width;     // The width extracted.
563202375Srdivacky
564202375Srdivacky  LoweredPHIRecord(PHINode *pn, unsigned Sh, const Type *Ty)
565202375Srdivacky    : PN(pn), Shift(Sh), Width(Ty->getPrimitiveSizeInBits()) {}
566202375Srdivacky
567202375Srdivacky  // Ctor form used by DenseMap.
568202375Srdivacky  LoweredPHIRecord(PHINode *pn, unsigned Sh)
569202375Srdivacky    : PN(pn), Shift(Sh), Width(0) {}
570202375Srdivacky};
571202375Srdivacky}
572202375Srdivacky
573202375Srdivackynamespace llvm {
574202375Srdivacky  template<>
575202375Srdivacky  struct DenseMapInfo<LoweredPHIRecord> {
576202375Srdivacky    static inline LoweredPHIRecord getEmptyKey() {
577202375Srdivacky      return LoweredPHIRecord(0, 0);
578202375Srdivacky    }
579202375Srdivacky    static inline LoweredPHIRecord getTombstoneKey() {
580202375Srdivacky      return LoweredPHIRecord(0, 1);
581202375Srdivacky    }
582202375Srdivacky    static unsigned getHashValue(const LoweredPHIRecord &Val) {
583202375Srdivacky      return DenseMapInfo<PHINode*>::getHashValue(Val.PN) ^ (Val.Shift>>3) ^
584202375Srdivacky             (Val.Width>>3);
585202375Srdivacky    }
586202375Srdivacky    static bool isEqual(const LoweredPHIRecord &LHS,
587202375Srdivacky                        const LoweredPHIRecord &RHS) {
588202375Srdivacky      return LHS.PN == RHS.PN && LHS.Shift == RHS.Shift &&
589202375Srdivacky             LHS.Width == RHS.Width;
590202375Srdivacky    }
591202375Srdivacky  };
592202375Srdivacky  template <>
593202375Srdivacky  struct isPodLike<LoweredPHIRecord> { static const bool value = true; };
594202375Srdivacky}
595202375Srdivacky
596202375Srdivacky
597202375Srdivacky/// SliceUpIllegalIntegerPHI - This is an integer PHI and we know that it has an
598202375Srdivacky/// illegal type: see if it is only used by trunc or trunc(lshr) operations.  If
599202375Srdivacky/// so, we split the PHI into the various pieces being extracted.  This sort of
600202375Srdivacky/// thing is introduced when SROA promotes an aggregate to large integer values.
601202375Srdivacky///
602202375Srdivacky/// TODO: The user of the trunc may be an bitcast to float/double/vector or an
603202375Srdivacky/// inttoptr.  We should produce new PHIs in the right type.
604202375Srdivacky///
605202375SrdivackyInstruction *InstCombiner::SliceUpIllegalIntegerPHI(PHINode &FirstPhi) {
606202375Srdivacky  // PHIUsers - Keep track of all of the truncated values extracted from a set
607202375Srdivacky  // of PHIs, along with their offset.  These are the things we want to rewrite.
608202375Srdivacky  SmallVector<PHIUsageRecord, 16> PHIUsers;
609202375Srdivacky
610202375Srdivacky  // PHIs are often mutually cyclic, so we keep track of a whole set of PHI
611202375Srdivacky  // nodes which are extracted from. PHIsToSlice is a set we use to avoid
612202375Srdivacky  // revisiting PHIs, PHIsInspected is a ordered list of PHIs that we need to
613202375Srdivacky  // check the uses of (to ensure they are all extracts).
614202375Srdivacky  SmallVector<PHINode*, 8> PHIsToSlice;
615202375Srdivacky  SmallPtrSet<PHINode*, 8> PHIsInspected;
616202375Srdivacky
617202375Srdivacky  PHIsToSlice.push_back(&FirstPhi);
618202375Srdivacky  PHIsInspected.insert(&FirstPhi);
619202375Srdivacky
620202375Srdivacky  for (unsigned PHIId = 0; PHIId != PHIsToSlice.size(); ++PHIId) {
621202375Srdivacky    PHINode *PN = PHIsToSlice[PHIId];
622202375Srdivacky
623202375Srdivacky    // Scan the input list of the PHI.  If any input is an invoke, and if the
624202375Srdivacky    // input is defined in the predecessor, then we won't be split the critical
625202375Srdivacky    // edge which is required to insert a truncate.  Because of this, we have to
626202375Srdivacky    // bail out.
627202375Srdivacky    for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) {
628202375Srdivacky      InvokeInst *II = dyn_cast<InvokeInst>(PN->getIncomingValue(i));
629202375Srdivacky      if (II == 0) continue;
630202375Srdivacky      if (II->getParent() != PN->getIncomingBlock(i))
631202375Srdivacky        continue;
632202375Srdivacky
633202375Srdivacky      // If we have a phi, and if it's directly in the predecessor, then we have
634202375Srdivacky      // a critical edge where we need to put the truncate.  Since we can't
635202375Srdivacky      // split the edge in instcombine, we have to bail out.
636202375Srdivacky      return 0;
637202375Srdivacky    }
638202375Srdivacky
639202375Srdivacky
640202375Srdivacky    for (Value::use_iterator UI = PN->use_begin(), E = PN->use_end();
641202375Srdivacky         UI != E; ++UI) {
642202375Srdivacky      Instruction *User = cast<Instruction>(*UI);
643202375Srdivacky
644202375Srdivacky      // If the user is a PHI, inspect its uses recursively.
645202375Srdivacky      if (PHINode *UserPN = dyn_cast<PHINode>(User)) {
646202375Srdivacky        if (PHIsInspected.insert(UserPN))
647202375Srdivacky          PHIsToSlice.push_back(UserPN);
648202375Srdivacky        continue;
649202375Srdivacky      }
650202375Srdivacky
651202375Srdivacky      // Truncates are always ok.
652202375Srdivacky      if (isa<TruncInst>(User)) {
653202375Srdivacky        PHIUsers.push_back(PHIUsageRecord(PHIId, 0, User));
654202375Srdivacky        continue;
655202375Srdivacky      }
656202375Srdivacky
657202375Srdivacky      // Otherwise it must be a lshr which can only be used by one trunc.
658202375Srdivacky      if (User->getOpcode() != Instruction::LShr ||
659202375Srdivacky          !User->hasOneUse() || !isa<TruncInst>(User->use_back()) ||
660202375Srdivacky          !isa<ConstantInt>(User->getOperand(1)))
661202375Srdivacky        return 0;
662202375Srdivacky
663202375Srdivacky      unsigned Shift = cast<ConstantInt>(User->getOperand(1))->getZExtValue();
664202375Srdivacky      PHIUsers.push_back(PHIUsageRecord(PHIId, Shift, User->use_back()));
665202375Srdivacky    }
666202375Srdivacky  }
667202375Srdivacky
668202375Srdivacky  // If we have no users, they must be all self uses, just nuke the PHI.
669202375Srdivacky  if (PHIUsers.empty())
670202375Srdivacky    return ReplaceInstUsesWith(FirstPhi, UndefValue::get(FirstPhi.getType()));
671202375Srdivacky
672202375Srdivacky  // If this phi node is transformable, create new PHIs for all the pieces
673202375Srdivacky  // extracted out of it.  First, sort the users by their offset and size.
674202375Srdivacky  array_pod_sort(PHIUsers.begin(), PHIUsers.end());
675202375Srdivacky
676202375Srdivacky  DEBUG(errs() << "SLICING UP PHI: " << FirstPhi << '\n';
677202375Srdivacky            for (unsigned i = 1, e = PHIsToSlice.size(); i != e; ++i)
678202375Srdivacky              errs() << "AND USER PHI #" << i << ": " << *PHIsToSlice[i] <<'\n';
679202375Srdivacky        );
680202375Srdivacky
681202375Srdivacky  // PredValues - This is a temporary used when rewriting PHI nodes.  It is
682202375Srdivacky  // hoisted out here to avoid construction/destruction thrashing.
683202375Srdivacky  DenseMap<BasicBlock*, Value*> PredValues;
684202375Srdivacky
685202375Srdivacky  // ExtractedVals - Each new PHI we introduce is saved here so we don't
686202375Srdivacky  // introduce redundant PHIs.
687202375Srdivacky  DenseMap<LoweredPHIRecord, PHINode*> ExtractedVals;
688202375Srdivacky
689202375Srdivacky  for (unsigned UserI = 0, UserE = PHIUsers.size(); UserI != UserE; ++UserI) {
690202375Srdivacky    unsigned PHIId = PHIUsers[UserI].PHIId;
691202375Srdivacky    PHINode *PN = PHIsToSlice[PHIId];
692202375Srdivacky    unsigned Offset = PHIUsers[UserI].Shift;
693202375Srdivacky    const Type *Ty = PHIUsers[UserI].Inst->getType();
694202375Srdivacky
695202375Srdivacky    PHINode *EltPHI;
696202375Srdivacky
697202375Srdivacky    // If we've already lowered a user like this, reuse the previously lowered
698202375Srdivacky    // value.
699202375Srdivacky    if ((EltPHI = ExtractedVals[LoweredPHIRecord(PN, Offset, Ty)]) == 0) {
700202375Srdivacky
701202375Srdivacky      // Otherwise, Create the new PHI node for this user.
702202375Srdivacky      EltPHI = PHINode::Create(Ty, PN->getName()+".off"+Twine(Offset), PN);
703202375Srdivacky      assert(EltPHI->getType() != PN->getType() &&
704202375Srdivacky             "Truncate didn't shrink phi?");
705202375Srdivacky
706202375Srdivacky      for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) {
707202375Srdivacky        BasicBlock *Pred = PN->getIncomingBlock(i);
708202375Srdivacky        Value *&PredVal = PredValues[Pred];
709202375Srdivacky
710202375Srdivacky        // If we already have a value for this predecessor, reuse it.
711202375Srdivacky        if (PredVal) {
712202375Srdivacky          EltPHI->addIncoming(PredVal, Pred);
713202375Srdivacky          continue;
714202375Srdivacky        }
715202375Srdivacky
716202375Srdivacky        // Handle the PHI self-reuse case.
717202375Srdivacky        Value *InVal = PN->getIncomingValue(i);
718202375Srdivacky        if (InVal == PN) {
719202375Srdivacky          PredVal = EltPHI;
720202375Srdivacky          EltPHI->addIncoming(PredVal, Pred);
721202375Srdivacky          continue;
722202375Srdivacky        }
723202375Srdivacky
724202375Srdivacky        if (PHINode *InPHI = dyn_cast<PHINode>(PN)) {
725202375Srdivacky          // If the incoming value was a PHI, and if it was one of the PHIs we
726202375Srdivacky          // already rewrote it, just use the lowered value.
727202375Srdivacky          if (Value *Res = ExtractedVals[LoweredPHIRecord(InPHI, Offset, Ty)]) {
728202375Srdivacky            PredVal = Res;
729202375Srdivacky            EltPHI->addIncoming(PredVal, Pred);
730202375Srdivacky            continue;
731202375Srdivacky          }
732202375Srdivacky        }
733202375Srdivacky
734202375Srdivacky        // Otherwise, do an extract in the predecessor.
735202375Srdivacky        Builder->SetInsertPoint(Pred, Pred->getTerminator());
736202375Srdivacky        Value *Res = InVal;
737202375Srdivacky        if (Offset)
738202375Srdivacky          Res = Builder->CreateLShr(Res, ConstantInt::get(InVal->getType(),
739202375Srdivacky                                                          Offset), "extract");
740202375Srdivacky        Res = Builder->CreateTrunc(Res, Ty, "extract.t");
741202375Srdivacky        PredVal = Res;
742202375Srdivacky        EltPHI->addIncoming(Res, Pred);
743202375Srdivacky
744202375Srdivacky        // If the incoming value was a PHI, and if it was one of the PHIs we are
745202375Srdivacky        // rewriting, we will ultimately delete the code we inserted.  This
746202375Srdivacky        // means we need to revisit that PHI to make sure we extract out the
747202375Srdivacky        // needed piece.
748202375Srdivacky        if (PHINode *OldInVal = dyn_cast<PHINode>(PN->getIncomingValue(i)))
749202375Srdivacky          if (PHIsInspected.count(OldInVal)) {
750202375Srdivacky            unsigned RefPHIId = std::find(PHIsToSlice.begin(),PHIsToSlice.end(),
751202375Srdivacky                                          OldInVal)-PHIsToSlice.begin();
752202375Srdivacky            PHIUsers.push_back(PHIUsageRecord(RefPHIId, Offset,
753202375Srdivacky                                              cast<Instruction>(Res)));
754202375Srdivacky            ++UserE;
755202375Srdivacky          }
756202375Srdivacky      }
757202375Srdivacky      PredValues.clear();
758202375Srdivacky
759202375Srdivacky      DEBUG(errs() << "  Made element PHI for offset " << Offset << ": "
760202375Srdivacky                   << *EltPHI << '\n');
761202375Srdivacky      ExtractedVals[LoweredPHIRecord(PN, Offset, Ty)] = EltPHI;
762202375Srdivacky    }
763202375Srdivacky
764202375Srdivacky    // Replace the use of this piece with the PHI node.
765202375Srdivacky    ReplaceInstUsesWith(*PHIUsers[UserI].Inst, EltPHI);
766202375Srdivacky  }
767202375Srdivacky
768202375Srdivacky  // Replace all the remaining uses of the PHI nodes (self uses and the lshrs)
769202375Srdivacky  // with undefs.
770202375Srdivacky  Value *Undef = UndefValue::get(FirstPhi.getType());
771202375Srdivacky  for (unsigned i = 1, e = PHIsToSlice.size(); i != e; ++i)
772202375Srdivacky    ReplaceInstUsesWith(*PHIsToSlice[i], Undef);
773202375Srdivacky  return ReplaceInstUsesWith(FirstPhi, Undef);
774202375Srdivacky}
775202375Srdivacky
776202375Srdivacky// PHINode simplification
777202375Srdivacky//
778202375SrdivackyInstruction *InstCombiner::visitPHINode(PHINode &PN) {
779202375Srdivacky  // If LCSSA is around, don't mess with Phi nodes
780202375Srdivacky  if (MustPreserveLCSSA) return 0;
781218893Sdim
782218893Sdim  if (Value *V = SimplifyInstruction(&PN, TD))
783202375Srdivacky    return ReplaceInstUsesWith(PN, V);
784202375Srdivacky
785202375Srdivacky  // If all PHI operands are the same operation, pull them through the PHI,
786202375Srdivacky  // reducing code size.
787202375Srdivacky  if (isa<Instruction>(PN.getIncomingValue(0)) &&
788202375Srdivacky      isa<Instruction>(PN.getIncomingValue(1)) &&
789202375Srdivacky      cast<Instruction>(PN.getIncomingValue(0))->getOpcode() ==
790202375Srdivacky      cast<Instruction>(PN.getIncomingValue(1))->getOpcode() &&
791202375Srdivacky      // FIXME: The hasOneUse check will fail for PHIs that use the value more
792202375Srdivacky      // than themselves more than once.
793202375Srdivacky      PN.getIncomingValue(0)->hasOneUse())
794202375Srdivacky    if (Instruction *Result = FoldPHIArgOpIntoPHI(PN))
795202375Srdivacky      return Result;
796202375Srdivacky
797202375Srdivacky  // If this is a trivial cycle in the PHI node graph, remove it.  Basically, if
798202375Srdivacky  // this PHI only has a single use (a PHI), and if that PHI only has one use (a
799202375Srdivacky  // PHI)... break the cycle.
800202375Srdivacky  if (PN.hasOneUse()) {
801202375Srdivacky    Instruction *PHIUser = cast<Instruction>(PN.use_back());
802202375Srdivacky    if (PHINode *PU = dyn_cast<PHINode>(PHIUser)) {
803202375Srdivacky      SmallPtrSet<PHINode*, 16> PotentiallyDeadPHIs;
804202375Srdivacky      PotentiallyDeadPHIs.insert(&PN);
805202375Srdivacky      if (DeadPHICycle(PU, PotentiallyDeadPHIs))
806202375Srdivacky        return ReplaceInstUsesWith(PN, UndefValue::get(PN.getType()));
807202375Srdivacky    }
808202375Srdivacky
809202375Srdivacky    // If this phi has a single use, and if that use just computes a value for
810202375Srdivacky    // the next iteration of a loop, delete the phi.  This occurs with unused
811202375Srdivacky    // induction variables, e.g. "for (int j = 0; ; ++j);".  Detecting this
812202375Srdivacky    // common case here is good because the only other things that catch this
813202375Srdivacky    // are induction variable analysis (sometimes) and ADCE, which is only run
814202375Srdivacky    // late.
815202375Srdivacky    if (PHIUser->hasOneUse() &&
816202375Srdivacky        (isa<BinaryOperator>(PHIUser) || isa<GetElementPtrInst>(PHIUser)) &&
817202375Srdivacky        PHIUser->use_back() == &PN) {
818202375Srdivacky      return ReplaceInstUsesWith(PN, UndefValue::get(PN.getType()));
819202375Srdivacky    }
820202375Srdivacky  }
821202375Srdivacky
822202375Srdivacky  // We sometimes end up with phi cycles that non-obviously end up being the
823202375Srdivacky  // same value, for example:
824202375Srdivacky  //   z = some value; x = phi (y, z); y = phi (x, z)
825202375Srdivacky  // where the phi nodes don't necessarily need to be in the same block.  Do a
826202375Srdivacky  // quick check to see if the PHI node only contains a single non-phi value, if
827202375Srdivacky  // so, scan to see if the phi cycle is actually equal to that value.
828202375Srdivacky  {
829202375Srdivacky    unsigned InValNo = 0, NumOperandVals = PN.getNumIncomingValues();
830202375Srdivacky    // Scan for the first non-phi operand.
831202375Srdivacky    while (InValNo != NumOperandVals &&
832202375Srdivacky           isa<PHINode>(PN.getIncomingValue(InValNo)))
833202375Srdivacky      ++InValNo;
834202375Srdivacky
835202375Srdivacky    if (InValNo != NumOperandVals) {
836202375Srdivacky      Value *NonPhiInVal = PN.getOperand(InValNo);
837202375Srdivacky
838202375Srdivacky      // Scan the rest of the operands to see if there are any conflicts, if so
839202375Srdivacky      // there is no need to recursively scan other phis.
840202375Srdivacky      for (++InValNo; InValNo != NumOperandVals; ++InValNo) {
841202375Srdivacky        Value *OpVal = PN.getIncomingValue(InValNo);
842202375Srdivacky        if (OpVal != NonPhiInVal && !isa<PHINode>(OpVal))
843202375Srdivacky          break;
844202375Srdivacky      }
845202375Srdivacky
846202375Srdivacky      // If we scanned over all operands, then we have one unique value plus
847202375Srdivacky      // phi values.  Scan PHI nodes to see if they all merge in each other or
848202375Srdivacky      // the value.
849202375Srdivacky      if (InValNo == NumOperandVals) {
850202375Srdivacky        SmallPtrSet<PHINode*, 16> ValueEqualPHIs;
851202375Srdivacky        if (PHIsEqualValue(&PN, NonPhiInVal, ValueEqualPHIs))
852202375Srdivacky          return ReplaceInstUsesWith(PN, NonPhiInVal);
853202375Srdivacky      }
854202375Srdivacky    }
855202375Srdivacky  }
856202375Srdivacky
857202375Srdivacky  // If there are multiple PHIs, sort their operands so that they all list
858202375Srdivacky  // the blocks in the same order. This will help identical PHIs be eliminated
859202375Srdivacky  // by other passes. Other passes shouldn't depend on this for correctness
860202375Srdivacky  // however.
861202375Srdivacky  PHINode *FirstPN = cast<PHINode>(PN.getParent()->begin());
862202375Srdivacky  if (&PN != FirstPN)
863202375Srdivacky    for (unsigned i = 0, e = FirstPN->getNumIncomingValues(); i != e; ++i) {
864202375Srdivacky      BasicBlock *BBA = PN.getIncomingBlock(i);
865202375Srdivacky      BasicBlock *BBB = FirstPN->getIncomingBlock(i);
866202375Srdivacky      if (BBA != BBB) {
867202375Srdivacky        Value *VA = PN.getIncomingValue(i);
868202375Srdivacky        unsigned j = PN.getBasicBlockIndex(BBB);
869202375Srdivacky        Value *VB = PN.getIncomingValue(j);
870202375Srdivacky        PN.setIncomingBlock(i, BBB);
871202375Srdivacky        PN.setIncomingValue(i, VB);
872202375Srdivacky        PN.setIncomingBlock(j, BBA);
873202375Srdivacky        PN.setIncomingValue(j, VA);
874202375Srdivacky        // NOTE: Instcombine normally would want us to "return &PN" if we
875202375Srdivacky        // modified any of the operands of an instruction.  However, since we
876202375Srdivacky        // aren't adding or removing uses (just rearranging them) we don't do
877202375Srdivacky        // this in this case.
878202375Srdivacky      }
879202375Srdivacky    }
880202375Srdivacky
881202375Srdivacky  // If this is an integer PHI and we know that it has an illegal type, see if
882202375Srdivacky  // it is only used by trunc or trunc(lshr) operations.  If so, we split the
883202375Srdivacky  // PHI into the various pieces being extracted.  This sort of thing is
884202375Srdivacky  // introduced when SROA promotes an aggregate to a single large integer type.
885204642Srdivacky  if (PN.getType()->isIntegerTy() && TD &&
886202375Srdivacky      !TD->isLegalInteger(PN.getType()->getPrimitiveSizeInBits()))
887202375Srdivacky    if (Instruction *Res = SliceUpIllegalIntegerPHI(PN))
888202375Srdivacky      return Res;
889202375Srdivacky
890202375Srdivacky  return 0;
891202375Srdivacky}
892