1f54e72962991005a3c0cc7dce0c550a14af90792Chris Lattner//===- InstCombinePHI.cpp -------------------------------------------------===//
2f54e72962991005a3c0cc7dce0c550a14af90792Chris Lattner//
3f54e72962991005a3c0cc7dce0c550a14af90792Chris Lattner//                     The LLVM Compiler Infrastructure
4f54e72962991005a3c0cc7dce0c550a14af90792Chris Lattner//
5f54e72962991005a3c0cc7dce0c550a14af90792Chris Lattner// This file is distributed under the University of Illinois Open Source
6f54e72962991005a3c0cc7dce0c550a14af90792Chris Lattner// License. See LICENSE.TXT for details.
7f54e72962991005a3c0cc7dce0c550a14af90792Chris Lattner//
8f54e72962991005a3c0cc7dce0c550a14af90792Chris Lattner//===----------------------------------------------------------------------===//
9f54e72962991005a3c0cc7dce0c550a14af90792Chris Lattner//
10f54e72962991005a3c0cc7dce0c550a14af90792Chris Lattner// This file implements the visitPHINode function.
11f54e72962991005a3c0cc7dce0c550a14af90792Chris Lattner//
12f54e72962991005a3c0cc7dce0c550a14af90792Chris Lattner//===----------------------------------------------------------------------===//
13f54e72962991005a3c0cc7dce0c550a14af90792Chris Lattner
14f54e72962991005a3c0cc7dce0c550a14af90792Chris Lattner#include "InstCombine.h"
15d04a8d4b33ff316ca4cf961e06c9e312eff8e64fChandler Carruth#include "llvm/ADT/STLExtras.h"
16d04a8d4b33ff316ca4cf961e06c9e312eff8e64fChandler Carruth#include "llvm/ADT/SmallPtrSet.h"
17cd6636c737a82949ad13db2d0d918af6424fb78bDuncan Sands#include "llvm/Analysis/InstructionSimplify.h"
180b8c9a80f20772c3793201ab5b251d3520b9cea3Chandler Carruth#include "llvm/IR/DataLayout.h"
19f54e72962991005a3c0cc7dce0c550a14af90792Chris Lattnerusing namespace llvm;
20f54e72962991005a3c0cc7dce0c550a14af90792Chris Lattner
21dce4a407a24b04eebc6a376f8e62b41aaa7b071fStephen Hines#define DEBUG_TYPE "instcombine"
22dce4a407a24b04eebc6a376f8e62b41aaa7b071fStephen Hines
23f54e72962991005a3c0cc7dce0c550a14af90792Chris Lattner/// FoldPHIArgBinOpIntoPHI - If we have something like phi [add (a,b), add(a,c)]
24f54e72962991005a3c0cc7dce0c550a14af90792Chris Lattner/// and if a/b/c and the add's all have a single use, turn this into a phi
25f54e72962991005a3c0cc7dce0c550a14af90792Chris Lattner/// and a single binop.
26f54e72962991005a3c0cc7dce0c550a14af90792Chris LattnerInstruction *InstCombiner::FoldPHIArgBinOpIntoPHI(PHINode &PN) {
27f54e72962991005a3c0cc7dce0c550a14af90792Chris Lattner  Instruction *FirstInst = cast<Instruction>(PN.getIncomingValue(0));
28f54e72962991005a3c0cc7dce0c550a14af90792Chris Lattner  assert(isa<BinaryOperator>(FirstInst) || isa<CmpInst>(FirstInst));
29f54e72962991005a3c0cc7dce0c550a14af90792Chris Lattner  unsigned Opc = FirstInst->getOpcode();
30f54e72962991005a3c0cc7dce0c550a14af90792Chris Lattner  Value *LHSVal = FirstInst->getOperand(0);
31f54e72962991005a3c0cc7dce0c550a14af90792Chris Lattner  Value *RHSVal = FirstInst->getOperand(1);
3203fceff6f69a0261a767aab8e62de8aa9301b86cJim Grosbach
33db125cfaf57cc83e7dd7453de2d509bc8efd0e5eChris Lattner  Type *LHSType = LHSVal->getType();
34db125cfaf57cc83e7dd7453de2d509bc8efd0e5eChris Lattner  Type *RHSType = RHSVal->getType();
3503fceff6f69a0261a767aab8e62de8aa9301b86cJim Grosbach
36c8cb8ef9c2d5e354db661022d707a19b3533c00eChris Lattner  bool isNUW = false, isNSW = false, isExact = false;
37c8cb8ef9c2d5e354db661022d707a19b3533c00eChris Lattner  if (OverflowingBinaryOperator *BO =
38c8cb8ef9c2d5e354db661022d707a19b3533c00eChris Lattner        dyn_cast<OverflowingBinaryOperator>(FirstInst)) {
39c8cb8ef9c2d5e354db661022d707a19b3533c00eChris Lattner    isNUW = BO->hasNoUnsignedWrap();
40c8cb8ef9c2d5e354db661022d707a19b3533c00eChris Lattner    isNSW = BO->hasNoSignedWrap();
41c8cb8ef9c2d5e354db661022d707a19b3533c00eChris Lattner  } else if (PossiblyExactOperator *PEO =
42c8cb8ef9c2d5e354db661022d707a19b3533c00eChris Lattner               dyn_cast<PossiblyExactOperator>(FirstInst))
43c8cb8ef9c2d5e354db661022d707a19b3533c00eChris Lattner    isExact = PEO->isExact();
4403fceff6f69a0261a767aab8e62de8aa9301b86cJim Grosbach
45f54e72962991005a3c0cc7dce0c550a14af90792Chris Lattner  // Scan to see if all operands are the same opcode, and all have one use.
46f54e72962991005a3c0cc7dce0c550a14af90792Chris Lattner  for (unsigned i = 1; i != PN.getNumIncomingValues(); ++i) {
47f54e72962991005a3c0cc7dce0c550a14af90792Chris Lattner    Instruction *I = dyn_cast<Instruction>(PN.getIncomingValue(i));
48f54e72962991005a3c0cc7dce0c550a14af90792Chris Lattner    if (!I || I->getOpcode() != Opc || !I->hasOneUse() ||
49f54e72962991005a3c0cc7dce0c550a14af90792Chris Lattner        // Verify type of the LHS matches so we don't fold cmp's of different
50c8cb8ef9c2d5e354db661022d707a19b3533c00eChris Lattner        // types.
51f54e72962991005a3c0cc7dce0c550a14af90792Chris Lattner        I->getOperand(0)->getType() != LHSType ||
52f54e72962991005a3c0cc7dce0c550a14af90792Chris Lattner        I->getOperand(1)->getType() != RHSType)
53dce4a407a24b04eebc6a376f8e62b41aaa7b071fStephen Hines      return nullptr;
54f54e72962991005a3c0cc7dce0c550a14af90792Chris Lattner
55f54e72962991005a3c0cc7dce0c550a14af90792Chris Lattner    // If they are CmpInst instructions, check their predicates
56c8cb8ef9c2d5e354db661022d707a19b3533c00eChris Lattner    if (CmpInst *CI = dyn_cast<CmpInst>(I))
57c8cb8ef9c2d5e354db661022d707a19b3533c00eChris Lattner      if (CI->getPredicate() != cast<CmpInst>(FirstInst)->getPredicate())
58dce4a407a24b04eebc6a376f8e62b41aaa7b071fStephen Hines        return nullptr;
5903fceff6f69a0261a767aab8e62de8aa9301b86cJim Grosbach
60c8cb8ef9c2d5e354db661022d707a19b3533c00eChris Lattner    if (isNUW)
61c8cb8ef9c2d5e354db661022d707a19b3533c00eChris Lattner      isNUW = cast<OverflowingBinaryOperator>(I)->hasNoUnsignedWrap();
62c8cb8ef9c2d5e354db661022d707a19b3533c00eChris Lattner    if (isNSW)
63c8cb8ef9c2d5e354db661022d707a19b3533c00eChris Lattner      isNSW = cast<OverflowingBinaryOperator>(I)->hasNoSignedWrap();
64c8cb8ef9c2d5e354db661022d707a19b3533c00eChris Lattner    if (isExact)
65c8cb8ef9c2d5e354db661022d707a19b3533c00eChris Lattner      isExact = cast<PossiblyExactOperator>(I)->isExact();
6603fceff6f69a0261a767aab8e62de8aa9301b86cJim Grosbach
67f54e72962991005a3c0cc7dce0c550a14af90792Chris Lattner    // Keep track of which operand needs a phi node.
68dce4a407a24b04eebc6a376f8e62b41aaa7b071fStephen Hines    if (I->getOperand(0) != LHSVal) LHSVal = nullptr;
69dce4a407a24b04eebc6a376f8e62b41aaa7b071fStephen Hines    if (I->getOperand(1) != RHSVal) RHSVal = nullptr;
70f54e72962991005a3c0cc7dce0c550a14af90792Chris Lattner  }
71f54e72962991005a3c0cc7dce0c550a14af90792Chris Lattner
72f54e72962991005a3c0cc7dce0c550a14af90792Chris Lattner  // If both LHS and RHS would need a PHI, don't do this transformation,
73f54e72962991005a3c0cc7dce0c550a14af90792Chris Lattner  // because it would increase the number of PHIs entering the block,
74f54e72962991005a3c0cc7dce0c550a14af90792Chris Lattner  // which leads to higher register pressure. This is especially
75f54e72962991005a3c0cc7dce0c550a14af90792Chris Lattner  // bad when the PHIs are in the header of a loop.
76f54e72962991005a3c0cc7dce0c550a14af90792Chris Lattner  if (!LHSVal && !RHSVal)
77dce4a407a24b04eebc6a376f8e62b41aaa7b071fStephen Hines    return nullptr;
7803fceff6f69a0261a767aab8e62de8aa9301b86cJim Grosbach
79f54e72962991005a3c0cc7dce0c550a14af90792Chris Lattner  // Otherwise, this is safe to transform!
8003fceff6f69a0261a767aab8e62de8aa9301b86cJim Grosbach
81f54e72962991005a3c0cc7dce0c550a14af90792Chris Lattner  Value *InLHS = FirstInst->getOperand(0);
82f54e72962991005a3c0cc7dce0c550a14af90792Chris Lattner  Value *InRHS = FirstInst->getOperand(1);
83dce4a407a24b04eebc6a376f8e62b41aaa7b071fStephen Hines  PHINode *NewLHS = nullptr, *NewRHS = nullptr;
84dce4a407a24b04eebc6a376f8e62b41aaa7b071fStephen Hines  if (!LHSVal) {
853ecfc861b4365f341c5c969b40e1afccde676e6fJay Foad    NewLHS = PHINode::Create(LHSType, PN.getNumIncomingValues(),
86f54e72962991005a3c0cc7dce0c550a14af90792Chris Lattner                             FirstInst->getOperand(0)->getName() + ".pn");
87f54e72962991005a3c0cc7dce0c550a14af90792Chris Lattner    NewLHS->addIncoming(InLHS, PN.getIncomingBlock(0));
88f54e72962991005a3c0cc7dce0c550a14af90792Chris Lattner    InsertNewInstBefore(NewLHS, PN);
89f54e72962991005a3c0cc7dce0c550a14af90792Chris Lattner    LHSVal = NewLHS;
90f54e72962991005a3c0cc7dce0c550a14af90792Chris Lattner  }
9103fceff6f69a0261a767aab8e62de8aa9301b86cJim Grosbach
92dce4a407a24b04eebc6a376f8e62b41aaa7b071fStephen Hines  if (!RHSVal) {
933ecfc861b4365f341c5c969b40e1afccde676e6fJay Foad    NewRHS = PHINode::Create(RHSType, PN.getNumIncomingValues(),
94f54e72962991005a3c0cc7dce0c550a14af90792Chris Lattner                             FirstInst->getOperand(1)->getName() + ".pn");
95f54e72962991005a3c0cc7dce0c550a14af90792Chris Lattner    NewRHS->addIncoming(InRHS, PN.getIncomingBlock(0));
96f54e72962991005a3c0cc7dce0c550a14af90792Chris Lattner    InsertNewInstBefore(NewRHS, PN);
97f54e72962991005a3c0cc7dce0c550a14af90792Chris Lattner    RHSVal = NewRHS;
98f54e72962991005a3c0cc7dce0c550a14af90792Chris Lattner  }
9903fceff6f69a0261a767aab8e62de8aa9301b86cJim Grosbach
100f54e72962991005a3c0cc7dce0c550a14af90792Chris Lattner  // Add all operands to the new PHIs.
101f54e72962991005a3c0cc7dce0c550a14af90792Chris Lattner  if (NewLHS || NewRHS) {
102f54e72962991005a3c0cc7dce0c550a14af90792Chris Lattner    for (unsigned i = 1, e = PN.getNumIncomingValues(); i != e; ++i) {
103f54e72962991005a3c0cc7dce0c550a14af90792Chris Lattner      Instruction *InInst = cast<Instruction>(PN.getIncomingValue(i));
104f54e72962991005a3c0cc7dce0c550a14af90792Chris Lattner      if (NewLHS) {
105f54e72962991005a3c0cc7dce0c550a14af90792Chris Lattner        Value *NewInLHS = InInst->getOperand(0);
106f54e72962991005a3c0cc7dce0c550a14af90792Chris Lattner        NewLHS->addIncoming(NewInLHS, PN.getIncomingBlock(i));
107f54e72962991005a3c0cc7dce0c550a14af90792Chris Lattner      }
108f54e72962991005a3c0cc7dce0c550a14af90792Chris Lattner      if (NewRHS) {
109f54e72962991005a3c0cc7dce0c550a14af90792Chris Lattner        Value *NewInRHS = InInst->getOperand(1);
110f54e72962991005a3c0cc7dce0c550a14af90792Chris Lattner        NewRHS->addIncoming(NewInRHS, PN.getIncomingBlock(i));
111f54e72962991005a3c0cc7dce0c550a14af90792Chris Lattner      }
112f54e72962991005a3c0cc7dce0c550a14af90792Chris Lattner    }
113f54e72962991005a3c0cc7dce0c550a14af90792Chris Lattner  }
11403fceff6f69a0261a767aab8e62de8aa9301b86cJim Grosbach
115a311c34d2af7c750f016ef5e4c41bee77a1dfac7Eli Friedman  if (CmpInst *CIOp = dyn_cast<CmpInst>(FirstInst)) {
116a311c34d2af7c750f016ef5e4c41bee77a1dfac7Eli Friedman    CmpInst *NewCI = CmpInst::Create(CIOp->getOpcode(), CIOp->getPredicate(),
117a311c34d2af7c750f016ef5e4c41bee77a1dfac7Eli Friedman                                     LHSVal, RHSVal);
118a311c34d2af7c750f016ef5e4c41bee77a1dfac7Eli Friedman    NewCI->setDebugLoc(FirstInst->getDebugLoc());
119a311c34d2af7c750f016ef5e4c41bee77a1dfac7Eli Friedman    return NewCI;
120a311c34d2af7c750f016ef5e4c41bee77a1dfac7Eli Friedman  }
121a311c34d2af7c750f016ef5e4c41bee77a1dfac7Eli Friedman
122c8cb8ef9c2d5e354db661022d707a19b3533c00eChris Lattner  BinaryOperator *BinOp = cast<BinaryOperator>(FirstInst);
123c8cb8ef9c2d5e354db661022d707a19b3533c00eChris Lattner  BinaryOperator *NewBinOp =
124c8cb8ef9c2d5e354db661022d707a19b3533c00eChris Lattner    BinaryOperator::Create(BinOp->getOpcode(), LHSVal, RHSVal);
125c8cb8ef9c2d5e354db661022d707a19b3533c00eChris Lattner  if (isNUW) NewBinOp->setHasNoUnsignedWrap();
126c8cb8ef9c2d5e354db661022d707a19b3533c00eChris Lattner  if (isNSW) NewBinOp->setHasNoSignedWrap();
127c8cb8ef9c2d5e354db661022d707a19b3533c00eChris Lattner  if (isExact) NewBinOp->setIsExact();
128a311c34d2af7c750f016ef5e4c41bee77a1dfac7Eli Friedman  NewBinOp->setDebugLoc(FirstInst->getDebugLoc());
129c8cb8ef9c2d5e354db661022d707a19b3533c00eChris Lattner  return NewBinOp;
130f54e72962991005a3c0cc7dce0c550a14af90792Chris Lattner}
131f54e72962991005a3c0cc7dce0c550a14af90792Chris Lattner
132f54e72962991005a3c0cc7dce0c550a14af90792Chris LattnerInstruction *InstCombiner::FoldPHIArgGEPIntoPHI(PHINode &PN) {
133f54e72962991005a3c0cc7dce0c550a14af90792Chris Lattner  GetElementPtrInst *FirstInst =cast<GetElementPtrInst>(PN.getIncomingValue(0));
13403fceff6f69a0261a767aab8e62de8aa9301b86cJim Grosbach
13503fceff6f69a0261a767aab8e62de8aa9301b86cJim Grosbach  SmallVector<Value*, 16> FixedOperands(FirstInst->op_begin(),
136f54e72962991005a3c0cc7dce0c550a14af90792Chris Lattner                                        FirstInst->op_end());
137f54e72962991005a3c0cc7dce0c550a14af90792Chris Lattner  // This is true if all GEP bases are allocas and if all indices into them are
138f54e72962991005a3c0cc7dce0c550a14af90792Chris Lattner  // constants.
139f54e72962991005a3c0cc7dce0c550a14af90792Chris Lattner  bool AllBasePointersAreAllocas = true;
140f54e72962991005a3c0cc7dce0c550a14af90792Chris Lattner
141f54e72962991005a3c0cc7dce0c550a14af90792Chris Lattner  // We don't want to replace this phi if the replacement would require
142f54e72962991005a3c0cc7dce0c550a14af90792Chris Lattner  // more than one phi, which leads to higher register pressure. This is
143f54e72962991005a3c0cc7dce0c550a14af90792Chris Lattner  // especially bad when the PHIs are in the header of a loop.
144f54e72962991005a3c0cc7dce0c550a14af90792Chris Lattner  bool NeededPhi = false;
14503fceff6f69a0261a767aab8e62de8aa9301b86cJim Grosbach
1464bd8217af3cf38f9fcce378fbc687162e28a7cf8Chris Lattner  bool AllInBounds = true;
14703fceff6f69a0261a767aab8e62de8aa9301b86cJim Grosbach
148f54e72962991005a3c0cc7dce0c550a14af90792Chris Lattner  // Scan to see if all operands are the same opcode, and all have one use.
149f54e72962991005a3c0cc7dce0c550a14af90792Chris Lattner  for (unsigned i = 1; i != PN.getNumIncomingValues(); ++i) {
150f54e72962991005a3c0cc7dce0c550a14af90792Chris Lattner    GetElementPtrInst *GEP= dyn_cast<GetElementPtrInst>(PN.getIncomingValue(i));
151f54e72962991005a3c0cc7dce0c550a14af90792Chris Lattner    if (!GEP || !GEP->hasOneUse() || GEP->getType() != FirstInst->getType() ||
152f54e72962991005a3c0cc7dce0c550a14af90792Chris Lattner      GEP->getNumOperands() != FirstInst->getNumOperands())
153dce4a407a24b04eebc6a376f8e62b41aaa7b071fStephen Hines      return nullptr;
154f54e72962991005a3c0cc7dce0c550a14af90792Chris Lattner
1554bd8217af3cf38f9fcce378fbc687162e28a7cf8Chris Lattner    AllInBounds &= GEP->isInBounds();
15603fceff6f69a0261a767aab8e62de8aa9301b86cJim Grosbach
157f54e72962991005a3c0cc7dce0c550a14af90792Chris Lattner    // Keep track of whether or not all GEPs are of alloca pointers.
158f54e72962991005a3c0cc7dce0c550a14af90792Chris Lattner    if (AllBasePointersAreAllocas &&
159f54e72962991005a3c0cc7dce0c550a14af90792Chris Lattner        (!isa<AllocaInst>(GEP->getOperand(0)) ||
160f54e72962991005a3c0cc7dce0c550a14af90792Chris Lattner         !GEP->hasAllConstantIndices()))
161f54e72962991005a3c0cc7dce0c550a14af90792Chris Lattner      AllBasePointersAreAllocas = false;
16203fceff6f69a0261a767aab8e62de8aa9301b86cJim Grosbach
163f54e72962991005a3c0cc7dce0c550a14af90792Chris Lattner    // Compare the operand lists.
164f54e72962991005a3c0cc7dce0c550a14af90792Chris Lattner    for (unsigned op = 0, e = FirstInst->getNumOperands(); op != e; ++op) {
165f54e72962991005a3c0cc7dce0c550a14af90792Chris Lattner      if (FirstInst->getOperand(op) == GEP->getOperand(op))
166f54e72962991005a3c0cc7dce0c550a14af90792Chris Lattner        continue;
16703fceff6f69a0261a767aab8e62de8aa9301b86cJim Grosbach
168f54e72962991005a3c0cc7dce0c550a14af90792Chris Lattner      // Don't merge two GEPs when two operands differ (introducing phi nodes)
169f54e72962991005a3c0cc7dce0c550a14af90792Chris Lattner      // if one of the PHIs has a constant for the index.  The index may be
170f54e72962991005a3c0cc7dce0c550a14af90792Chris Lattner      // substantially cheaper to compute for the constants, so making it a
171f54e72962991005a3c0cc7dce0c550a14af90792Chris Lattner      // variable index could pessimize the path.  This also handles the case
172f54e72962991005a3c0cc7dce0c550a14af90792Chris Lattner      // for struct indices, which must always be constant.
173f54e72962991005a3c0cc7dce0c550a14af90792Chris Lattner      if (isa<ConstantInt>(FirstInst->getOperand(op)) ||
174f54e72962991005a3c0cc7dce0c550a14af90792Chris Lattner          isa<ConstantInt>(GEP->getOperand(op)))
175dce4a407a24b04eebc6a376f8e62b41aaa7b071fStephen Hines        return nullptr;
17603fceff6f69a0261a767aab8e62de8aa9301b86cJim Grosbach
177f54e72962991005a3c0cc7dce0c550a14af90792Chris Lattner      if (FirstInst->getOperand(op)->getType() !=GEP->getOperand(op)->getType())
178dce4a407a24b04eebc6a376f8e62b41aaa7b071fStephen Hines        return nullptr;
179f54e72962991005a3c0cc7dce0c550a14af90792Chris Lattner
180f54e72962991005a3c0cc7dce0c550a14af90792Chris Lattner      // If we already needed a PHI for an earlier operand, and another operand
181f54e72962991005a3c0cc7dce0c550a14af90792Chris Lattner      // also requires a PHI, we'd be introducing more PHIs than we're
182f54e72962991005a3c0cc7dce0c550a14af90792Chris Lattner      // eliminating, which increases register pressure on entry to the PHI's
183f54e72962991005a3c0cc7dce0c550a14af90792Chris Lattner      // block.
184f54e72962991005a3c0cc7dce0c550a14af90792Chris Lattner      if (NeededPhi)
185dce4a407a24b04eebc6a376f8e62b41aaa7b071fStephen Hines        return nullptr;
186f54e72962991005a3c0cc7dce0c550a14af90792Chris Lattner
187dce4a407a24b04eebc6a376f8e62b41aaa7b071fStephen Hines      FixedOperands[op] = nullptr;  // Needs a PHI.
188f54e72962991005a3c0cc7dce0c550a14af90792Chris Lattner      NeededPhi = true;
189f54e72962991005a3c0cc7dce0c550a14af90792Chris Lattner    }
190f54e72962991005a3c0cc7dce0c550a14af90792Chris Lattner  }
19103fceff6f69a0261a767aab8e62de8aa9301b86cJim Grosbach
192f54e72962991005a3c0cc7dce0c550a14af90792Chris Lattner  // If all of the base pointers of the PHI'd GEPs are from allocas, don't
193f54e72962991005a3c0cc7dce0c550a14af90792Chris Lattner  // bother doing this transformation.  At best, this will just save a bit of
194f54e72962991005a3c0cc7dce0c550a14af90792Chris Lattner  // offset calculation, but all the predecessors will have to materialize the
195f54e72962991005a3c0cc7dce0c550a14af90792Chris Lattner  // stack address into a register anyway.  We'd actually rather *clone* the
196f54e72962991005a3c0cc7dce0c550a14af90792Chris Lattner  // load up into the predecessors so that we have a load of a gep of an alloca,
197f54e72962991005a3c0cc7dce0c550a14af90792Chris Lattner  // which can usually all be folded into the load.
198f54e72962991005a3c0cc7dce0c550a14af90792Chris Lattner  if (AllBasePointersAreAllocas)
199dce4a407a24b04eebc6a376f8e62b41aaa7b071fStephen Hines    return nullptr;
20003fceff6f69a0261a767aab8e62de8aa9301b86cJim Grosbach
201f54e72962991005a3c0cc7dce0c550a14af90792Chris Lattner  // Otherwise, this is safe to transform.  Insert PHI nodes for each operand
202f54e72962991005a3c0cc7dce0c550a14af90792Chris Lattner  // that is variable.
203f54e72962991005a3c0cc7dce0c550a14af90792Chris Lattner  SmallVector<PHINode*, 16> OperandPhis(FixedOperands.size());
20403fceff6f69a0261a767aab8e62de8aa9301b86cJim Grosbach
205f54e72962991005a3c0cc7dce0c550a14af90792Chris Lattner  bool HasAnyPHIs = false;
206f54e72962991005a3c0cc7dce0c550a14af90792Chris Lattner  for (unsigned i = 0, e = FixedOperands.size(); i != e; ++i) {
207f54e72962991005a3c0cc7dce0c550a14af90792Chris Lattner    if (FixedOperands[i]) continue;  // operand doesn't need a phi.
208f54e72962991005a3c0cc7dce0c550a14af90792Chris Lattner    Value *FirstOp = FirstInst->getOperand(i);
2093ecfc861b4365f341c5c969b40e1afccde676e6fJay Foad    PHINode *NewPN = PHINode::Create(FirstOp->getType(), e,
210f54e72962991005a3c0cc7dce0c550a14af90792Chris Lattner                                     FirstOp->getName()+".pn");
211f54e72962991005a3c0cc7dce0c550a14af90792Chris Lattner    InsertNewInstBefore(NewPN, PN);
21203fceff6f69a0261a767aab8e62de8aa9301b86cJim Grosbach
213f54e72962991005a3c0cc7dce0c550a14af90792Chris Lattner    NewPN->addIncoming(FirstOp, PN.getIncomingBlock(0));
214f54e72962991005a3c0cc7dce0c550a14af90792Chris Lattner    OperandPhis[i] = NewPN;
215f54e72962991005a3c0cc7dce0c550a14af90792Chris Lattner    FixedOperands[i] = NewPN;
216f54e72962991005a3c0cc7dce0c550a14af90792Chris Lattner    HasAnyPHIs = true;
217f54e72962991005a3c0cc7dce0c550a14af90792Chris Lattner  }
218f54e72962991005a3c0cc7dce0c550a14af90792Chris Lattner
21903fceff6f69a0261a767aab8e62de8aa9301b86cJim Grosbach
220f54e72962991005a3c0cc7dce0c550a14af90792Chris Lattner  // Add all operands to the new PHIs.
221f54e72962991005a3c0cc7dce0c550a14af90792Chris Lattner  if (HasAnyPHIs) {
222f54e72962991005a3c0cc7dce0c550a14af90792Chris Lattner    for (unsigned i = 1, e = PN.getNumIncomingValues(); i != e; ++i) {
223f54e72962991005a3c0cc7dce0c550a14af90792Chris Lattner      GetElementPtrInst *InGEP =cast<GetElementPtrInst>(PN.getIncomingValue(i));
224f54e72962991005a3c0cc7dce0c550a14af90792Chris Lattner      BasicBlock *InBB = PN.getIncomingBlock(i);
22503fceff6f69a0261a767aab8e62de8aa9301b86cJim Grosbach
226f54e72962991005a3c0cc7dce0c550a14af90792Chris Lattner      for (unsigned op = 0, e = OperandPhis.size(); op != e; ++op)
227f54e72962991005a3c0cc7dce0c550a14af90792Chris Lattner        if (PHINode *OpPhi = OperandPhis[op])
228f54e72962991005a3c0cc7dce0c550a14af90792Chris Lattner          OpPhi->addIncoming(InGEP->getOperand(op), InBB);
229f54e72962991005a3c0cc7dce0c550a14af90792Chris Lattner    }
230f54e72962991005a3c0cc7dce0c550a14af90792Chris Lattner  }
23103fceff6f69a0261a767aab8e62de8aa9301b86cJim Grosbach
232f54e72962991005a3c0cc7dce0c550a14af90792Chris Lattner  Value *Base = FixedOperands[0];
23303fceff6f69a0261a767aab8e62de8aa9301b86cJim Grosbach  GetElementPtrInst *NewGEP =
2342eb40f6d86ab44e7e642ea665afb28604008d367Frits van Bommel    GetElementPtrInst::Create(Base, makeArrayRef(FixedOperands).slice(1));
2351521e91fc442b5c27d56118b45248e3d5707f7e2Chris Lattner  if (AllInBounds) NewGEP->setIsInBounds();
236a311c34d2af7c750f016ef5e4c41bee77a1dfac7Eli Friedman  NewGEP->setDebugLoc(FirstInst->getDebugLoc());
2374bd8217af3cf38f9fcce378fbc687162e28a7cf8Chris Lattner  return NewGEP;
238f54e72962991005a3c0cc7dce0c550a14af90792Chris Lattner}
239f54e72962991005a3c0cc7dce0c550a14af90792Chris Lattner
240f54e72962991005a3c0cc7dce0c550a14af90792Chris Lattner
241f54e72962991005a3c0cc7dce0c550a14af90792Chris Lattner/// isSafeAndProfitableToSinkLoad - Return true if we know that it is safe to
242f54e72962991005a3c0cc7dce0c550a14af90792Chris Lattner/// sink the load out of the block that defines it.  This means that it must be
243f54e72962991005a3c0cc7dce0c550a14af90792Chris Lattner/// obvious the value of the load is not changed from the point of the load to
244f54e72962991005a3c0cc7dce0c550a14af90792Chris Lattner/// the end of the block it is in.
245f54e72962991005a3c0cc7dce0c550a14af90792Chris Lattner///
2467a2bdde0a0eebcd2125055e0eacaca040f0b766cChris Lattner/// Finally, it is safe, but not profitable, to sink a load targeting a
247f54e72962991005a3c0cc7dce0c550a14af90792Chris Lattner/// non-address-taken alloca.  Doing so will cause us to not promote the alloca
248f54e72962991005a3c0cc7dce0c550a14af90792Chris Lattner/// to a register.
249f54e72962991005a3c0cc7dce0c550a14af90792Chris Lattnerstatic bool isSafeAndProfitableToSinkLoad(LoadInst *L) {
250f54e72962991005a3c0cc7dce0c550a14af90792Chris Lattner  BasicBlock::iterator BBI = L, E = L->getParent()->end();
25103fceff6f69a0261a767aab8e62de8aa9301b86cJim Grosbach
252f54e72962991005a3c0cc7dce0c550a14af90792Chris Lattner  for (++BBI; BBI != E; ++BBI)
253f54e72962991005a3c0cc7dce0c550a14af90792Chris Lattner    if (BBI->mayWriteToMemory())
254f54e72962991005a3c0cc7dce0c550a14af90792Chris Lattner      return false;
25503fceff6f69a0261a767aab8e62de8aa9301b86cJim Grosbach
256f54e72962991005a3c0cc7dce0c550a14af90792Chris Lattner  // Check for non-address taken alloca.  If not address-taken already, it isn't
257f54e72962991005a3c0cc7dce0c550a14af90792Chris Lattner  // profitable to do this xform.
258f54e72962991005a3c0cc7dce0c550a14af90792Chris Lattner  if (AllocaInst *AI = dyn_cast<AllocaInst>(L->getOperand(0))) {
259f54e72962991005a3c0cc7dce0c550a14af90792Chris Lattner    bool isAddressTaken = false;
26036b56886974eae4f9c5ebc96befd3e7bfe5de338Stephen Hines    for (User *U : AI->users()) {
26140119ceeecafdd6d47bd7bb7f520262858b931dfGabor Greif      if (isa<LoadInst>(U)) continue;
26240119ceeecafdd6d47bd7bb7f520262858b931dfGabor Greif      if (StoreInst *SI = dyn_cast<StoreInst>(U)) {
263f54e72962991005a3c0cc7dce0c550a14af90792Chris Lattner        // If storing TO the alloca, then the address isn't taken.
264f54e72962991005a3c0cc7dce0c550a14af90792Chris Lattner        if (SI->getOperand(1) == AI) continue;
265f54e72962991005a3c0cc7dce0c550a14af90792Chris Lattner      }
266f54e72962991005a3c0cc7dce0c550a14af90792Chris Lattner      isAddressTaken = true;
267f54e72962991005a3c0cc7dce0c550a14af90792Chris Lattner      break;
268f54e72962991005a3c0cc7dce0c550a14af90792Chris Lattner    }
26903fceff6f69a0261a767aab8e62de8aa9301b86cJim Grosbach
270f54e72962991005a3c0cc7dce0c550a14af90792Chris Lattner    if (!isAddressTaken && AI->isStaticAlloca())
271f54e72962991005a3c0cc7dce0c550a14af90792Chris Lattner      return false;
272f54e72962991005a3c0cc7dce0c550a14af90792Chris Lattner  }
27303fceff6f69a0261a767aab8e62de8aa9301b86cJim Grosbach
274f54e72962991005a3c0cc7dce0c550a14af90792Chris Lattner  // If this load is a load from a GEP with a constant offset from an alloca,
275f54e72962991005a3c0cc7dce0c550a14af90792Chris Lattner  // then we don't want to sink it.  In its present form, it will be
276f54e72962991005a3c0cc7dce0c550a14af90792Chris Lattner  // load [constant stack offset].  Sinking it will cause us to have to
277f54e72962991005a3c0cc7dce0c550a14af90792Chris Lattner  // materialize the stack addresses in each predecessor in a register only to
278f54e72962991005a3c0cc7dce0c550a14af90792Chris Lattner  // do a shared load from register in the successor.
279f54e72962991005a3c0cc7dce0c550a14af90792Chris Lattner  if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(L->getOperand(0)))
280f54e72962991005a3c0cc7dce0c550a14af90792Chris Lattner    if (AllocaInst *AI = dyn_cast<AllocaInst>(GEP->getOperand(0)))
281f54e72962991005a3c0cc7dce0c550a14af90792Chris Lattner      if (AI->isStaticAlloca() && GEP->hasAllConstantIndices())
282f54e72962991005a3c0cc7dce0c550a14af90792Chris Lattner        return false;
28303fceff6f69a0261a767aab8e62de8aa9301b86cJim Grosbach
284f54e72962991005a3c0cc7dce0c550a14af90792Chris Lattner  return true;
285f54e72962991005a3c0cc7dce0c550a14af90792Chris Lattner}
286f54e72962991005a3c0cc7dce0c550a14af90792Chris Lattner
287f54e72962991005a3c0cc7dce0c550a14af90792Chris LattnerInstruction *InstCombiner::FoldPHIArgLoadIntoPHI(PHINode &PN) {
288f54e72962991005a3c0cc7dce0c550a14af90792Chris Lattner  LoadInst *FirstLI = cast<LoadInst>(PN.getIncomingValue(0));
289cc4a0435b7ee34af2c64a6f7ee63642f56096d1bEli Friedman
290cc4a0435b7ee34af2c64a6f7ee63642f56096d1bEli Friedman  // FIXME: This is overconservative; this transform is allowed in some cases
291cc4a0435b7ee34af2c64a6f7ee63642f56096d1bEli Friedman  // for atomic operations.
292cc4a0435b7ee34af2c64a6f7ee63642f56096d1bEli Friedman  if (FirstLI->isAtomic())
293dce4a407a24b04eebc6a376f8e62b41aaa7b071fStephen Hines    return nullptr;
294cc4a0435b7ee34af2c64a6f7ee63642f56096d1bEli Friedman
295f54e72962991005a3c0cc7dce0c550a14af90792Chris Lattner  // When processing loads, we need to propagate two bits of information to the
296f54e72962991005a3c0cc7dce0c550a14af90792Chris Lattner  // sunk load: whether it is volatile, and what its alignment is.  We currently
297f54e72962991005a3c0cc7dce0c550a14af90792Chris Lattner  // don't sink loads when some have their alignment specified and some don't.
298f54e72962991005a3c0cc7dce0c550a14af90792Chris Lattner  // visitLoadInst will propagate an alignment onto the load when TD is around,
299f54e72962991005a3c0cc7dce0c550a14af90792Chris Lattner  // and if TD isn't around, we can't handle the mixed case.
300f54e72962991005a3c0cc7dce0c550a14af90792Chris Lattner  bool isVolatile = FirstLI->isVolatile();
301f54e72962991005a3c0cc7dce0c550a14af90792Chris Lattner  unsigned LoadAlignment = FirstLI->getAlignment();
3024c5fb1a311a7a5e3ceb802f5b26329d30f2713b1Chris Lattner  unsigned LoadAddrSpace = FirstLI->getPointerAddressSpace();
30303fceff6f69a0261a767aab8e62de8aa9301b86cJim Grosbach
304f54e72962991005a3c0cc7dce0c550a14af90792Chris Lattner  // We can't sink the load if the loaded value could be modified between the
305f54e72962991005a3c0cc7dce0c550a14af90792Chris Lattner  // load and the PHI.
306f54e72962991005a3c0cc7dce0c550a14af90792Chris Lattner  if (FirstLI->getParent() != PN.getIncomingBlock(0) ||
307f54e72962991005a3c0cc7dce0c550a14af90792Chris Lattner      !isSafeAndProfitableToSinkLoad(FirstLI))
308dce4a407a24b04eebc6a376f8e62b41aaa7b071fStephen Hines    return nullptr;
30903fceff6f69a0261a767aab8e62de8aa9301b86cJim Grosbach
310f54e72962991005a3c0cc7dce0c550a14af90792Chris Lattner  // If the PHI is of volatile loads and the load block has multiple
311f54e72962991005a3c0cc7dce0c550a14af90792Chris Lattner  // successors, sinking it would remove a load of the volatile value from
312f54e72962991005a3c0cc7dce0c550a14af90792Chris Lattner  // the path through the other successor.
31303fceff6f69a0261a767aab8e62de8aa9301b86cJim Grosbach  if (isVolatile &&
314f54e72962991005a3c0cc7dce0c550a14af90792Chris Lattner      FirstLI->getParent()->getTerminator()->getNumSuccessors() != 1)
315dce4a407a24b04eebc6a376f8e62b41aaa7b071fStephen Hines    return nullptr;
31603fceff6f69a0261a767aab8e62de8aa9301b86cJim Grosbach
317f54e72962991005a3c0cc7dce0c550a14af90792Chris Lattner  // Check to see if all arguments are the same operation.
318f54e72962991005a3c0cc7dce0c550a14af90792Chris Lattner  for (unsigned i = 1, e = PN.getNumIncomingValues(); i != e; ++i) {
319f54e72962991005a3c0cc7dce0c550a14af90792Chris Lattner    LoadInst *LI = dyn_cast<LoadInst>(PN.getIncomingValue(i));
320f54e72962991005a3c0cc7dce0c550a14af90792Chris Lattner    if (!LI || !LI->hasOneUse())
321dce4a407a24b04eebc6a376f8e62b41aaa7b071fStephen Hines      return nullptr;
32203fceff6f69a0261a767aab8e62de8aa9301b86cJim Grosbach
32303fceff6f69a0261a767aab8e62de8aa9301b86cJim Grosbach    // We can't sink the load if the loaded value could be modified between
324f54e72962991005a3c0cc7dce0c550a14af90792Chris Lattner    // the load and the PHI.
325f54e72962991005a3c0cc7dce0c550a14af90792Chris Lattner    if (LI->isVolatile() != isVolatile ||
326f54e72962991005a3c0cc7dce0c550a14af90792Chris Lattner        LI->getParent() != PN.getIncomingBlock(i) ||
3274c5fb1a311a7a5e3ceb802f5b26329d30f2713b1Chris Lattner        LI->getPointerAddressSpace() != LoadAddrSpace ||
328f54e72962991005a3c0cc7dce0c550a14af90792Chris Lattner        !isSafeAndProfitableToSinkLoad(LI))
329dce4a407a24b04eebc6a376f8e62b41aaa7b071fStephen Hines      return nullptr;
33003fceff6f69a0261a767aab8e62de8aa9301b86cJim Grosbach
331f54e72962991005a3c0cc7dce0c550a14af90792Chris Lattner    // If some of the loads have an alignment specified but not all of them,
332f54e72962991005a3c0cc7dce0c550a14af90792Chris Lattner    // we can't do the transformation.
333f54e72962991005a3c0cc7dce0c550a14af90792Chris Lattner    if ((LoadAlignment != 0) != (LI->getAlignment() != 0))
334dce4a407a24b04eebc6a376f8e62b41aaa7b071fStephen Hines      return nullptr;
33503fceff6f69a0261a767aab8e62de8aa9301b86cJim Grosbach
336f54e72962991005a3c0cc7dce0c550a14af90792Chris Lattner    LoadAlignment = std::min(LoadAlignment, LI->getAlignment());
33703fceff6f69a0261a767aab8e62de8aa9301b86cJim Grosbach
338f54e72962991005a3c0cc7dce0c550a14af90792Chris Lattner    // If the PHI is of volatile loads and the load block has multiple
339f54e72962991005a3c0cc7dce0c550a14af90792Chris Lattner    // successors, sinking it would remove a load of the volatile value from
340f54e72962991005a3c0cc7dce0c550a14af90792Chris Lattner    // the path through the other successor.
341f54e72962991005a3c0cc7dce0c550a14af90792Chris Lattner    if (isVolatile &&
342f54e72962991005a3c0cc7dce0c550a14af90792Chris Lattner        LI->getParent()->getTerminator()->getNumSuccessors() != 1)
343dce4a407a24b04eebc6a376f8e62b41aaa7b071fStephen Hines      return nullptr;
344f54e72962991005a3c0cc7dce0c550a14af90792Chris Lattner  }
34503fceff6f69a0261a767aab8e62de8aa9301b86cJim Grosbach
346f54e72962991005a3c0cc7dce0c550a14af90792Chris Lattner  // Okay, they are all the same operation.  Create a new PHI node of the
347f54e72962991005a3c0cc7dce0c550a14af90792Chris Lattner  // correct type, and PHI together all of the LHS's of the instructions.
348f54e72962991005a3c0cc7dce0c550a14af90792Chris Lattner  PHINode *NewPN = PHINode::Create(FirstLI->getOperand(0)->getType(),
3493ecfc861b4365f341c5c969b40e1afccde676e6fJay Foad                                   PN.getNumIncomingValues(),
350f54e72962991005a3c0cc7dce0c550a14af90792Chris Lattner                                   PN.getName()+".in");
35103fceff6f69a0261a767aab8e62de8aa9301b86cJim Grosbach
352f54e72962991005a3c0cc7dce0c550a14af90792Chris Lattner  Value *InVal = FirstLI->getOperand(0);
353f54e72962991005a3c0cc7dce0c550a14af90792Chris Lattner  NewPN->addIncoming(InVal, PN.getIncomingBlock(0));
35403fceff6f69a0261a767aab8e62de8aa9301b86cJim Grosbach
355f54e72962991005a3c0cc7dce0c550a14af90792Chris Lattner  // Add all operands to the new PHI.
356f54e72962991005a3c0cc7dce0c550a14af90792Chris Lattner  for (unsigned i = 1, e = PN.getNumIncomingValues(); i != e; ++i) {
357f54e72962991005a3c0cc7dce0c550a14af90792Chris Lattner    Value *NewInVal = cast<LoadInst>(PN.getIncomingValue(i))->getOperand(0);
358f54e72962991005a3c0cc7dce0c550a14af90792Chris Lattner    if (NewInVal != InVal)
359dce4a407a24b04eebc6a376f8e62b41aaa7b071fStephen Hines      InVal = nullptr;
360f54e72962991005a3c0cc7dce0c550a14af90792Chris Lattner    NewPN->addIncoming(NewInVal, PN.getIncomingBlock(i));
361f54e72962991005a3c0cc7dce0c550a14af90792Chris Lattner  }
36203fceff6f69a0261a767aab8e62de8aa9301b86cJim Grosbach
363f54e72962991005a3c0cc7dce0c550a14af90792Chris Lattner  Value *PhiVal;
364f54e72962991005a3c0cc7dce0c550a14af90792Chris Lattner  if (InVal) {
365f54e72962991005a3c0cc7dce0c550a14af90792Chris Lattner    // The new PHI unions all of the same values together.  This is really
366f54e72962991005a3c0cc7dce0c550a14af90792Chris Lattner    // common, so we handle it intelligently here for compile-time speed.
367f54e72962991005a3c0cc7dce0c550a14af90792Chris Lattner    PhiVal = InVal;
368f54e72962991005a3c0cc7dce0c550a14af90792Chris Lattner    delete NewPN;
369f54e72962991005a3c0cc7dce0c550a14af90792Chris Lattner  } else {
370f54e72962991005a3c0cc7dce0c550a14af90792Chris Lattner    InsertNewInstBefore(NewPN, PN);
371f54e72962991005a3c0cc7dce0c550a14af90792Chris Lattner    PhiVal = NewPN;
372f54e72962991005a3c0cc7dce0c550a14af90792Chris Lattner  }
37303fceff6f69a0261a767aab8e62de8aa9301b86cJim Grosbach
374f54e72962991005a3c0cc7dce0c550a14af90792Chris Lattner  // If this was a volatile load that we are merging, make sure to loop through
375f54e72962991005a3c0cc7dce0c550a14af90792Chris Lattner  // and mark all the input loads as non-volatile.  If we don't do this, we will
376f54e72962991005a3c0cc7dce0c550a14af90792Chris Lattner  // insert a new volatile load and the old ones will not be deletable.
377f54e72962991005a3c0cc7dce0c550a14af90792Chris Lattner  if (isVolatile)
378f54e72962991005a3c0cc7dce0c550a14af90792Chris Lattner    for (unsigned i = 0, e = PN.getNumIncomingValues(); i != e; ++i)
379f54e72962991005a3c0cc7dce0c550a14af90792Chris Lattner      cast<LoadInst>(PN.getIncomingValue(i))->setVolatile(false);
38003fceff6f69a0261a767aab8e62de8aa9301b86cJim Grosbach
381a311c34d2af7c750f016ef5e4c41bee77a1dfac7Eli Friedman  LoadInst *NewLI = new LoadInst(PhiVal, "", isVolatile, LoadAlignment);
382a311c34d2af7c750f016ef5e4c41bee77a1dfac7Eli Friedman  NewLI->setDebugLoc(FirstLI->getDebugLoc());
383a311c34d2af7c750f016ef5e4c41bee77a1dfac7Eli Friedman  return NewLI;
384f54e72962991005a3c0cc7dce0c550a14af90792Chris Lattner}
385f54e72962991005a3c0cc7dce0c550a14af90792Chris Lattner
386f54e72962991005a3c0cc7dce0c550a14af90792Chris Lattner
387f54e72962991005a3c0cc7dce0c550a14af90792Chris Lattner
388f54e72962991005a3c0cc7dce0c550a14af90792Chris Lattner/// FoldPHIArgOpIntoPHI - If all operands to a PHI node are the same "unary"
389f54e72962991005a3c0cc7dce0c550a14af90792Chris Lattner/// operator and they all are only used by the PHI, PHI together their
390f54e72962991005a3c0cc7dce0c550a14af90792Chris Lattner/// inputs, and do the operation once, to the result of the PHI.
391f54e72962991005a3c0cc7dce0c550a14af90792Chris LattnerInstruction *InstCombiner::FoldPHIArgOpIntoPHI(PHINode &PN) {
392f54e72962991005a3c0cc7dce0c550a14af90792Chris Lattner  Instruction *FirstInst = cast<Instruction>(PN.getIncomingValue(0));
393f54e72962991005a3c0cc7dce0c550a14af90792Chris Lattner
394f54e72962991005a3c0cc7dce0c550a14af90792Chris Lattner  if (isa<GetElementPtrInst>(FirstInst))
395f54e72962991005a3c0cc7dce0c550a14af90792Chris Lattner    return FoldPHIArgGEPIntoPHI(PN);
396f54e72962991005a3c0cc7dce0c550a14af90792Chris Lattner  if (isa<LoadInst>(FirstInst))
397f54e72962991005a3c0cc7dce0c550a14af90792Chris Lattner    return FoldPHIArgLoadIntoPHI(PN);
39803fceff6f69a0261a767aab8e62de8aa9301b86cJim Grosbach
399f54e72962991005a3c0cc7dce0c550a14af90792Chris Lattner  // Scan the instruction, looking for input operations that can be folded away.
400f54e72962991005a3c0cc7dce0c550a14af90792Chris Lattner  // If all input operands to the phi are the same instruction (e.g. a cast from
401f54e72962991005a3c0cc7dce0c550a14af90792Chris Lattner  // the same type or "+42") we can pull the operation through the PHI, reducing
402f54e72962991005a3c0cc7dce0c550a14af90792Chris Lattner  // code size and simplifying code.
403dce4a407a24b04eebc6a376f8e62b41aaa7b071fStephen Hines  Constant *ConstantOp = nullptr;
404dce4a407a24b04eebc6a376f8e62b41aaa7b071fStephen Hines  Type *CastSrcTy = nullptr;
405c8cb8ef9c2d5e354db661022d707a19b3533c00eChris Lattner  bool isNUW = false, isNSW = false, isExact = false;
40603fceff6f69a0261a767aab8e62de8aa9301b86cJim Grosbach
407f54e72962991005a3c0cc7dce0c550a14af90792Chris Lattner  if (isa<CastInst>(FirstInst)) {
408f54e72962991005a3c0cc7dce0c550a14af90792Chris Lattner    CastSrcTy = FirstInst->getOperand(0)->getType();
409f54e72962991005a3c0cc7dce0c550a14af90792Chris Lattner
410f54e72962991005a3c0cc7dce0c550a14af90792Chris Lattner    // Be careful about transforming integer PHIs.  We don't want to pessimize
411f54e72962991005a3c0cc7dce0c550a14af90792Chris Lattner    // the code by turning an i32 into an i1293.
4121df9859c40492511b8aa4321eb76496005d3b75bDuncan Sands    if (PN.getType()->isIntegerTy() && CastSrcTy->isIntegerTy()) {
413f54e72962991005a3c0cc7dce0c550a14af90792Chris Lattner      if (!ShouldChangeType(PN.getType(), CastSrcTy))
414dce4a407a24b04eebc6a376f8e62b41aaa7b071fStephen Hines        return nullptr;
415f54e72962991005a3c0cc7dce0c550a14af90792Chris Lattner    }
416f54e72962991005a3c0cc7dce0c550a14af90792Chris Lattner  } else if (isa<BinaryOperator>(FirstInst) || isa<CmpInst>(FirstInst)) {
41703fceff6f69a0261a767aab8e62de8aa9301b86cJim Grosbach    // Can fold binop, compare or shift here if the RHS is a constant,
418f54e72962991005a3c0cc7dce0c550a14af90792Chris Lattner    // otherwise call FoldPHIArgBinOpIntoPHI.
419f54e72962991005a3c0cc7dce0c550a14af90792Chris Lattner    ConstantOp = dyn_cast<Constant>(FirstInst->getOperand(1));
420dce4a407a24b04eebc6a376f8e62b41aaa7b071fStephen Hines    if (!ConstantOp)
421f54e72962991005a3c0cc7dce0c550a14af90792Chris Lattner      return FoldPHIArgBinOpIntoPHI(PN);
42203fceff6f69a0261a767aab8e62de8aa9301b86cJim Grosbach
423c8cb8ef9c2d5e354db661022d707a19b3533c00eChris Lattner    if (OverflowingBinaryOperator *BO =
424c8cb8ef9c2d5e354db661022d707a19b3533c00eChris Lattner        dyn_cast<OverflowingBinaryOperator>(FirstInst)) {
425c8cb8ef9c2d5e354db661022d707a19b3533c00eChris Lattner      isNUW = BO->hasNoUnsignedWrap();
426c8cb8ef9c2d5e354db661022d707a19b3533c00eChris Lattner      isNSW = BO->hasNoSignedWrap();
427c8cb8ef9c2d5e354db661022d707a19b3533c00eChris Lattner    } else if (PossiblyExactOperator *PEO =
428c8cb8ef9c2d5e354db661022d707a19b3533c00eChris Lattner               dyn_cast<PossiblyExactOperator>(FirstInst))
429c8cb8ef9c2d5e354db661022d707a19b3533c00eChris Lattner      isExact = PEO->isExact();
430f54e72962991005a3c0cc7dce0c550a14af90792Chris Lattner  } else {
431dce4a407a24b04eebc6a376f8e62b41aaa7b071fStephen Hines    return nullptr;  // Cannot fold this operation.
432f54e72962991005a3c0cc7dce0c550a14af90792Chris Lattner  }
433f54e72962991005a3c0cc7dce0c550a14af90792Chris Lattner
434f54e72962991005a3c0cc7dce0c550a14af90792Chris Lattner  // Check to see if all arguments are the same operation.
435f54e72962991005a3c0cc7dce0c550a14af90792Chris Lattner  for (unsigned i = 1, e = PN.getNumIncomingValues(); i != e; ++i) {
436f54e72962991005a3c0cc7dce0c550a14af90792Chris Lattner    Instruction *I = dyn_cast<Instruction>(PN.getIncomingValue(i));
437dce4a407a24b04eebc6a376f8e62b41aaa7b071fStephen Hines    if (!I || !I->hasOneUse() || !I->isSameOperationAs(FirstInst))
438dce4a407a24b04eebc6a376f8e62b41aaa7b071fStephen Hines      return nullptr;
439f54e72962991005a3c0cc7dce0c550a14af90792Chris Lattner    if (CastSrcTy) {
440f54e72962991005a3c0cc7dce0c550a14af90792Chris Lattner      if (I->getOperand(0)->getType() != CastSrcTy)
441dce4a407a24b04eebc6a376f8e62b41aaa7b071fStephen Hines        return nullptr;  // Cast operation must match.
442f54e72962991005a3c0cc7dce0c550a14af90792Chris Lattner    } else if (I->getOperand(1) != ConstantOp) {
443dce4a407a24b04eebc6a376f8e62b41aaa7b071fStephen Hines      return nullptr;
444f54e72962991005a3c0cc7dce0c550a14af90792Chris Lattner    }
44503fceff6f69a0261a767aab8e62de8aa9301b86cJim Grosbach
446c8cb8ef9c2d5e354db661022d707a19b3533c00eChris Lattner    if (isNUW)
447c8cb8ef9c2d5e354db661022d707a19b3533c00eChris Lattner      isNUW = cast<OverflowingBinaryOperator>(I)->hasNoUnsignedWrap();
448c8cb8ef9c2d5e354db661022d707a19b3533c00eChris Lattner    if (isNSW)
449c8cb8ef9c2d5e354db661022d707a19b3533c00eChris Lattner      isNSW = cast<OverflowingBinaryOperator>(I)->hasNoSignedWrap();
450c8cb8ef9c2d5e354db661022d707a19b3533c00eChris Lattner    if (isExact)
451c8cb8ef9c2d5e354db661022d707a19b3533c00eChris Lattner      isExact = cast<PossiblyExactOperator>(I)->isExact();
452f54e72962991005a3c0cc7dce0c550a14af90792Chris Lattner  }
453f54e72962991005a3c0cc7dce0c550a14af90792Chris Lattner
454f54e72962991005a3c0cc7dce0c550a14af90792Chris Lattner  // Okay, they are all the same operation.  Create a new PHI node of the
455f54e72962991005a3c0cc7dce0c550a14af90792Chris Lattner  // correct type, and PHI together all of the LHS's of the instructions.
456f54e72962991005a3c0cc7dce0c550a14af90792Chris Lattner  PHINode *NewPN = PHINode::Create(FirstInst->getOperand(0)->getType(),
4573ecfc861b4365f341c5c969b40e1afccde676e6fJay Foad                                   PN.getNumIncomingValues(),
458f54e72962991005a3c0cc7dce0c550a14af90792Chris Lattner                                   PN.getName()+".in");
459f54e72962991005a3c0cc7dce0c550a14af90792Chris Lattner
460f54e72962991005a3c0cc7dce0c550a14af90792Chris Lattner  Value *InVal = FirstInst->getOperand(0);
461f54e72962991005a3c0cc7dce0c550a14af90792Chris Lattner  NewPN->addIncoming(InVal, PN.getIncomingBlock(0));
462f54e72962991005a3c0cc7dce0c550a14af90792Chris Lattner
463f54e72962991005a3c0cc7dce0c550a14af90792Chris Lattner  // Add all operands to the new PHI.
464f54e72962991005a3c0cc7dce0c550a14af90792Chris Lattner  for (unsigned i = 1, e = PN.getNumIncomingValues(); i != e; ++i) {
465f54e72962991005a3c0cc7dce0c550a14af90792Chris Lattner    Value *NewInVal = cast<Instruction>(PN.getIncomingValue(i))->getOperand(0);
466f54e72962991005a3c0cc7dce0c550a14af90792Chris Lattner    if (NewInVal != InVal)
467dce4a407a24b04eebc6a376f8e62b41aaa7b071fStephen Hines      InVal = nullptr;
468f54e72962991005a3c0cc7dce0c550a14af90792Chris Lattner    NewPN->addIncoming(NewInVal, PN.getIncomingBlock(i));
469f54e72962991005a3c0cc7dce0c550a14af90792Chris Lattner  }
470f54e72962991005a3c0cc7dce0c550a14af90792Chris Lattner
471f54e72962991005a3c0cc7dce0c550a14af90792Chris Lattner  Value *PhiVal;
472f54e72962991005a3c0cc7dce0c550a14af90792Chris Lattner  if (InVal) {
473f54e72962991005a3c0cc7dce0c550a14af90792Chris Lattner    // The new PHI unions all of the same values together.  This is really
474f54e72962991005a3c0cc7dce0c550a14af90792Chris Lattner    // common, so we handle it intelligently here for compile-time speed.
475f54e72962991005a3c0cc7dce0c550a14af90792Chris Lattner    PhiVal = InVal;
476f54e72962991005a3c0cc7dce0c550a14af90792Chris Lattner    delete NewPN;
477f54e72962991005a3c0cc7dce0c550a14af90792Chris Lattner  } else {
478f54e72962991005a3c0cc7dce0c550a14af90792Chris Lattner    InsertNewInstBefore(NewPN, PN);
479f54e72962991005a3c0cc7dce0c550a14af90792Chris Lattner    PhiVal = NewPN;
480f54e72962991005a3c0cc7dce0c550a14af90792Chris Lattner  }
481f54e72962991005a3c0cc7dce0c550a14af90792Chris Lattner
482f54e72962991005a3c0cc7dce0c550a14af90792Chris Lattner  // Insert and return the new operation.
483a311c34d2af7c750f016ef5e4c41bee77a1dfac7Eli Friedman  if (CastInst *FirstCI = dyn_cast<CastInst>(FirstInst)) {
484a311c34d2af7c750f016ef5e4c41bee77a1dfac7Eli Friedman    CastInst *NewCI = CastInst::Create(FirstCI->getOpcode(), PhiVal,
485a311c34d2af7c750f016ef5e4c41bee77a1dfac7Eli Friedman                                       PN.getType());
486a311c34d2af7c750f016ef5e4c41bee77a1dfac7Eli Friedman    NewCI->setDebugLoc(FirstInst->getDebugLoc());
487a311c34d2af7c750f016ef5e4c41bee77a1dfac7Eli Friedman    return NewCI;
488a311c34d2af7c750f016ef5e4c41bee77a1dfac7Eli Friedman  }
48903fceff6f69a0261a767aab8e62de8aa9301b86cJim Grosbach
490c8cb8ef9c2d5e354db661022d707a19b3533c00eChris Lattner  if (BinaryOperator *BinOp = dyn_cast<BinaryOperator>(FirstInst)) {
491c8cb8ef9c2d5e354db661022d707a19b3533c00eChris Lattner    BinOp = BinaryOperator::Create(BinOp->getOpcode(), PhiVal, ConstantOp);
492c8cb8ef9c2d5e354db661022d707a19b3533c00eChris Lattner    if (isNUW) BinOp->setHasNoUnsignedWrap();
493c8cb8ef9c2d5e354db661022d707a19b3533c00eChris Lattner    if (isNSW) BinOp->setHasNoSignedWrap();
494c8cb8ef9c2d5e354db661022d707a19b3533c00eChris Lattner    if (isExact) BinOp->setIsExact();
495a311c34d2af7c750f016ef5e4c41bee77a1dfac7Eli Friedman    BinOp->setDebugLoc(FirstInst->getDebugLoc());
496c8cb8ef9c2d5e354db661022d707a19b3533c00eChris Lattner    return BinOp;
497c8cb8ef9c2d5e354db661022d707a19b3533c00eChris Lattner  }
49803fceff6f69a0261a767aab8e62de8aa9301b86cJim Grosbach
499f54e72962991005a3c0cc7dce0c550a14af90792Chris Lattner  CmpInst *CIOp = cast<CmpInst>(FirstInst);
500a311c34d2af7c750f016ef5e4c41bee77a1dfac7Eli Friedman  CmpInst *NewCI = CmpInst::Create(CIOp->getOpcode(), CIOp->getPredicate(),
501a311c34d2af7c750f016ef5e4c41bee77a1dfac7Eli Friedman                                   PhiVal, ConstantOp);
502a311c34d2af7c750f016ef5e4c41bee77a1dfac7Eli Friedman  NewCI->setDebugLoc(FirstInst->getDebugLoc());
503a311c34d2af7c750f016ef5e4c41bee77a1dfac7Eli Friedman  return NewCI;
504f54e72962991005a3c0cc7dce0c550a14af90792Chris Lattner}
505f54e72962991005a3c0cc7dce0c550a14af90792Chris Lattner
506f54e72962991005a3c0cc7dce0c550a14af90792Chris Lattner/// DeadPHICycle - Return true if this PHI node is only used by a PHI node cycle
507f54e72962991005a3c0cc7dce0c550a14af90792Chris Lattner/// that is dead.
508f54e72962991005a3c0cc7dce0c550a14af90792Chris Lattnerstatic bool DeadPHICycle(PHINode *PN,
509f54e72962991005a3c0cc7dce0c550a14af90792Chris Lattner                         SmallPtrSet<PHINode*, 16> &PotentiallyDeadPHIs) {
510f54e72962991005a3c0cc7dce0c550a14af90792Chris Lattner  if (PN->use_empty()) return true;
511f54e72962991005a3c0cc7dce0c550a14af90792Chris Lattner  if (!PN->hasOneUse()) return false;
512f54e72962991005a3c0cc7dce0c550a14af90792Chris Lattner
513f54e72962991005a3c0cc7dce0c550a14af90792Chris Lattner  // Remember this node, and if we find the cycle, return.
514f54e72962991005a3c0cc7dce0c550a14af90792Chris Lattner  if (!PotentiallyDeadPHIs.insert(PN))
515f54e72962991005a3c0cc7dce0c550a14af90792Chris Lattner    return true;
51603fceff6f69a0261a767aab8e62de8aa9301b86cJim Grosbach
517f54e72962991005a3c0cc7dce0c550a14af90792Chris Lattner  // Don't scan crazily complex things.
518f54e72962991005a3c0cc7dce0c550a14af90792Chris Lattner  if (PotentiallyDeadPHIs.size() == 16)
519f54e72962991005a3c0cc7dce0c550a14af90792Chris Lattner    return false;
520f54e72962991005a3c0cc7dce0c550a14af90792Chris Lattner
52136b56886974eae4f9c5ebc96befd3e7bfe5de338Stephen Hines  if (PHINode *PU = dyn_cast<PHINode>(PN->user_back()))
522f54e72962991005a3c0cc7dce0c550a14af90792Chris Lattner    return DeadPHICycle(PU, PotentiallyDeadPHIs);
523f54e72962991005a3c0cc7dce0c550a14af90792Chris Lattner
524f54e72962991005a3c0cc7dce0c550a14af90792Chris Lattner  return false;
525f54e72962991005a3c0cc7dce0c550a14af90792Chris Lattner}
526f54e72962991005a3c0cc7dce0c550a14af90792Chris Lattner
527f54e72962991005a3c0cc7dce0c550a14af90792Chris Lattner/// PHIsEqualValue - Return true if this phi node is always equal to
528f54e72962991005a3c0cc7dce0c550a14af90792Chris Lattner/// NonPhiInVal.  This happens with mutually cyclic phi nodes like:
529f54e72962991005a3c0cc7dce0c550a14af90792Chris Lattner///   z = some value; x = phi (y, z); y = phi (x, z)
53003fceff6f69a0261a767aab8e62de8aa9301b86cJim Grosbachstatic bool PHIsEqualValue(PHINode *PN, Value *NonPhiInVal,
531f54e72962991005a3c0cc7dce0c550a14af90792Chris Lattner                           SmallPtrSet<PHINode*, 16> &ValueEqualPHIs) {
532f54e72962991005a3c0cc7dce0c550a14af90792Chris Lattner  // See if we already saw this PHI node.
533f54e72962991005a3c0cc7dce0c550a14af90792Chris Lattner  if (!ValueEqualPHIs.insert(PN))
534f54e72962991005a3c0cc7dce0c550a14af90792Chris Lattner    return true;
53503fceff6f69a0261a767aab8e62de8aa9301b86cJim Grosbach
536f54e72962991005a3c0cc7dce0c550a14af90792Chris Lattner  // Don't scan crazily complex things.
537f54e72962991005a3c0cc7dce0c550a14af90792Chris Lattner  if (ValueEqualPHIs.size() == 16)
538f54e72962991005a3c0cc7dce0c550a14af90792Chris Lattner    return false;
53903fceff6f69a0261a767aab8e62de8aa9301b86cJim Grosbach
540f54e72962991005a3c0cc7dce0c550a14af90792Chris Lattner  // Scan the operands to see if they are either phi nodes or are equal to
541f54e72962991005a3c0cc7dce0c550a14af90792Chris Lattner  // the value.
542f54e72962991005a3c0cc7dce0c550a14af90792Chris Lattner  for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) {
543f54e72962991005a3c0cc7dce0c550a14af90792Chris Lattner    Value *Op = PN->getIncomingValue(i);
544f54e72962991005a3c0cc7dce0c550a14af90792Chris Lattner    if (PHINode *OpPN = dyn_cast<PHINode>(Op)) {
545f54e72962991005a3c0cc7dce0c550a14af90792Chris Lattner      if (!PHIsEqualValue(OpPN, NonPhiInVal, ValueEqualPHIs))
546f54e72962991005a3c0cc7dce0c550a14af90792Chris Lattner        return false;
547f54e72962991005a3c0cc7dce0c550a14af90792Chris Lattner    } else if (Op != NonPhiInVal)
548f54e72962991005a3c0cc7dce0c550a14af90792Chris Lattner      return false;
549f54e72962991005a3c0cc7dce0c550a14af90792Chris Lattner  }
55003fceff6f69a0261a767aab8e62de8aa9301b86cJim Grosbach
551f54e72962991005a3c0cc7dce0c550a14af90792Chris Lattner  return true;
552f54e72962991005a3c0cc7dce0c550a14af90792Chris Lattner}
553f54e72962991005a3c0cc7dce0c550a14af90792Chris Lattner
554f54e72962991005a3c0cc7dce0c550a14af90792Chris Lattner
555f54e72962991005a3c0cc7dce0c550a14af90792Chris Lattnernamespace {
556f54e72962991005a3c0cc7dce0c550a14af90792Chris Lattnerstruct PHIUsageRecord {
557f54e72962991005a3c0cc7dce0c550a14af90792Chris Lattner  unsigned PHIId;     // The ID # of the PHI (something determinstic to sort on)
558f54e72962991005a3c0cc7dce0c550a14af90792Chris Lattner  unsigned Shift;     // The amount shifted.
559f54e72962991005a3c0cc7dce0c550a14af90792Chris Lattner  Instruction *Inst;  // The trunc instruction.
56003fceff6f69a0261a767aab8e62de8aa9301b86cJim Grosbach
561f54e72962991005a3c0cc7dce0c550a14af90792Chris Lattner  PHIUsageRecord(unsigned pn, unsigned Sh, Instruction *User)
562f54e72962991005a3c0cc7dce0c550a14af90792Chris Lattner    : PHIId(pn), Shift(Sh), Inst(User) {}
56303fceff6f69a0261a767aab8e62de8aa9301b86cJim Grosbach
564f54e72962991005a3c0cc7dce0c550a14af90792Chris Lattner  bool operator<(const PHIUsageRecord &RHS) const {
565f54e72962991005a3c0cc7dce0c550a14af90792Chris Lattner    if (PHIId < RHS.PHIId) return true;
566f54e72962991005a3c0cc7dce0c550a14af90792Chris Lattner    if (PHIId > RHS.PHIId) return false;
567f54e72962991005a3c0cc7dce0c550a14af90792Chris Lattner    if (Shift < RHS.Shift) return true;
568f54e72962991005a3c0cc7dce0c550a14af90792Chris Lattner    if (Shift > RHS.Shift) return false;
569f54e72962991005a3c0cc7dce0c550a14af90792Chris Lattner    return Inst->getType()->getPrimitiveSizeInBits() <
570f54e72962991005a3c0cc7dce0c550a14af90792Chris Lattner           RHS.Inst->getType()->getPrimitiveSizeInBits();
571f54e72962991005a3c0cc7dce0c550a14af90792Chris Lattner  }
572f54e72962991005a3c0cc7dce0c550a14af90792Chris Lattner};
57303fceff6f69a0261a767aab8e62de8aa9301b86cJim Grosbach
574f54e72962991005a3c0cc7dce0c550a14af90792Chris Lattnerstruct LoweredPHIRecord {
575f54e72962991005a3c0cc7dce0c550a14af90792Chris Lattner  PHINode *PN;        // The PHI that was lowered.
576f54e72962991005a3c0cc7dce0c550a14af90792Chris Lattner  unsigned Shift;     // The amount shifted.
577f54e72962991005a3c0cc7dce0c550a14af90792Chris Lattner  unsigned Width;     // The width extracted.
57803fceff6f69a0261a767aab8e62de8aa9301b86cJim Grosbach
579db125cfaf57cc83e7dd7453de2d509bc8efd0e5eChris Lattner  LoweredPHIRecord(PHINode *pn, unsigned Sh, Type *Ty)
580f54e72962991005a3c0cc7dce0c550a14af90792Chris Lattner    : PN(pn), Shift(Sh), Width(Ty->getPrimitiveSizeInBits()) {}
58103fceff6f69a0261a767aab8e62de8aa9301b86cJim Grosbach
582f54e72962991005a3c0cc7dce0c550a14af90792Chris Lattner  // Ctor form used by DenseMap.
583f54e72962991005a3c0cc7dce0c550a14af90792Chris Lattner  LoweredPHIRecord(PHINode *pn, unsigned Sh)
584f54e72962991005a3c0cc7dce0c550a14af90792Chris Lattner    : PN(pn), Shift(Sh), Width(0) {}
585f54e72962991005a3c0cc7dce0c550a14af90792Chris Lattner};
586f54e72962991005a3c0cc7dce0c550a14af90792Chris Lattner}
587f54e72962991005a3c0cc7dce0c550a14af90792Chris Lattner
588f54e72962991005a3c0cc7dce0c550a14af90792Chris Lattnernamespace llvm {
589f54e72962991005a3c0cc7dce0c550a14af90792Chris Lattner  template<>
590f54e72962991005a3c0cc7dce0c550a14af90792Chris Lattner  struct DenseMapInfo<LoweredPHIRecord> {
591f54e72962991005a3c0cc7dce0c550a14af90792Chris Lattner    static inline LoweredPHIRecord getEmptyKey() {
592dce4a407a24b04eebc6a376f8e62b41aaa7b071fStephen Hines      return LoweredPHIRecord(nullptr, 0);
593f54e72962991005a3c0cc7dce0c550a14af90792Chris Lattner    }
594f54e72962991005a3c0cc7dce0c550a14af90792Chris Lattner    static inline LoweredPHIRecord getTombstoneKey() {
595dce4a407a24b04eebc6a376f8e62b41aaa7b071fStephen Hines      return LoweredPHIRecord(nullptr, 1);
596f54e72962991005a3c0cc7dce0c550a14af90792Chris Lattner    }
597f54e72962991005a3c0cc7dce0c550a14af90792Chris Lattner    static unsigned getHashValue(const LoweredPHIRecord &Val) {
598f54e72962991005a3c0cc7dce0c550a14af90792Chris Lattner      return DenseMapInfo<PHINode*>::getHashValue(Val.PN) ^ (Val.Shift>>3) ^
599f54e72962991005a3c0cc7dce0c550a14af90792Chris Lattner             (Val.Width>>3);
600f54e72962991005a3c0cc7dce0c550a14af90792Chris Lattner    }
601f54e72962991005a3c0cc7dce0c550a14af90792Chris Lattner    static bool isEqual(const LoweredPHIRecord &LHS,
602f54e72962991005a3c0cc7dce0c550a14af90792Chris Lattner                        const LoweredPHIRecord &RHS) {
603f54e72962991005a3c0cc7dce0c550a14af90792Chris Lattner      return LHS.PN == RHS.PN && LHS.Shift == RHS.Shift &&
604f54e72962991005a3c0cc7dce0c550a14af90792Chris Lattner             LHS.Width == RHS.Width;
605f54e72962991005a3c0cc7dce0c550a14af90792Chris Lattner    }
606f54e72962991005a3c0cc7dce0c550a14af90792Chris Lattner  };
607f54e72962991005a3c0cc7dce0c550a14af90792Chris Lattner}
608f54e72962991005a3c0cc7dce0c550a14af90792Chris Lattner
609f54e72962991005a3c0cc7dce0c550a14af90792Chris Lattner
610f54e72962991005a3c0cc7dce0c550a14af90792Chris Lattner/// SliceUpIllegalIntegerPHI - This is an integer PHI and we know that it has an
611f54e72962991005a3c0cc7dce0c550a14af90792Chris Lattner/// illegal type: see if it is only used by trunc or trunc(lshr) operations.  If
612f54e72962991005a3c0cc7dce0c550a14af90792Chris Lattner/// so, we split the PHI into the various pieces being extracted.  This sort of
613f54e72962991005a3c0cc7dce0c550a14af90792Chris Lattner/// thing is introduced when SROA promotes an aggregate to large integer values.
614f54e72962991005a3c0cc7dce0c550a14af90792Chris Lattner///
615f54e72962991005a3c0cc7dce0c550a14af90792Chris Lattner/// TODO: The user of the trunc may be an bitcast to float/double/vector or an
616f54e72962991005a3c0cc7dce0c550a14af90792Chris Lattner/// inttoptr.  We should produce new PHIs in the right type.
617f54e72962991005a3c0cc7dce0c550a14af90792Chris Lattner///
618f54e72962991005a3c0cc7dce0c550a14af90792Chris LattnerInstruction *InstCombiner::SliceUpIllegalIntegerPHI(PHINode &FirstPhi) {
619f54e72962991005a3c0cc7dce0c550a14af90792Chris Lattner  // PHIUsers - Keep track of all of the truncated values extracted from a set
620f54e72962991005a3c0cc7dce0c550a14af90792Chris Lattner  // of PHIs, along with their offset.  These are the things we want to rewrite.
621f54e72962991005a3c0cc7dce0c550a14af90792Chris Lattner  SmallVector<PHIUsageRecord, 16> PHIUsers;
62203fceff6f69a0261a767aab8e62de8aa9301b86cJim Grosbach
623f54e72962991005a3c0cc7dce0c550a14af90792Chris Lattner  // PHIs are often mutually cyclic, so we keep track of a whole set of PHI
624f54e72962991005a3c0cc7dce0c550a14af90792Chris Lattner  // nodes which are extracted from. PHIsToSlice is a set we use to avoid
625f54e72962991005a3c0cc7dce0c550a14af90792Chris Lattner  // revisiting PHIs, PHIsInspected is a ordered list of PHIs that we need to
626f54e72962991005a3c0cc7dce0c550a14af90792Chris Lattner  // check the uses of (to ensure they are all extracts).
627f54e72962991005a3c0cc7dce0c550a14af90792Chris Lattner  SmallVector<PHINode*, 8> PHIsToSlice;
628f54e72962991005a3c0cc7dce0c550a14af90792Chris Lattner  SmallPtrSet<PHINode*, 8> PHIsInspected;
62903fceff6f69a0261a767aab8e62de8aa9301b86cJim Grosbach
630f54e72962991005a3c0cc7dce0c550a14af90792Chris Lattner  PHIsToSlice.push_back(&FirstPhi);
631f54e72962991005a3c0cc7dce0c550a14af90792Chris Lattner  PHIsInspected.insert(&FirstPhi);
63203fceff6f69a0261a767aab8e62de8aa9301b86cJim Grosbach
633f54e72962991005a3c0cc7dce0c550a14af90792Chris Lattner  for (unsigned PHIId = 0; PHIId != PHIsToSlice.size(); ++PHIId) {
634f54e72962991005a3c0cc7dce0c550a14af90792Chris Lattner    PHINode *PN = PHIsToSlice[PHIId];
63503fceff6f69a0261a767aab8e62de8aa9301b86cJim Grosbach
636f54e72962991005a3c0cc7dce0c550a14af90792Chris Lattner    // Scan the input list of the PHI.  If any input is an invoke, and if the
637f54e72962991005a3c0cc7dce0c550a14af90792Chris Lattner    // input is defined in the predecessor, then we won't be split the critical
638f54e72962991005a3c0cc7dce0c550a14af90792Chris Lattner    // edge which is required to insert a truncate.  Because of this, we have to
639f54e72962991005a3c0cc7dce0c550a14af90792Chris Lattner    // bail out.
640f54e72962991005a3c0cc7dce0c550a14af90792Chris Lattner    for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) {
641f54e72962991005a3c0cc7dce0c550a14af90792Chris Lattner      InvokeInst *II = dyn_cast<InvokeInst>(PN->getIncomingValue(i));
642dce4a407a24b04eebc6a376f8e62b41aaa7b071fStephen Hines      if (!II) continue;
643f54e72962991005a3c0cc7dce0c550a14af90792Chris Lattner      if (II->getParent() != PN->getIncomingBlock(i))
644f54e72962991005a3c0cc7dce0c550a14af90792Chris Lattner        continue;
64503fceff6f69a0261a767aab8e62de8aa9301b86cJim Grosbach
646f54e72962991005a3c0cc7dce0c550a14af90792Chris Lattner      // If we have a phi, and if it's directly in the predecessor, then we have
647f54e72962991005a3c0cc7dce0c550a14af90792Chris Lattner      // a critical edge where we need to put the truncate.  Since we can't
648f54e72962991005a3c0cc7dce0c550a14af90792Chris Lattner      // split the edge in instcombine, we have to bail out.
649dce4a407a24b04eebc6a376f8e62b41aaa7b071fStephen Hines      return nullptr;
650f54e72962991005a3c0cc7dce0c550a14af90792Chris Lattner    }
65103fceff6f69a0261a767aab8e62de8aa9301b86cJim Grosbach
65236b56886974eae4f9c5ebc96befd3e7bfe5de338Stephen Hines    for (User *U : PN->users()) {
65336b56886974eae4f9c5ebc96befd3e7bfe5de338Stephen Hines      Instruction *UserI = cast<Instruction>(U);
65403fceff6f69a0261a767aab8e62de8aa9301b86cJim Grosbach
655f54e72962991005a3c0cc7dce0c550a14af90792Chris Lattner      // If the user is a PHI, inspect its uses recursively.
65636b56886974eae4f9c5ebc96befd3e7bfe5de338Stephen Hines      if (PHINode *UserPN = dyn_cast<PHINode>(UserI)) {
657f54e72962991005a3c0cc7dce0c550a14af90792Chris Lattner        if (PHIsInspected.insert(UserPN))
658f54e72962991005a3c0cc7dce0c550a14af90792Chris Lattner          PHIsToSlice.push_back(UserPN);
659f54e72962991005a3c0cc7dce0c550a14af90792Chris Lattner        continue;
660f54e72962991005a3c0cc7dce0c550a14af90792Chris Lattner      }
66103fceff6f69a0261a767aab8e62de8aa9301b86cJim Grosbach
662f54e72962991005a3c0cc7dce0c550a14af90792Chris Lattner      // Truncates are always ok.
66336b56886974eae4f9c5ebc96befd3e7bfe5de338Stephen Hines      if (isa<TruncInst>(UserI)) {
66436b56886974eae4f9c5ebc96befd3e7bfe5de338Stephen Hines        PHIUsers.push_back(PHIUsageRecord(PHIId, 0, UserI));
665f54e72962991005a3c0cc7dce0c550a14af90792Chris Lattner        continue;
666f54e72962991005a3c0cc7dce0c550a14af90792Chris Lattner      }
66703fceff6f69a0261a767aab8e62de8aa9301b86cJim Grosbach
668f54e72962991005a3c0cc7dce0c550a14af90792Chris Lattner      // Otherwise it must be a lshr which can only be used by one trunc.
66936b56886974eae4f9c5ebc96befd3e7bfe5de338Stephen Hines      if (UserI->getOpcode() != Instruction::LShr ||
67036b56886974eae4f9c5ebc96befd3e7bfe5de338Stephen Hines          !UserI->hasOneUse() || !isa<TruncInst>(UserI->user_back()) ||
67136b56886974eae4f9c5ebc96befd3e7bfe5de338Stephen Hines          !isa<ConstantInt>(UserI->getOperand(1)))
672dce4a407a24b04eebc6a376f8e62b41aaa7b071fStephen Hines        return nullptr;
67303fceff6f69a0261a767aab8e62de8aa9301b86cJim Grosbach
67436b56886974eae4f9c5ebc96befd3e7bfe5de338Stephen Hines      unsigned Shift = cast<ConstantInt>(UserI->getOperand(1))->getZExtValue();
67536b56886974eae4f9c5ebc96befd3e7bfe5de338Stephen Hines      PHIUsers.push_back(PHIUsageRecord(PHIId, Shift, UserI->user_back()));
676f54e72962991005a3c0cc7dce0c550a14af90792Chris Lattner    }
677f54e72962991005a3c0cc7dce0c550a14af90792Chris Lattner  }
67803fceff6f69a0261a767aab8e62de8aa9301b86cJim Grosbach
679f54e72962991005a3c0cc7dce0c550a14af90792Chris Lattner  // If we have no users, they must be all self uses, just nuke the PHI.
680f54e72962991005a3c0cc7dce0c550a14af90792Chris Lattner  if (PHIUsers.empty())
681f54e72962991005a3c0cc7dce0c550a14af90792Chris Lattner    return ReplaceInstUsesWith(FirstPhi, UndefValue::get(FirstPhi.getType()));
68203fceff6f69a0261a767aab8e62de8aa9301b86cJim Grosbach
683f54e72962991005a3c0cc7dce0c550a14af90792Chris Lattner  // If this phi node is transformable, create new PHIs for all the pieces
684f54e72962991005a3c0cc7dce0c550a14af90792Chris Lattner  // extracted out of it.  First, sort the users by their offset and size.
685f54e72962991005a3c0cc7dce0c550a14af90792Chris Lattner  array_pod_sort(PHIUsers.begin(), PHIUsers.end());
68603fceff6f69a0261a767aab8e62de8aa9301b86cJim Grosbach
687596aa123f46158639c836f1d53b89a9d7898c4b7Matt Arsenault  DEBUG(dbgs() << "SLICING UP PHI: " << FirstPhi << '\n';
688596aa123f46158639c836f1d53b89a9d7898c4b7Matt Arsenault        for (unsigned i = 1, e = PHIsToSlice.size(); i != e; ++i)
689596aa123f46158639c836f1d53b89a9d7898c4b7Matt Arsenault          dbgs() << "AND USER PHI #" << i << ": " << *PHIsToSlice[i] << '\n';
690596aa123f46158639c836f1d53b89a9d7898c4b7Matt Arsenault    );
69103fceff6f69a0261a767aab8e62de8aa9301b86cJim Grosbach
692f54e72962991005a3c0cc7dce0c550a14af90792Chris Lattner  // PredValues - This is a temporary used when rewriting PHI nodes.  It is
693f54e72962991005a3c0cc7dce0c550a14af90792Chris Lattner  // hoisted out here to avoid construction/destruction thrashing.
694f54e72962991005a3c0cc7dce0c550a14af90792Chris Lattner  DenseMap<BasicBlock*, Value*> PredValues;
69503fceff6f69a0261a767aab8e62de8aa9301b86cJim Grosbach
696f54e72962991005a3c0cc7dce0c550a14af90792Chris Lattner  // ExtractedVals - Each new PHI we introduce is saved here so we don't
697f54e72962991005a3c0cc7dce0c550a14af90792Chris Lattner  // introduce redundant PHIs.
698f54e72962991005a3c0cc7dce0c550a14af90792Chris Lattner  DenseMap<LoweredPHIRecord, PHINode*> ExtractedVals;
69903fceff6f69a0261a767aab8e62de8aa9301b86cJim Grosbach
700f54e72962991005a3c0cc7dce0c550a14af90792Chris Lattner  for (unsigned UserI = 0, UserE = PHIUsers.size(); UserI != UserE; ++UserI) {
701f54e72962991005a3c0cc7dce0c550a14af90792Chris Lattner    unsigned PHIId = PHIUsers[UserI].PHIId;
702f54e72962991005a3c0cc7dce0c550a14af90792Chris Lattner    PHINode *PN = PHIsToSlice[PHIId];
703f54e72962991005a3c0cc7dce0c550a14af90792Chris Lattner    unsigned Offset = PHIUsers[UserI].Shift;
704db125cfaf57cc83e7dd7453de2d509bc8efd0e5eChris Lattner    Type *Ty = PHIUsers[UserI].Inst->getType();
70503fceff6f69a0261a767aab8e62de8aa9301b86cJim Grosbach
706f54e72962991005a3c0cc7dce0c550a14af90792Chris Lattner    PHINode *EltPHI;
70703fceff6f69a0261a767aab8e62de8aa9301b86cJim Grosbach
708f54e72962991005a3c0cc7dce0c550a14af90792Chris Lattner    // If we've already lowered a user like this, reuse the previously lowered
709f54e72962991005a3c0cc7dce0c550a14af90792Chris Lattner    // value.
710dce4a407a24b04eebc6a376f8e62b41aaa7b071fStephen Hines    if ((EltPHI = ExtractedVals[LoweredPHIRecord(PN, Offset, Ty)]) == nullptr) {
71103fceff6f69a0261a767aab8e62de8aa9301b86cJim Grosbach
712f54e72962991005a3c0cc7dce0c550a14af90792Chris Lattner      // Otherwise, Create the new PHI node for this user.
7133ecfc861b4365f341c5c969b40e1afccde676e6fJay Foad      EltPHI = PHINode::Create(Ty, PN->getNumIncomingValues(),
7143ecfc861b4365f341c5c969b40e1afccde676e6fJay Foad                               PN->getName()+".off"+Twine(Offset), PN);
715f54e72962991005a3c0cc7dce0c550a14af90792Chris Lattner      assert(EltPHI->getType() != PN->getType() &&
716f54e72962991005a3c0cc7dce0c550a14af90792Chris Lattner             "Truncate didn't shrink phi?");
71703fceff6f69a0261a767aab8e62de8aa9301b86cJim Grosbach
718f54e72962991005a3c0cc7dce0c550a14af90792Chris Lattner      for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) {
719f54e72962991005a3c0cc7dce0c550a14af90792Chris Lattner        BasicBlock *Pred = PN->getIncomingBlock(i);
720f54e72962991005a3c0cc7dce0c550a14af90792Chris Lattner        Value *&PredVal = PredValues[Pred];
72103fceff6f69a0261a767aab8e62de8aa9301b86cJim Grosbach
722f54e72962991005a3c0cc7dce0c550a14af90792Chris Lattner        // If we already have a value for this predecessor, reuse it.
723f54e72962991005a3c0cc7dce0c550a14af90792Chris Lattner        if (PredVal) {
724f54e72962991005a3c0cc7dce0c550a14af90792Chris Lattner          EltPHI->addIncoming(PredVal, Pred);
725f54e72962991005a3c0cc7dce0c550a14af90792Chris Lattner          continue;
726f54e72962991005a3c0cc7dce0c550a14af90792Chris Lattner        }
727f54e72962991005a3c0cc7dce0c550a14af90792Chris Lattner
728f54e72962991005a3c0cc7dce0c550a14af90792Chris Lattner        // Handle the PHI self-reuse case.
729f54e72962991005a3c0cc7dce0c550a14af90792Chris Lattner        Value *InVal = PN->getIncomingValue(i);
730f54e72962991005a3c0cc7dce0c550a14af90792Chris Lattner        if (InVal == PN) {
731f54e72962991005a3c0cc7dce0c550a14af90792Chris Lattner          PredVal = EltPHI;
732f54e72962991005a3c0cc7dce0c550a14af90792Chris Lattner          EltPHI->addIncoming(PredVal, Pred);
733f54e72962991005a3c0cc7dce0c550a14af90792Chris Lattner          continue;
734f54e72962991005a3c0cc7dce0c550a14af90792Chris Lattner        }
73503fceff6f69a0261a767aab8e62de8aa9301b86cJim Grosbach
736f54e72962991005a3c0cc7dce0c550a14af90792Chris Lattner        if (PHINode *InPHI = dyn_cast<PHINode>(PN)) {
737f54e72962991005a3c0cc7dce0c550a14af90792Chris Lattner          // If the incoming value was a PHI, and if it was one of the PHIs we
738f54e72962991005a3c0cc7dce0c550a14af90792Chris Lattner          // already rewrote it, just use the lowered value.
739f54e72962991005a3c0cc7dce0c550a14af90792Chris Lattner          if (Value *Res = ExtractedVals[LoweredPHIRecord(InPHI, Offset, Ty)]) {
740f54e72962991005a3c0cc7dce0c550a14af90792Chris Lattner            PredVal = Res;
741f54e72962991005a3c0cc7dce0c550a14af90792Chris Lattner            EltPHI->addIncoming(PredVal, Pred);
742f54e72962991005a3c0cc7dce0c550a14af90792Chris Lattner            continue;
743f54e72962991005a3c0cc7dce0c550a14af90792Chris Lattner          }
744f54e72962991005a3c0cc7dce0c550a14af90792Chris Lattner        }
74503fceff6f69a0261a767aab8e62de8aa9301b86cJim Grosbach
746f54e72962991005a3c0cc7dce0c550a14af90792Chris Lattner        // Otherwise, do an extract in the predecessor.
747f54e72962991005a3c0cc7dce0c550a14af90792Chris Lattner        Builder->SetInsertPoint(Pred, Pred->getTerminator());
748f54e72962991005a3c0cc7dce0c550a14af90792Chris Lattner        Value *Res = InVal;
749f54e72962991005a3c0cc7dce0c550a14af90792Chris Lattner        if (Offset)
750f54e72962991005a3c0cc7dce0c550a14af90792Chris Lattner          Res = Builder->CreateLShr(Res, ConstantInt::get(InVal->getType(),
751f54e72962991005a3c0cc7dce0c550a14af90792Chris Lattner                                                          Offset), "extract");
752f54e72962991005a3c0cc7dce0c550a14af90792Chris Lattner        Res = Builder->CreateTrunc(Res, Ty, "extract.t");
753f54e72962991005a3c0cc7dce0c550a14af90792Chris Lattner        PredVal = Res;
754f54e72962991005a3c0cc7dce0c550a14af90792Chris Lattner        EltPHI->addIncoming(Res, Pred);
75503fceff6f69a0261a767aab8e62de8aa9301b86cJim Grosbach
756f54e72962991005a3c0cc7dce0c550a14af90792Chris Lattner        // If the incoming value was a PHI, and if it was one of the PHIs we are
757f54e72962991005a3c0cc7dce0c550a14af90792Chris Lattner        // rewriting, we will ultimately delete the code we inserted.  This
758f54e72962991005a3c0cc7dce0c550a14af90792Chris Lattner        // means we need to revisit that PHI to make sure we extract out the
759f54e72962991005a3c0cc7dce0c550a14af90792Chris Lattner        // needed piece.
760f54e72962991005a3c0cc7dce0c550a14af90792Chris Lattner        if (PHINode *OldInVal = dyn_cast<PHINode>(PN->getIncomingValue(i)))
761f54e72962991005a3c0cc7dce0c550a14af90792Chris Lattner          if (PHIsInspected.count(OldInVal)) {
762f54e72962991005a3c0cc7dce0c550a14af90792Chris Lattner            unsigned RefPHIId = std::find(PHIsToSlice.begin(),PHIsToSlice.end(),
763f54e72962991005a3c0cc7dce0c550a14af90792Chris Lattner                                          OldInVal)-PHIsToSlice.begin();
76403fceff6f69a0261a767aab8e62de8aa9301b86cJim Grosbach            PHIUsers.push_back(PHIUsageRecord(RefPHIId, Offset,
765f54e72962991005a3c0cc7dce0c550a14af90792Chris Lattner                                              cast<Instruction>(Res)));
766f54e72962991005a3c0cc7dce0c550a14af90792Chris Lattner            ++UserE;
767f54e72962991005a3c0cc7dce0c550a14af90792Chris Lattner          }
768f54e72962991005a3c0cc7dce0c550a14af90792Chris Lattner      }
769f54e72962991005a3c0cc7dce0c550a14af90792Chris Lattner      PredValues.clear();
77003fceff6f69a0261a767aab8e62de8aa9301b86cJim Grosbach
771596aa123f46158639c836f1d53b89a9d7898c4b7Matt Arsenault      DEBUG(dbgs() << "  Made element PHI for offset " << Offset << ": "
772f54e72962991005a3c0cc7dce0c550a14af90792Chris Lattner                   << *EltPHI << '\n');
773f54e72962991005a3c0cc7dce0c550a14af90792Chris Lattner      ExtractedVals[LoweredPHIRecord(PN, Offset, Ty)] = EltPHI;
774f54e72962991005a3c0cc7dce0c550a14af90792Chris Lattner    }
77503fceff6f69a0261a767aab8e62de8aa9301b86cJim Grosbach
776f54e72962991005a3c0cc7dce0c550a14af90792Chris Lattner    // Replace the use of this piece with the PHI node.
777f54e72962991005a3c0cc7dce0c550a14af90792Chris Lattner    ReplaceInstUsesWith(*PHIUsers[UserI].Inst, EltPHI);
778f54e72962991005a3c0cc7dce0c550a14af90792Chris Lattner  }
77903fceff6f69a0261a767aab8e62de8aa9301b86cJim Grosbach
780f54e72962991005a3c0cc7dce0c550a14af90792Chris Lattner  // Replace all the remaining uses of the PHI nodes (self uses and the lshrs)
781f54e72962991005a3c0cc7dce0c550a14af90792Chris Lattner  // with undefs.
782f54e72962991005a3c0cc7dce0c550a14af90792Chris Lattner  Value *Undef = UndefValue::get(FirstPhi.getType());
783f54e72962991005a3c0cc7dce0c550a14af90792Chris Lattner  for (unsigned i = 1, e = PHIsToSlice.size(); i != e; ++i)
784f54e72962991005a3c0cc7dce0c550a14af90792Chris Lattner    ReplaceInstUsesWith(*PHIsToSlice[i], Undef);
785f54e72962991005a3c0cc7dce0c550a14af90792Chris Lattner  return ReplaceInstUsesWith(FirstPhi, Undef);
786f54e72962991005a3c0cc7dce0c550a14af90792Chris Lattner}
787f54e72962991005a3c0cc7dce0c550a14af90792Chris Lattner
788f54e72962991005a3c0cc7dce0c550a14af90792Chris Lattner// PHINode simplification
789f54e72962991005a3c0cc7dce0c550a14af90792Chris Lattner//
790f54e72962991005a3c0cc7dce0c550a14af90792Chris LattnerInstruction *InstCombiner::visitPHINode(PHINode &PN) {
79136b56886974eae4f9c5ebc96befd3e7bfe5de338Stephen Hines  if (Value *V = SimplifyInstruction(&PN, DL, TLI))
792f54e72962991005a3c0cc7dce0c550a14af90792Chris Lattner    return ReplaceInstUsesWith(PN, V);
793f54e72962991005a3c0cc7dce0c550a14af90792Chris Lattner
794f54e72962991005a3c0cc7dce0c550a14af90792Chris Lattner  // If all PHI operands are the same operation, pull them through the PHI,
795f54e72962991005a3c0cc7dce0c550a14af90792Chris Lattner  // reducing code size.
796f54e72962991005a3c0cc7dce0c550a14af90792Chris Lattner  if (isa<Instruction>(PN.getIncomingValue(0)) &&
797f54e72962991005a3c0cc7dce0c550a14af90792Chris Lattner      isa<Instruction>(PN.getIncomingValue(1)) &&
798f54e72962991005a3c0cc7dce0c550a14af90792Chris Lattner      cast<Instruction>(PN.getIncomingValue(0))->getOpcode() ==
799f54e72962991005a3c0cc7dce0c550a14af90792Chris Lattner      cast<Instruction>(PN.getIncomingValue(1))->getOpcode() &&
800f54e72962991005a3c0cc7dce0c550a14af90792Chris Lattner      // FIXME: The hasOneUse check will fail for PHIs that use the value more
801f54e72962991005a3c0cc7dce0c550a14af90792Chris Lattner      // than themselves more than once.
802f54e72962991005a3c0cc7dce0c550a14af90792Chris Lattner      PN.getIncomingValue(0)->hasOneUse())
803f54e72962991005a3c0cc7dce0c550a14af90792Chris Lattner    if (Instruction *Result = FoldPHIArgOpIntoPHI(PN))
804f54e72962991005a3c0cc7dce0c550a14af90792Chris Lattner      return Result;
805f54e72962991005a3c0cc7dce0c550a14af90792Chris Lattner
806f54e72962991005a3c0cc7dce0c550a14af90792Chris Lattner  // If this is a trivial cycle in the PHI node graph, remove it.  Basically, if
807f54e72962991005a3c0cc7dce0c550a14af90792Chris Lattner  // this PHI only has a single use (a PHI), and if that PHI only has one use (a
808f54e72962991005a3c0cc7dce0c550a14af90792Chris Lattner  // PHI)... break the cycle.
809f54e72962991005a3c0cc7dce0c550a14af90792Chris Lattner  if (PN.hasOneUse()) {
81036b56886974eae4f9c5ebc96befd3e7bfe5de338Stephen Hines    Instruction *PHIUser = cast<Instruction>(PN.user_back());
811f54e72962991005a3c0cc7dce0c550a14af90792Chris Lattner    if (PHINode *PU = dyn_cast<PHINode>(PHIUser)) {
812f54e72962991005a3c0cc7dce0c550a14af90792Chris Lattner      SmallPtrSet<PHINode*, 16> PotentiallyDeadPHIs;
813f54e72962991005a3c0cc7dce0c550a14af90792Chris Lattner      PotentiallyDeadPHIs.insert(&PN);
814f54e72962991005a3c0cc7dce0c550a14af90792Chris Lattner      if (DeadPHICycle(PU, PotentiallyDeadPHIs))
815f54e72962991005a3c0cc7dce0c550a14af90792Chris Lattner        return ReplaceInstUsesWith(PN, UndefValue::get(PN.getType()));
816f54e72962991005a3c0cc7dce0c550a14af90792Chris Lattner    }
81703fceff6f69a0261a767aab8e62de8aa9301b86cJim Grosbach
818f54e72962991005a3c0cc7dce0c550a14af90792Chris Lattner    // If this phi has a single use, and if that use just computes a value for
819f54e72962991005a3c0cc7dce0c550a14af90792Chris Lattner    // the next iteration of a loop, delete the phi.  This occurs with unused
820f54e72962991005a3c0cc7dce0c550a14af90792Chris Lattner    // induction variables, e.g. "for (int j = 0; ; ++j);".  Detecting this
821f54e72962991005a3c0cc7dce0c550a14af90792Chris Lattner    // common case here is good because the only other things that catch this
822f54e72962991005a3c0cc7dce0c550a14af90792Chris Lattner    // are induction variable analysis (sometimes) and ADCE, which is only run
823f54e72962991005a3c0cc7dce0c550a14af90792Chris Lattner    // late.
824f54e72962991005a3c0cc7dce0c550a14af90792Chris Lattner    if (PHIUser->hasOneUse() &&
825f54e72962991005a3c0cc7dce0c550a14af90792Chris Lattner        (isa<BinaryOperator>(PHIUser) || isa<GetElementPtrInst>(PHIUser)) &&
82636b56886974eae4f9c5ebc96befd3e7bfe5de338Stephen Hines        PHIUser->user_back() == &PN) {
827f54e72962991005a3c0cc7dce0c550a14af90792Chris Lattner      return ReplaceInstUsesWith(PN, UndefValue::get(PN.getType()));
828f54e72962991005a3c0cc7dce0c550a14af90792Chris Lattner    }
829f54e72962991005a3c0cc7dce0c550a14af90792Chris Lattner  }
830f54e72962991005a3c0cc7dce0c550a14af90792Chris Lattner
831f54e72962991005a3c0cc7dce0c550a14af90792Chris Lattner  // We sometimes end up with phi cycles that non-obviously end up being the
832f54e72962991005a3c0cc7dce0c550a14af90792Chris Lattner  // same value, for example:
833f54e72962991005a3c0cc7dce0c550a14af90792Chris Lattner  //   z = some value; x = phi (y, z); y = phi (x, z)
834f54e72962991005a3c0cc7dce0c550a14af90792Chris Lattner  // where the phi nodes don't necessarily need to be in the same block.  Do a
835f54e72962991005a3c0cc7dce0c550a14af90792Chris Lattner  // quick check to see if the PHI node only contains a single non-phi value, if
836f54e72962991005a3c0cc7dce0c550a14af90792Chris Lattner  // so, scan to see if the phi cycle is actually equal to that value.
837f54e72962991005a3c0cc7dce0c550a14af90792Chris Lattner  {
83886f72a8002ef6049d17ae8b9a536dee18b101fd0Frits van Bommel    unsigned InValNo = 0, NumIncomingVals = PN.getNumIncomingValues();
839f54e72962991005a3c0cc7dce0c550a14af90792Chris Lattner    // Scan for the first non-phi operand.
84086f72a8002ef6049d17ae8b9a536dee18b101fd0Frits van Bommel    while (InValNo != NumIncomingVals &&
841f54e72962991005a3c0cc7dce0c550a14af90792Chris Lattner           isa<PHINode>(PN.getIncomingValue(InValNo)))
842f54e72962991005a3c0cc7dce0c550a14af90792Chris Lattner      ++InValNo;
843f54e72962991005a3c0cc7dce0c550a14af90792Chris Lattner
84486f72a8002ef6049d17ae8b9a536dee18b101fd0Frits van Bommel    if (InValNo != NumIncomingVals) {
8454130278fbee97b9cd1ea4069e9c666bbe89d61f9Jay Foad      Value *NonPhiInVal = PN.getIncomingValue(InValNo);
84603fceff6f69a0261a767aab8e62de8aa9301b86cJim Grosbach
847f54e72962991005a3c0cc7dce0c550a14af90792Chris Lattner      // Scan the rest of the operands to see if there are any conflicts, if so
848f54e72962991005a3c0cc7dce0c550a14af90792Chris Lattner      // there is no need to recursively scan other phis.
84986f72a8002ef6049d17ae8b9a536dee18b101fd0Frits van Bommel      for (++InValNo; InValNo != NumIncomingVals; ++InValNo) {
850f54e72962991005a3c0cc7dce0c550a14af90792Chris Lattner        Value *OpVal = PN.getIncomingValue(InValNo);
851f54e72962991005a3c0cc7dce0c550a14af90792Chris Lattner        if (OpVal != NonPhiInVal && !isa<PHINode>(OpVal))
852f54e72962991005a3c0cc7dce0c550a14af90792Chris Lattner          break;
853f54e72962991005a3c0cc7dce0c550a14af90792Chris Lattner      }
85403fceff6f69a0261a767aab8e62de8aa9301b86cJim Grosbach
855f54e72962991005a3c0cc7dce0c550a14af90792Chris Lattner      // If we scanned over all operands, then we have one unique value plus
856f54e72962991005a3c0cc7dce0c550a14af90792Chris Lattner      // phi values.  Scan PHI nodes to see if they all merge in each other or
857f54e72962991005a3c0cc7dce0c550a14af90792Chris Lattner      // the value.
85886f72a8002ef6049d17ae8b9a536dee18b101fd0Frits van Bommel      if (InValNo == NumIncomingVals) {
859f54e72962991005a3c0cc7dce0c550a14af90792Chris Lattner        SmallPtrSet<PHINode*, 16> ValueEqualPHIs;
860f54e72962991005a3c0cc7dce0c550a14af90792Chris Lattner        if (PHIsEqualValue(&PN, NonPhiInVal, ValueEqualPHIs))
861f54e72962991005a3c0cc7dce0c550a14af90792Chris Lattner          return ReplaceInstUsesWith(PN, NonPhiInVal);
862f54e72962991005a3c0cc7dce0c550a14af90792Chris Lattner      }
863f54e72962991005a3c0cc7dce0c550a14af90792Chris Lattner    }
864f54e72962991005a3c0cc7dce0c550a14af90792Chris Lattner  }
865f54e72962991005a3c0cc7dce0c550a14af90792Chris Lattner
866f54e72962991005a3c0cc7dce0c550a14af90792Chris Lattner  // If there are multiple PHIs, sort their operands so that they all list
867f54e72962991005a3c0cc7dce0c550a14af90792Chris Lattner  // the blocks in the same order. This will help identical PHIs be eliminated
868f54e72962991005a3c0cc7dce0c550a14af90792Chris Lattner  // by other passes. Other passes shouldn't depend on this for correctness
869f54e72962991005a3c0cc7dce0c550a14af90792Chris Lattner  // however.
870f54e72962991005a3c0cc7dce0c550a14af90792Chris Lattner  PHINode *FirstPN = cast<PHINode>(PN.getParent()->begin());
871f54e72962991005a3c0cc7dce0c550a14af90792Chris Lattner  if (&PN != FirstPN)
872f54e72962991005a3c0cc7dce0c550a14af90792Chris Lattner    for (unsigned i = 0, e = FirstPN->getNumIncomingValues(); i != e; ++i) {
873f54e72962991005a3c0cc7dce0c550a14af90792Chris Lattner      BasicBlock *BBA = PN.getIncomingBlock(i);
874f54e72962991005a3c0cc7dce0c550a14af90792Chris Lattner      BasicBlock *BBB = FirstPN->getIncomingBlock(i);
875f54e72962991005a3c0cc7dce0c550a14af90792Chris Lattner      if (BBA != BBB) {
876f54e72962991005a3c0cc7dce0c550a14af90792Chris Lattner        Value *VA = PN.getIncomingValue(i);
877f54e72962991005a3c0cc7dce0c550a14af90792Chris Lattner        unsigned j = PN.getBasicBlockIndex(BBB);
878f54e72962991005a3c0cc7dce0c550a14af90792Chris Lattner        Value *VB = PN.getIncomingValue(j);
879f54e72962991005a3c0cc7dce0c550a14af90792Chris Lattner        PN.setIncomingBlock(i, BBB);
880f54e72962991005a3c0cc7dce0c550a14af90792Chris Lattner        PN.setIncomingValue(i, VB);
881f54e72962991005a3c0cc7dce0c550a14af90792Chris Lattner        PN.setIncomingBlock(j, BBA);
882f54e72962991005a3c0cc7dce0c550a14af90792Chris Lattner        PN.setIncomingValue(j, VA);
883f54e72962991005a3c0cc7dce0c550a14af90792Chris Lattner        // NOTE: Instcombine normally would want us to "return &PN" if we
884f54e72962991005a3c0cc7dce0c550a14af90792Chris Lattner        // modified any of the operands of an instruction.  However, since we
885f54e72962991005a3c0cc7dce0c550a14af90792Chris Lattner        // aren't adding or removing uses (just rearranging them) we don't do
886f54e72962991005a3c0cc7dce0c550a14af90792Chris Lattner        // this in this case.
887f54e72962991005a3c0cc7dce0c550a14af90792Chris Lattner      }
888f54e72962991005a3c0cc7dce0c550a14af90792Chris Lattner    }
889f54e72962991005a3c0cc7dce0c550a14af90792Chris Lattner
890f54e72962991005a3c0cc7dce0c550a14af90792Chris Lattner  // If this is an integer PHI and we know that it has an illegal type, see if
891f54e72962991005a3c0cc7dce0c550a14af90792Chris Lattner  // it is only used by trunc or trunc(lshr) operations.  If so, we split the
892f54e72962991005a3c0cc7dce0c550a14af90792Chris Lattner  // PHI into the various pieces being extracted.  This sort of thing is
893f54e72962991005a3c0cc7dce0c550a14af90792Chris Lattner  // introduced when SROA promotes an aggregate to a single large integer type.
89436b56886974eae4f9c5ebc96befd3e7bfe5de338Stephen Hines  if (PN.getType()->isIntegerTy() && DL &&
89536b56886974eae4f9c5ebc96befd3e7bfe5de338Stephen Hines      !DL->isLegalInteger(PN.getType()->getPrimitiveSizeInBits()))
896f54e72962991005a3c0cc7dce0c550a14af90792Chris Lattner    if (Instruction *Res = SliceUpIllegalIntegerPHI(PN))
897f54e72962991005a3c0cc7dce0c550a14af90792Chris Lattner      return Res;
89803fceff6f69a0261a767aab8e62de8aa9301b86cJim Grosbach
899dce4a407a24b04eebc6a376f8e62b41aaa7b071fStephen Hines  return nullptr;
900eade00209447c07953a609b30666ce5f6d9f9864Benjamin Kramer}
901