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