Fix indentation.
[oota-llvm.git] / lib / Transforms / InstCombine / InstCombinePHI.cpp
1 //===- InstCombinePHI.cpp -------------------------------------------------===//
2 //
3 //                     The LLVM Compiler Infrastructure
4 //
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
7 //
8 //===----------------------------------------------------------------------===//
9 //
10 // This file implements the visitPHINode function.
11 //
12 //===----------------------------------------------------------------------===//
13
14 #include "InstCombine.h"
15 #include "llvm/Target/TargetData.h"
16 #include "llvm/ADT/SmallPtrSet.h"
17 #include "llvm/ADT/STLExtras.h"
18 using namespace llvm;
19
20 /// FoldPHIArgBinOpIntoPHI - If we have something like phi [add (a,b), add(a,c)]
21 /// and if a/b/c and the add's all have a single use, turn this into a phi
22 /// and a single binop.
23 Instruction *InstCombiner::FoldPHIArgBinOpIntoPHI(PHINode &PN) {
24   Instruction *FirstInst = cast<Instruction>(PN.getIncomingValue(0));
25   assert(isa<BinaryOperator>(FirstInst) || isa<CmpInst>(FirstInst));
26   unsigned Opc = FirstInst->getOpcode();
27   Value *LHSVal = FirstInst->getOperand(0);
28   Value *RHSVal = FirstInst->getOperand(1);
29     
30   const Type *LHSType = LHSVal->getType();
31   const Type *RHSType = RHSVal->getType();
32   
33   // Scan to see if all operands are the same opcode, and all have one use.
34   for (unsigned i = 1; i != PN.getNumIncomingValues(); ++i) {
35     Instruction *I = dyn_cast<Instruction>(PN.getIncomingValue(i));
36     if (!I || I->getOpcode() != Opc || !I->hasOneUse() ||
37         // Verify type of the LHS matches so we don't fold cmp's of different
38         // types or GEP's with different index types.
39         I->getOperand(0)->getType() != LHSType ||
40         I->getOperand(1)->getType() != RHSType)
41       return 0;
42
43     // If they are CmpInst instructions, check their predicates
44     if (Opc == Instruction::ICmp || Opc == Instruction::FCmp)
45       if (cast<CmpInst>(I)->getPredicate() !=
46           cast<CmpInst>(FirstInst)->getPredicate())
47         return 0;
48     
49     // Keep track of which operand needs a phi node.
50     if (I->getOperand(0) != LHSVal) LHSVal = 0;
51     if (I->getOperand(1) != RHSVal) RHSVal = 0;
52   }
53
54   // If both LHS and RHS would need a PHI, don't do this transformation,
55   // because it would increase the number of PHIs entering the block,
56   // which leads to higher register pressure. This is especially
57   // bad when the PHIs are in the header of a loop.
58   if (!LHSVal && !RHSVal)
59     return 0;
60   
61   // Otherwise, this is safe to transform!
62   
63   Value *InLHS = FirstInst->getOperand(0);
64   Value *InRHS = FirstInst->getOperand(1);
65   PHINode *NewLHS = 0, *NewRHS = 0;
66   if (LHSVal == 0) {
67     NewLHS = PHINode::Create(LHSType,
68                              FirstInst->getOperand(0)->getName() + ".pn");
69     NewLHS->reserveOperandSpace(PN.getNumOperands()/2);
70     NewLHS->addIncoming(InLHS, PN.getIncomingBlock(0));
71     InsertNewInstBefore(NewLHS, PN);
72     LHSVal = NewLHS;
73   }
74   
75   if (RHSVal == 0) {
76     NewRHS = PHINode::Create(RHSType,
77                              FirstInst->getOperand(1)->getName() + ".pn");
78     NewRHS->reserveOperandSpace(PN.getNumOperands()/2);
79     NewRHS->addIncoming(InRHS, PN.getIncomingBlock(0));
80     InsertNewInstBefore(NewRHS, PN);
81     RHSVal = NewRHS;
82   }
83   
84   // Add all operands to the new PHIs.
85   if (NewLHS || NewRHS) {
86     for (unsigned i = 1, e = PN.getNumIncomingValues(); i != e; ++i) {
87       Instruction *InInst = cast<Instruction>(PN.getIncomingValue(i));
88       if (NewLHS) {
89         Value *NewInLHS = InInst->getOperand(0);
90         NewLHS->addIncoming(NewInLHS, PN.getIncomingBlock(i));
91       }
92       if (NewRHS) {
93         Value *NewInRHS = InInst->getOperand(1);
94         NewRHS->addIncoming(NewInRHS, PN.getIncomingBlock(i));
95       }
96     }
97   }
98     
99   if (BinaryOperator *BinOp = dyn_cast<BinaryOperator>(FirstInst))
100     return BinaryOperator::Create(BinOp->getOpcode(), LHSVal, RHSVal);
101   CmpInst *CIOp = cast<CmpInst>(FirstInst);
102   return CmpInst::Create(CIOp->getOpcode(), CIOp->getPredicate(),
103                          LHSVal, RHSVal);
104 }
105
106 Instruction *InstCombiner::FoldPHIArgGEPIntoPHI(PHINode &PN) {
107   GetElementPtrInst *FirstInst =cast<GetElementPtrInst>(PN.getIncomingValue(0));
108   
109   SmallVector<Value*, 16> FixedOperands(FirstInst->op_begin(), 
110                                         FirstInst->op_end());
111   // This is true if all GEP bases are allocas and if all indices into them are
112   // constants.
113   bool AllBasePointersAreAllocas = true;
114
115   // We don't want to replace this phi if the replacement would require
116   // more than one phi, which leads to higher register pressure. This is
117   // especially bad when the PHIs are in the header of a loop.
118   bool NeededPhi = false;
119   
120   // Scan to see if all operands are the same opcode, and all have one use.
121   for (unsigned i = 1; i != PN.getNumIncomingValues(); ++i) {
122     GetElementPtrInst *GEP= dyn_cast<GetElementPtrInst>(PN.getIncomingValue(i));
123     if (!GEP || !GEP->hasOneUse() || GEP->getType() != FirstInst->getType() ||
124       GEP->getNumOperands() != FirstInst->getNumOperands())
125       return 0;
126
127     // Keep track of whether or not all GEPs are of alloca pointers.
128     if (AllBasePointersAreAllocas &&
129         (!isa<AllocaInst>(GEP->getOperand(0)) ||
130          !GEP->hasAllConstantIndices()))
131       AllBasePointersAreAllocas = false;
132     
133     // Compare the operand lists.
134     for (unsigned op = 0, e = FirstInst->getNumOperands(); op != e; ++op) {
135       if (FirstInst->getOperand(op) == GEP->getOperand(op))
136         continue;
137       
138       // Don't merge two GEPs when two operands differ (introducing phi nodes)
139       // if one of the PHIs has a constant for the index.  The index may be
140       // substantially cheaper to compute for the constants, so making it a
141       // variable index could pessimize the path.  This also handles the case
142       // for struct indices, which must always be constant.
143       if (isa<ConstantInt>(FirstInst->getOperand(op)) ||
144           isa<ConstantInt>(GEP->getOperand(op)))
145         return 0;
146       
147       if (FirstInst->getOperand(op)->getType() !=GEP->getOperand(op)->getType())
148         return 0;
149
150       // If we already needed a PHI for an earlier operand, and another operand
151       // also requires a PHI, we'd be introducing more PHIs than we're
152       // eliminating, which increases register pressure on entry to the PHI's
153       // block.
154       if (NeededPhi)
155         return 0;
156
157       FixedOperands[op] = 0;  // Needs a PHI.
158       NeededPhi = true;
159     }
160   }
161   
162   // If all of the base pointers of the PHI'd GEPs are from allocas, don't
163   // bother doing this transformation.  At best, this will just save a bit of
164   // offset calculation, but all the predecessors will have to materialize the
165   // stack address into a register anyway.  We'd actually rather *clone* the
166   // load up into the predecessors so that we have a load of a gep of an alloca,
167   // which can usually all be folded into the load.
168   if (AllBasePointersAreAllocas)
169     return 0;
170   
171   // Otherwise, this is safe to transform.  Insert PHI nodes for each operand
172   // that is variable.
173   SmallVector<PHINode*, 16> OperandPhis(FixedOperands.size());
174   
175   bool HasAnyPHIs = false;
176   for (unsigned i = 0, e = FixedOperands.size(); i != e; ++i) {
177     if (FixedOperands[i]) continue;  // operand doesn't need a phi.
178     Value *FirstOp = FirstInst->getOperand(i);
179     PHINode *NewPN = PHINode::Create(FirstOp->getType(),
180                                      FirstOp->getName()+".pn");
181     InsertNewInstBefore(NewPN, PN);
182     
183     NewPN->reserveOperandSpace(e);
184     NewPN->addIncoming(FirstOp, PN.getIncomingBlock(0));
185     OperandPhis[i] = NewPN;
186     FixedOperands[i] = NewPN;
187     HasAnyPHIs = true;
188   }
189
190   
191   // Add all operands to the new PHIs.
192   if (HasAnyPHIs) {
193     for (unsigned i = 1, e = PN.getNumIncomingValues(); i != e; ++i) {
194       GetElementPtrInst *InGEP =cast<GetElementPtrInst>(PN.getIncomingValue(i));
195       BasicBlock *InBB = PN.getIncomingBlock(i);
196       
197       for (unsigned op = 0, e = OperandPhis.size(); op != e; ++op)
198         if (PHINode *OpPhi = OperandPhis[op])
199           OpPhi->addIncoming(InGEP->getOperand(op), InBB);
200     }
201   }
202   
203   Value *Base = FixedOperands[0];
204   return cast<GEPOperator>(FirstInst)->isInBounds() ?
205     GetElementPtrInst::CreateInBounds(Base, FixedOperands.begin()+1,
206                                       FixedOperands.end()) :
207     GetElementPtrInst::Create(Base, FixedOperands.begin()+1,
208                               FixedOperands.end());
209 }
210
211
212 /// isSafeAndProfitableToSinkLoad - Return true if we know that it is safe to
213 /// sink the load out of the block that defines it.  This means that it must be
214 /// obvious the value of the load is not changed from the point of the load to
215 /// the end of the block it is in.
216 ///
217 /// Finally, it is safe, but not profitable, to sink a load targetting a
218 /// non-address-taken alloca.  Doing so will cause us to not promote the alloca
219 /// to a register.
220 static bool isSafeAndProfitableToSinkLoad(LoadInst *L) {
221   BasicBlock::iterator BBI = L, E = L->getParent()->end();
222   
223   for (++BBI; BBI != E; ++BBI)
224     if (BBI->mayWriteToMemory())
225       return false;
226   
227   // Check for non-address taken alloca.  If not address-taken already, it isn't
228   // profitable to do this xform.
229   if (AllocaInst *AI = dyn_cast<AllocaInst>(L->getOperand(0))) {
230     bool isAddressTaken = false;
231     for (Value::use_iterator UI = AI->use_begin(), E = AI->use_end();
232          UI != E; ++UI) {
233       if (isa<LoadInst>(UI)) continue;
234       if (StoreInst *SI = dyn_cast<StoreInst>(*UI)) {
235         // If storing TO the alloca, then the address isn't taken.
236         if (SI->getOperand(1) == AI) continue;
237       }
238       isAddressTaken = true;
239       break;
240     }
241     
242     if (!isAddressTaken && AI->isStaticAlloca())
243       return false;
244   }
245   
246   // If this load is a load from a GEP with a constant offset from an alloca,
247   // then we don't want to sink it.  In its present form, it will be
248   // load [constant stack offset].  Sinking it will cause us to have to
249   // materialize the stack addresses in each predecessor in a register only to
250   // do a shared load from register in the successor.
251   if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(L->getOperand(0)))
252     if (AllocaInst *AI = dyn_cast<AllocaInst>(GEP->getOperand(0)))
253       if (AI->isStaticAlloca() && GEP->hasAllConstantIndices())
254         return false;
255   
256   return true;
257 }
258
259 Instruction *InstCombiner::FoldPHIArgLoadIntoPHI(PHINode &PN) {
260   LoadInst *FirstLI = cast<LoadInst>(PN.getIncomingValue(0));
261   
262   // When processing loads, we need to propagate two bits of information to the
263   // sunk load: whether it is volatile, and what its alignment is.  We currently
264   // don't sink loads when some have their alignment specified and some don't.
265   // visitLoadInst will propagate an alignment onto the load when TD is around,
266   // and if TD isn't around, we can't handle the mixed case.
267   bool isVolatile = FirstLI->isVolatile();
268   unsigned LoadAlignment = FirstLI->getAlignment();
269   
270   // We can't sink the load if the loaded value could be modified between the
271   // load and the PHI.
272   if (FirstLI->getParent() != PN.getIncomingBlock(0) ||
273       !isSafeAndProfitableToSinkLoad(FirstLI))
274     return 0;
275   
276   // If the PHI is of volatile loads and the load block has multiple
277   // successors, sinking it would remove a load of the volatile value from
278   // the path through the other successor.
279   if (isVolatile && 
280       FirstLI->getParent()->getTerminator()->getNumSuccessors() != 1)
281     return 0;
282   
283   // Check to see if all arguments are the same operation.
284   for (unsigned i = 1, e = PN.getNumIncomingValues(); i != e; ++i) {
285     LoadInst *LI = dyn_cast<LoadInst>(PN.getIncomingValue(i));
286     if (!LI || !LI->hasOneUse())
287       return 0;
288     
289     // We can't sink the load if the loaded value could be modified between 
290     // the load and the PHI.
291     if (LI->isVolatile() != isVolatile ||
292         LI->getParent() != PN.getIncomingBlock(i) ||
293         !isSafeAndProfitableToSinkLoad(LI))
294       return 0;
295       
296     // If some of the loads have an alignment specified but not all of them,
297     // we can't do the transformation.
298     if ((LoadAlignment != 0) != (LI->getAlignment() != 0))
299       return 0;
300     
301     LoadAlignment = std::min(LoadAlignment, LI->getAlignment());
302     
303     // If the PHI is of volatile loads and the load block has multiple
304     // successors, sinking it would remove a load of the volatile value from
305     // the path through the other successor.
306     if (isVolatile &&
307         LI->getParent()->getTerminator()->getNumSuccessors() != 1)
308       return 0;
309   }
310   
311   // Okay, they are all the same operation.  Create a new PHI node of the
312   // correct type, and PHI together all of the LHS's of the instructions.
313   PHINode *NewPN = PHINode::Create(FirstLI->getOperand(0)->getType(),
314                                    PN.getName()+".in");
315   NewPN->reserveOperandSpace(PN.getNumOperands()/2);
316   
317   Value *InVal = FirstLI->getOperand(0);
318   NewPN->addIncoming(InVal, PN.getIncomingBlock(0));
319   
320   // Add all operands to the new PHI.
321   for (unsigned i = 1, e = PN.getNumIncomingValues(); i != e; ++i) {
322     Value *NewInVal = cast<LoadInst>(PN.getIncomingValue(i))->getOperand(0);
323     if (NewInVal != InVal)
324       InVal = 0;
325     NewPN->addIncoming(NewInVal, PN.getIncomingBlock(i));
326   }
327   
328   Value *PhiVal;
329   if (InVal) {
330     // The new PHI unions all of the same values together.  This is really
331     // common, so we handle it intelligently here for compile-time speed.
332     PhiVal = InVal;
333     delete NewPN;
334   } else {
335     InsertNewInstBefore(NewPN, PN);
336     PhiVal = NewPN;
337   }
338   
339   // If this was a volatile load that we are merging, make sure to loop through
340   // and mark all the input loads as non-volatile.  If we don't do this, we will
341   // insert a new volatile load and the old ones will not be deletable.
342   if (isVolatile)
343     for (unsigned i = 0, e = PN.getNumIncomingValues(); i != e; ++i)
344       cast<LoadInst>(PN.getIncomingValue(i))->setVolatile(false);
345   
346   return new LoadInst(PhiVal, "", isVolatile, LoadAlignment);
347 }
348
349
350
351 /// FoldPHIArgOpIntoPHI - If all operands to a PHI node are the same "unary"
352 /// operator and they all are only used by the PHI, PHI together their
353 /// inputs, and do the operation once, to the result of the PHI.
354 Instruction *InstCombiner::FoldPHIArgOpIntoPHI(PHINode &PN) {
355   Instruction *FirstInst = cast<Instruction>(PN.getIncomingValue(0));
356
357   if (isa<GetElementPtrInst>(FirstInst))
358     return FoldPHIArgGEPIntoPHI(PN);
359   if (isa<LoadInst>(FirstInst))
360     return FoldPHIArgLoadIntoPHI(PN);
361   
362   // Scan the instruction, looking for input operations that can be folded away.
363   // If all input operands to the phi are the same instruction (e.g. a cast from
364   // the same type or "+42") we can pull the operation through the PHI, reducing
365   // code size and simplifying code.
366   Constant *ConstantOp = 0;
367   const Type *CastSrcTy = 0;
368   
369   if (isa<CastInst>(FirstInst)) {
370     CastSrcTy = FirstInst->getOperand(0)->getType();
371
372     // Be careful about transforming integer PHIs.  We don't want to pessimize
373     // the code by turning an i32 into an i1293.
374     if (PN.getType()->isIntegerTy() && CastSrcTy->isIntegerTy()) {
375       if (!ShouldChangeType(PN.getType(), CastSrcTy))
376         return 0;
377     }
378   } else if (isa<BinaryOperator>(FirstInst) || isa<CmpInst>(FirstInst)) {
379     // Can fold binop, compare or shift here if the RHS is a constant, 
380     // otherwise call FoldPHIArgBinOpIntoPHI.
381     ConstantOp = dyn_cast<Constant>(FirstInst->getOperand(1));
382     if (ConstantOp == 0)
383       return FoldPHIArgBinOpIntoPHI(PN);
384   } else {
385     return 0;  // Cannot fold this operation.
386   }
387
388   // Check to see if all arguments are the same operation.
389   for (unsigned i = 1, e = PN.getNumIncomingValues(); i != e; ++i) {
390     Instruction *I = dyn_cast<Instruction>(PN.getIncomingValue(i));
391     if (I == 0 || !I->hasOneUse() || !I->isSameOperationAs(FirstInst))
392       return 0;
393     if (CastSrcTy) {
394       if (I->getOperand(0)->getType() != CastSrcTy)
395         return 0;  // Cast operation must match.
396     } else if (I->getOperand(1) != ConstantOp) {
397       return 0;
398     }
399   }
400
401   // Okay, they are all the same operation.  Create a new PHI node of the
402   // correct type, and PHI together all of the LHS's of the instructions.
403   PHINode *NewPN = PHINode::Create(FirstInst->getOperand(0)->getType(),
404                                    PN.getName()+".in");
405   NewPN->reserveOperandSpace(PN.getNumOperands()/2);
406
407   Value *InVal = FirstInst->getOperand(0);
408   NewPN->addIncoming(InVal, PN.getIncomingBlock(0));
409
410   // Add all operands to the new PHI.
411   for (unsigned i = 1, e = PN.getNumIncomingValues(); i != e; ++i) {
412     Value *NewInVal = cast<Instruction>(PN.getIncomingValue(i))->getOperand(0);
413     if (NewInVal != InVal)
414       InVal = 0;
415     NewPN->addIncoming(NewInVal, PN.getIncomingBlock(i));
416   }
417
418   Value *PhiVal;
419   if (InVal) {
420     // The new PHI unions all of the same values together.  This is really
421     // common, so we handle it intelligently here for compile-time speed.
422     PhiVal = InVal;
423     delete NewPN;
424   } else {
425     InsertNewInstBefore(NewPN, PN);
426     PhiVal = NewPN;
427   }
428
429   // Insert and return the new operation.
430   if (CastInst *FirstCI = dyn_cast<CastInst>(FirstInst))
431     return CastInst::Create(FirstCI->getOpcode(), PhiVal, PN.getType());
432   
433   if (BinaryOperator *BinOp = dyn_cast<BinaryOperator>(FirstInst))
434     return BinaryOperator::Create(BinOp->getOpcode(), PhiVal, ConstantOp);
435   
436   CmpInst *CIOp = cast<CmpInst>(FirstInst);
437   return CmpInst::Create(CIOp->getOpcode(), CIOp->getPredicate(),
438                          PhiVal, ConstantOp);
439 }
440
441 /// DeadPHICycle - Return true if this PHI node is only used by a PHI node cycle
442 /// that is dead.
443 static bool DeadPHICycle(PHINode *PN,
444                          SmallPtrSet<PHINode*, 16> &PotentiallyDeadPHIs) {
445   if (PN->use_empty()) return true;
446   if (!PN->hasOneUse()) return false;
447
448   // Remember this node, and if we find the cycle, return.
449   if (!PotentiallyDeadPHIs.insert(PN))
450     return true;
451   
452   // Don't scan crazily complex things.
453   if (PotentiallyDeadPHIs.size() == 16)
454     return false;
455
456   if (PHINode *PU = dyn_cast<PHINode>(PN->use_back()))
457     return DeadPHICycle(PU, PotentiallyDeadPHIs);
458
459   return false;
460 }
461
462 /// PHIsEqualValue - Return true if this phi node is always equal to
463 /// NonPhiInVal.  This happens with mutually cyclic phi nodes like:
464 ///   z = some value; x = phi (y, z); y = phi (x, z)
465 static bool PHIsEqualValue(PHINode *PN, Value *NonPhiInVal, 
466                            SmallPtrSet<PHINode*, 16> &ValueEqualPHIs) {
467   // See if we already saw this PHI node.
468   if (!ValueEqualPHIs.insert(PN))
469     return true;
470   
471   // Don't scan crazily complex things.
472   if (ValueEqualPHIs.size() == 16)
473     return false;
474  
475   // Scan the operands to see if they are either phi nodes or are equal to
476   // the value.
477   for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) {
478     Value *Op = PN->getIncomingValue(i);
479     if (PHINode *OpPN = dyn_cast<PHINode>(Op)) {
480       if (!PHIsEqualValue(OpPN, NonPhiInVal, ValueEqualPHIs))
481         return false;
482     } else if (Op != NonPhiInVal)
483       return false;
484   }
485   
486   return true;
487 }
488
489
490 namespace {
491 struct PHIUsageRecord {
492   unsigned PHIId;     // The ID # of the PHI (something determinstic to sort on)
493   unsigned Shift;     // The amount shifted.
494   Instruction *Inst;  // The trunc instruction.
495   
496   PHIUsageRecord(unsigned pn, unsigned Sh, Instruction *User)
497     : PHIId(pn), Shift(Sh), Inst(User) {}
498   
499   bool operator<(const PHIUsageRecord &RHS) const {
500     if (PHIId < RHS.PHIId) return true;
501     if (PHIId > RHS.PHIId) return false;
502     if (Shift < RHS.Shift) return true;
503     if (Shift > RHS.Shift) return false;
504     return Inst->getType()->getPrimitiveSizeInBits() <
505            RHS.Inst->getType()->getPrimitiveSizeInBits();
506   }
507 };
508   
509 struct LoweredPHIRecord {
510   PHINode *PN;        // The PHI that was lowered.
511   unsigned Shift;     // The amount shifted.
512   unsigned Width;     // The width extracted.
513   
514   LoweredPHIRecord(PHINode *pn, unsigned Sh, const Type *Ty)
515     : PN(pn), Shift(Sh), Width(Ty->getPrimitiveSizeInBits()) {}
516   
517   // Ctor form used by DenseMap.
518   LoweredPHIRecord(PHINode *pn, unsigned Sh)
519     : PN(pn), Shift(Sh), Width(0) {}
520 };
521 }
522
523 namespace llvm {
524   template<>
525   struct DenseMapInfo<LoweredPHIRecord> {
526     static inline LoweredPHIRecord getEmptyKey() {
527       return LoweredPHIRecord(0, 0);
528     }
529     static inline LoweredPHIRecord getTombstoneKey() {
530       return LoweredPHIRecord(0, 1);
531     }
532     static unsigned getHashValue(const LoweredPHIRecord &Val) {
533       return DenseMapInfo<PHINode*>::getHashValue(Val.PN) ^ (Val.Shift>>3) ^
534              (Val.Width>>3);
535     }
536     static bool isEqual(const LoweredPHIRecord &LHS,
537                         const LoweredPHIRecord &RHS) {
538       return LHS.PN == RHS.PN && LHS.Shift == RHS.Shift &&
539              LHS.Width == RHS.Width;
540     }
541   };
542   template <>
543   struct isPodLike<LoweredPHIRecord> { static const bool value = true; };
544 }
545
546
547 /// SliceUpIllegalIntegerPHI - This is an integer PHI and we know that it has an
548 /// illegal type: see if it is only used by trunc or trunc(lshr) operations.  If
549 /// so, we split the PHI into the various pieces being extracted.  This sort of
550 /// thing is introduced when SROA promotes an aggregate to large integer values.
551 ///
552 /// TODO: The user of the trunc may be an bitcast to float/double/vector or an
553 /// inttoptr.  We should produce new PHIs in the right type.
554 ///
555 Instruction *InstCombiner::SliceUpIllegalIntegerPHI(PHINode &FirstPhi) {
556   // PHIUsers - Keep track of all of the truncated values extracted from a set
557   // of PHIs, along with their offset.  These are the things we want to rewrite.
558   SmallVector<PHIUsageRecord, 16> PHIUsers;
559   
560   // PHIs are often mutually cyclic, so we keep track of a whole set of PHI
561   // nodes which are extracted from. PHIsToSlice is a set we use to avoid
562   // revisiting PHIs, PHIsInspected is a ordered list of PHIs that we need to
563   // check the uses of (to ensure they are all extracts).
564   SmallVector<PHINode*, 8> PHIsToSlice;
565   SmallPtrSet<PHINode*, 8> PHIsInspected;
566   
567   PHIsToSlice.push_back(&FirstPhi);
568   PHIsInspected.insert(&FirstPhi);
569   
570   for (unsigned PHIId = 0; PHIId != PHIsToSlice.size(); ++PHIId) {
571     PHINode *PN = PHIsToSlice[PHIId];
572     
573     // Scan the input list of the PHI.  If any input is an invoke, and if the
574     // input is defined in the predecessor, then we won't be split the critical
575     // edge which is required to insert a truncate.  Because of this, we have to
576     // bail out.
577     for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) {
578       InvokeInst *II = dyn_cast<InvokeInst>(PN->getIncomingValue(i));
579       if (II == 0) continue;
580       if (II->getParent() != PN->getIncomingBlock(i))
581         continue;
582      
583       // If we have a phi, and if it's directly in the predecessor, then we have
584       // a critical edge where we need to put the truncate.  Since we can't
585       // split the edge in instcombine, we have to bail out.
586       return 0;
587     }
588       
589     
590     for (Value::use_iterator UI = PN->use_begin(), E = PN->use_end();
591          UI != E; ++UI) {
592       Instruction *User = cast<Instruction>(*UI);
593       
594       // If the user is a PHI, inspect its uses recursively.
595       if (PHINode *UserPN = dyn_cast<PHINode>(User)) {
596         if (PHIsInspected.insert(UserPN))
597           PHIsToSlice.push_back(UserPN);
598         continue;
599       }
600       
601       // Truncates are always ok.
602       if (isa<TruncInst>(User)) {
603         PHIUsers.push_back(PHIUsageRecord(PHIId, 0, User));
604         continue;
605       }
606       
607       // Otherwise it must be a lshr which can only be used by one trunc.
608       if (User->getOpcode() != Instruction::LShr ||
609           !User->hasOneUse() || !isa<TruncInst>(User->use_back()) ||
610           !isa<ConstantInt>(User->getOperand(1)))
611         return 0;
612       
613       unsigned Shift = cast<ConstantInt>(User->getOperand(1))->getZExtValue();
614       PHIUsers.push_back(PHIUsageRecord(PHIId, Shift, User->use_back()));
615     }
616   }
617   
618   // If we have no users, they must be all self uses, just nuke the PHI.
619   if (PHIUsers.empty())
620     return ReplaceInstUsesWith(FirstPhi, UndefValue::get(FirstPhi.getType()));
621   
622   // If this phi node is transformable, create new PHIs for all the pieces
623   // extracted out of it.  First, sort the users by their offset and size.
624   array_pod_sort(PHIUsers.begin(), PHIUsers.end());
625   
626   DEBUG(errs() << "SLICING UP PHI: " << FirstPhi << '\n';
627             for (unsigned i = 1, e = PHIsToSlice.size(); i != e; ++i)
628               errs() << "AND USER PHI #" << i << ": " << *PHIsToSlice[i] <<'\n';
629         );
630   
631   // PredValues - This is a temporary used when rewriting PHI nodes.  It is
632   // hoisted out here to avoid construction/destruction thrashing.
633   DenseMap<BasicBlock*, Value*> PredValues;
634   
635   // ExtractedVals - Each new PHI we introduce is saved here so we don't
636   // introduce redundant PHIs.
637   DenseMap<LoweredPHIRecord, PHINode*> ExtractedVals;
638   
639   for (unsigned UserI = 0, UserE = PHIUsers.size(); UserI != UserE; ++UserI) {
640     unsigned PHIId = PHIUsers[UserI].PHIId;
641     PHINode *PN = PHIsToSlice[PHIId];
642     unsigned Offset = PHIUsers[UserI].Shift;
643     const Type *Ty = PHIUsers[UserI].Inst->getType();
644     
645     PHINode *EltPHI;
646     
647     // If we've already lowered a user like this, reuse the previously lowered
648     // value.
649     if ((EltPHI = ExtractedVals[LoweredPHIRecord(PN, Offset, Ty)]) == 0) {
650       
651       // Otherwise, Create the new PHI node for this user.
652       EltPHI = PHINode::Create(Ty, PN->getName()+".off"+Twine(Offset), PN);
653       assert(EltPHI->getType() != PN->getType() &&
654              "Truncate didn't shrink phi?");
655     
656       for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) {
657         BasicBlock *Pred = PN->getIncomingBlock(i);
658         Value *&PredVal = PredValues[Pred];
659         
660         // If we already have a value for this predecessor, reuse it.
661         if (PredVal) {
662           EltPHI->addIncoming(PredVal, Pred);
663           continue;
664         }
665
666         // Handle the PHI self-reuse case.
667         Value *InVal = PN->getIncomingValue(i);
668         if (InVal == PN) {
669           PredVal = EltPHI;
670           EltPHI->addIncoming(PredVal, Pred);
671           continue;
672         }
673         
674         if (PHINode *InPHI = dyn_cast<PHINode>(PN)) {
675           // If the incoming value was a PHI, and if it was one of the PHIs we
676           // already rewrote it, just use the lowered value.
677           if (Value *Res = ExtractedVals[LoweredPHIRecord(InPHI, Offset, Ty)]) {
678             PredVal = Res;
679             EltPHI->addIncoming(PredVal, Pred);
680             continue;
681           }
682         }
683         
684         // Otherwise, do an extract in the predecessor.
685         Builder->SetInsertPoint(Pred, Pred->getTerminator());
686         Value *Res = InVal;
687         if (Offset)
688           Res = Builder->CreateLShr(Res, ConstantInt::get(InVal->getType(),
689                                                           Offset), "extract");
690         Res = Builder->CreateTrunc(Res, Ty, "extract.t");
691         PredVal = Res;
692         EltPHI->addIncoming(Res, Pred);
693         
694         // If the incoming value was a PHI, and if it was one of the PHIs we are
695         // rewriting, we will ultimately delete the code we inserted.  This
696         // means we need to revisit that PHI to make sure we extract out the
697         // needed piece.
698         if (PHINode *OldInVal = dyn_cast<PHINode>(PN->getIncomingValue(i)))
699           if (PHIsInspected.count(OldInVal)) {
700             unsigned RefPHIId = std::find(PHIsToSlice.begin(),PHIsToSlice.end(),
701                                           OldInVal)-PHIsToSlice.begin();
702             PHIUsers.push_back(PHIUsageRecord(RefPHIId, Offset, 
703                                               cast<Instruction>(Res)));
704             ++UserE;
705           }
706       }
707       PredValues.clear();
708       
709       DEBUG(errs() << "  Made element PHI for offset " << Offset << ": "
710                    << *EltPHI << '\n');
711       ExtractedVals[LoweredPHIRecord(PN, Offset, Ty)] = EltPHI;
712     }
713     
714     // Replace the use of this piece with the PHI node.
715     ReplaceInstUsesWith(*PHIUsers[UserI].Inst, EltPHI);
716   }
717   
718   // Replace all the remaining uses of the PHI nodes (self uses and the lshrs)
719   // with undefs.
720   Value *Undef = UndefValue::get(FirstPhi.getType());
721   for (unsigned i = 1, e = PHIsToSlice.size(); i != e; ++i)
722     ReplaceInstUsesWith(*PHIsToSlice[i], Undef);
723   return ReplaceInstUsesWith(FirstPhi, Undef);
724 }
725
726 // PHINode simplification
727 //
728 Instruction *InstCombiner::visitPHINode(PHINode &PN) {
729   // If LCSSA is around, don't mess with Phi nodes
730   if (MustPreserveLCSSA) return 0;
731   
732   if (Value *V = PN.hasConstantValue())
733     return ReplaceInstUsesWith(PN, V);
734
735   // If all PHI operands are the same operation, pull them through the PHI,
736   // reducing code size.
737   if (isa<Instruction>(PN.getIncomingValue(0)) &&
738       isa<Instruction>(PN.getIncomingValue(1)) &&
739       cast<Instruction>(PN.getIncomingValue(0))->getOpcode() ==
740       cast<Instruction>(PN.getIncomingValue(1))->getOpcode() &&
741       // FIXME: The hasOneUse check will fail for PHIs that use the value more
742       // than themselves more than once.
743       PN.getIncomingValue(0)->hasOneUse())
744     if (Instruction *Result = FoldPHIArgOpIntoPHI(PN))
745       return Result;
746
747   // If this is a trivial cycle in the PHI node graph, remove it.  Basically, if
748   // this PHI only has a single use (a PHI), and if that PHI only has one use (a
749   // PHI)... break the cycle.
750   if (PN.hasOneUse()) {
751     Instruction *PHIUser = cast<Instruction>(PN.use_back());
752     if (PHINode *PU = dyn_cast<PHINode>(PHIUser)) {
753       SmallPtrSet<PHINode*, 16> PotentiallyDeadPHIs;
754       PotentiallyDeadPHIs.insert(&PN);
755       if (DeadPHICycle(PU, PotentiallyDeadPHIs))
756         return ReplaceInstUsesWith(PN, UndefValue::get(PN.getType()));
757     }
758    
759     // If this phi has a single use, and if that use just computes a value for
760     // the next iteration of a loop, delete the phi.  This occurs with unused
761     // induction variables, e.g. "for (int j = 0; ; ++j);".  Detecting this
762     // common case here is good because the only other things that catch this
763     // are induction variable analysis (sometimes) and ADCE, which is only run
764     // late.
765     if (PHIUser->hasOneUse() &&
766         (isa<BinaryOperator>(PHIUser) || isa<GetElementPtrInst>(PHIUser)) &&
767         PHIUser->use_back() == &PN) {
768       return ReplaceInstUsesWith(PN, UndefValue::get(PN.getType()));
769     }
770   }
771
772   // We sometimes end up with phi cycles that non-obviously end up being the
773   // same value, for example:
774   //   z = some value; x = phi (y, z); y = phi (x, z)
775   // where the phi nodes don't necessarily need to be in the same block.  Do a
776   // quick check to see if the PHI node only contains a single non-phi value, if
777   // so, scan to see if the phi cycle is actually equal to that value.
778   {
779     unsigned InValNo = 0, NumOperandVals = PN.getNumIncomingValues();
780     // Scan for the first non-phi operand.
781     while (InValNo != NumOperandVals && 
782            isa<PHINode>(PN.getIncomingValue(InValNo)))
783       ++InValNo;
784
785     if (InValNo != NumOperandVals) {
786       Value *NonPhiInVal = PN.getOperand(InValNo);
787       
788       // Scan the rest of the operands to see if there are any conflicts, if so
789       // there is no need to recursively scan other phis.
790       for (++InValNo; InValNo != NumOperandVals; ++InValNo) {
791         Value *OpVal = PN.getIncomingValue(InValNo);
792         if (OpVal != NonPhiInVal && !isa<PHINode>(OpVal))
793           break;
794       }
795       
796       // If we scanned over all operands, then we have one unique value plus
797       // phi values.  Scan PHI nodes to see if they all merge in each other or
798       // the value.
799       if (InValNo == NumOperandVals) {
800         SmallPtrSet<PHINode*, 16> ValueEqualPHIs;
801         if (PHIsEqualValue(&PN, NonPhiInVal, ValueEqualPHIs))
802           return ReplaceInstUsesWith(PN, NonPhiInVal);
803       }
804     }
805   }
806
807   // If there are multiple PHIs, sort their operands so that they all list
808   // the blocks in the same order. This will help identical PHIs be eliminated
809   // by other passes. Other passes shouldn't depend on this for correctness
810   // however.
811   PHINode *FirstPN = cast<PHINode>(PN.getParent()->begin());
812   if (&PN != FirstPN)
813     for (unsigned i = 0, e = FirstPN->getNumIncomingValues(); i != e; ++i) {
814       BasicBlock *BBA = PN.getIncomingBlock(i);
815       BasicBlock *BBB = FirstPN->getIncomingBlock(i);
816       if (BBA != BBB) {
817         Value *VA = PN.getIncomingValue(i);
818         unsigned j = PN.getBasicBlockIndex(BBB);
819         Value *VB = PN.getIncomingValue(j);
820         PN.setIncomingBlock(i, BBB);
821         PN.setIncomingValue(i, VB);
822         PN.setIncomingBlock(j, BBA);
823         PN.setIncomingValue(j, VA);
824         // NOTE: Instcombine normally would want us to "return &PN" if we
825         // modified any of the operands of an instruction.  However, since we
826         // aren't adding or removing uses (just rearranging them) we don't do
827         // this in this case.
828       }
829     }
830
831   // If this is an integer PHI and we know that it has an illegal type, see if
832   // it is only used by trunc or trunc(lshr) operations.  If so, we split the
833   // PHI into the various pieces being extracted.  This sort of thing is
834   // introduced when SROA promotes an aggregate to a single large integer type.
835   if (PN.getType()->isIntegerTy() && TD &&
836       !TD->isLegalInteger(PN.getType()->getPrimitiveSizeInBits()))
837     if (Instruction *Res = SliceUpIllegalIntegerPHI(PN))
838       return Res;
839   
840   return 0;
841 }