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