blob: 460f6eb6a825c1f74dae9c30e0bc2b5ce3d2ab28 [file] [log] [blame]
Chris Lattnerde1fede2010-01-05 05:31:55 +00001//===- 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
Chandler Carrutha9174582015-01-22 05:25:13 +000014#include "InstCombineInternal.h"
Chandler Carruthed0881b2012-12-03 16:50:05 +000015#include "llvm/ADT/STLExtras.h"
16#include "llvm/ADT/SmallPtrSet.h"
Duncan Sands4581ddc2010-11-14 13:30:18 +000017#include "llvm/Analysis/InstructionSimplify.h"
Chris Lattnerde1fede2010-01-05 05:31:55 +000018using namespace llvm;
19
Chandler Carruth964daaa2014-04-22 02:55:47 +000020#define DEBUG_TYPE "instcombine"
21
Sanjay Patel9b7e6772015-06-23 23:05:08 +000022/// If we have something like phi [add (a,b), add(a,c)] and if a/b/c and the
23/// adds all have a single use, turn this into a phi and a single binop.
Chris Lattnerde1fede2010-01-05 05:31:55 +000024Instruction *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);
Jim Grosbachbdbd7342013-04-05 21:20:12 +000030
Chris Lattner229907c2011-07-18 04:54:35 +000031 Type *LHSType = LHSVal->getType();
32 Type *RHSType = RHSVal->getType();
Jim Grosbachbdbd7342013-04-05 21:20:12 +000033
Chris Lattnera8fed472011-02-17 23:01:49 +000034 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();
Jim Grosbachbdbd7342013-04-05 21:20:12 +000042
Chris Lattnerde1fede2010-01-05 05:31:55 +000043 // 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
Chris Lattnera8fed472011-02-17 23:01:49 +000048 // types.
Chris Lattnerde1fede2010-01-05 05:31:55 +000049 I->getOperand(0)->getType() != LHSType ||
50 I->getOperand(1)->getType() != RHSType)
Craig Topperf40110f2014-04-25 05:29:35 +000051 return nullptr;
Chris Lattnerde1fede2010-01-05 05:31:55 +000052
53 // If they are CmpInst instructions, check their predicates
Chris Lattnera8fed472011-02-17 23:01:49 +000054 if (CmpInst *CI = dyn_cast<CmpInst>(I))
55 if (CI->getPredicate() != cast<CmpInst>(FirstInst)->getPredicate())
Craig Topperf40110f2014-04-25 05:29:35 +000056 return nullptr;
Jim Grosbachbdbd7342013-04-05 21:20:12 +000057
Chris Lattnera8fed472011-02-17 23:01:49 +000058 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();
Jim Grosbachbdbd7342013-04-05 21:20:12 +000064
Chris Lattnerde1fede2010-01-05 05:31:55 +000065 // Keep track of which operand needs a phi node.
Craig Topperf40110f2014-04-25 05:29:35 +000066 if (I->getOperand(0) != LHSVal) LHSVal = nullptr;
67 if (I->getOperand(1) != RHSVal) RHSVal = nullptr;
Chris Lattnerde1fede2010-01-05 05:31:55 +000068 }
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)
Craig Topperf40110f2014-04-25 05:29:35 +000075 return nullptr;
Jim Grosbachbdbd7342013-04-05 21:20:12 +000076
Chris Lattnerde1fede2010-01-05 05:31:55 +000077 // Otherwise, this is safe to transform!
Jim Grosbachbdbd7342013-04-05 21:20:12 +000078
Chris Lattnerde1fede2010-01-05 05:31:55 +000079 Value *InLHS = FirstInst->getOperand(0);
80 Value *InRHS = FirstInst->getOperand(1);
Craig Topperf40110f2014-04-25 05:29:35 +000081 PHINode *NewLHS = nullptr, *NewRHS = nullptr;
82 if (!LHSVal) {
Jay Foad52131342011-03-30 11:28:46 +000083 NewLHS = PHINode::Create(LHSType, PN.getNumIncomingValues(),
Chris Lattnerde1fede2010-01-05 05:31:55 +000084 FirstInst->getOperand(0)->getName() + ".pn");
Chris Lattnerde1fede2010-01-05 05:31:55 +000085 NewLHS->addIncoming(InLHS, PN.getIncomingBlock(0));
86 InsertNewInstBefore(NewLHS, PN);
87 LHSVal = NewLHS;
88 }
Jim Grosbachbdbd7342013-04-05 21:20:12 +000089
Craig Topperf40110f2014-04-25 05:29:35 +000090 if (!RHSVal) {
Jay Foad52131342011-03-30 11:28:46 +000091 NewRHS = PHINode::Create(RHSType, PN.getNumIncomingValues(),
Chris Lattnerde1fede2010-01-05 05:31:55 +000092 FirstInst->getOperand(1)->getName() + ".pn");
Chris Lattnerde1fede2010-01-05 05:31:55 +000093 NewRHS->addIncoming(InRHS, PN.getIncomingBlock(0));
94 InsertNewInstBefore(NewRHS, PN);
95 RHSVal = NewRHS;
96 }
Jim Grosbachbdbd7342013-04-05 21:20:12 +000097
Chris Lattnerde1fede2010-01-05 05:31:55 +000098 // Add all operands to the new PHIs.
99 if (NewLHS || NewRHS) {
100 for (unsigned i = 1, e = PN.getNumIncomingValues(); i != e; ++i) {
101 Instruction *InInst = cast<Instruction>(PN.getIncomingValue(i));
102 if (NewLHS) {
103 Value *NewInLHS = InInst->getOperand(0);
104 NewLHS->addIncoming(NewInLHS, PN.getIncomingBlock(i));
105 }
106 if (NewRHS) {
107 Value *NewInRHS = InInst->getOperand(1);
108 NewRHS->addIncoming(NewInRHS, PN.getIncomingBlock(i));
109 }
110 }
111 }
Jim Grosbachbdbd7342013-04-05 21:20:12 +0000112
Eli Friedman35211c62011-05-27 00:19:40 +0000113 if (CmpInst *CIOp = dyn_cast<CmpInst>(FirstInst)) {
114 CmpInst *NewCI = CmpInst::Create(CIOp->getOpcode(), CIOp->getPredicate(),
115 LHSVal, RHSVal);
116 NewCI->setDebugLoc(FirstInst->getDebugLoc());
117 return NewCI;
118 }
119
Chris Lattnera8fed472011-02-17 23:01:49 +0000120 BinaryOperator *BinOp = cast<BinaryOperator>(FirstInst);
121 BinaryOperator *NewBinOp =
122 BinaryOperator::Create(BinOp->getOpcode(), LHSVal, RHSVal);
123 if (isNUW) NewBinOp->setHasNoUnsignedWrap();
124 if (isNSW) NewBinOp->setHasNoSignedWrap();
125 if (isExact) NewBinOp->setIsExact();
Eli Friedman35211c62011-05-27 00:19:40 +0000126 NewBinOp->setDebugLoc(FirstInst->getDebugLoc());
Chris Lattnera8fed472011-02-17 23:01:49 +0000127 return NewBinOp;
Chris Lattnerde1fede2010-01-05 05:31:55 +0000128}
129
130Instruction *InstCombiner::FoldPHIArgGEPIntoPHI(PHINode &PN) {
131 GetElementPtrInst *FirstInst =cast<GetElementPtrInst>(PN.getIncomingValue(0));
Jim Grosbachbdbd7342013-04-05 21:20:12 +0000132
133 SmallVector<Value*, 16> FixedOperands(FirstInst->op_begin(),
Chris Lattnerde1fede2010-01-05 05:31:55 +0000134 FirstInst->op_end());
135 // This is true if all GEP bases are allocas and if all indices into them are
136 // constants.
137 bool AllBasePointersAreAllocas = true;
138
139 // We don't want to replace this phi if the replacement would require
140 // more than one phi, which leads to higher register pressure. This is
141 // especially bad when the PHIs are in the header of a loop.
142 bool NeededPhi = false;
Jim Grosbachbdbd7342013-04-05 21:20:12 +0000143
Chris Lattnerabb8eb22011-02-17 22:21:26 +0000144 bool AllInBounds = true;
Jim Grosbachbdbd7342013-04-05 21:20:12 +0000145
Chris Lattnerde1fede2010-01-05 05:31:55 +0000146 // Scan to see if all operands are the same opcode, and all have one use.
147 for (unsigned i = 1; i != PN.getNumIncomingValues(); ++i) {
148 GetElementPtrInst *GEP= dyn_cast<GetElementPtrInst>(PN.getIncomingValue(i));
149 if (!GEP || !GEP->hasOneUse() || GEP->getType() != FirstInst->getType() ||
150 GEP->getNumOperands() != FirstInst->getNumOperands())
Craig Topperf40110f2014-04-25 05:29:35 +0000151 return nullptr;
Chris Lattnerde1fede2010-01-05 05:31:55 +0000152
Chris Lattnerabb8eb22011-02-17 22:21:26 +0000153 AllInBounds &= GEP->isInBounds();
Jim Grosbachbdbd7342013-04-05 21:20:12 +0000154
Chris Lattnerde1fede2010-01-05 05:31:55 +0000155 // Keep track of whether or not all GEPs are of alloca pointers.
156 if (AllBasePointersAreAllocas &&
157 (!isa<AllocaInst>(GEP->getOperand(0)) ||
158 !GEP->hasAllConstantIndices()))
159 AllBasePointersAreAllocas = false;
Jim Grosbachbdbd7342013-04-05 21:20:12 +0000160
Chris Lattnerde1fede2010-01-05 05:31:55 +0000161 // Compare the operand lists.
162 for (unsigned op = 0, e = FirstInst->getNumOperands(); op != e; ++op) {
163 if (FirstInst->getOperand(op) == GEP->getOperand(op))
164 continue;
Jim Grosbachbdbd7342013-04-05 21:20:12 +0000165
Chris Lattnerde1fede2010-01-05 05:31:55 +0000166 // Don't merge two GEPs when two operands differ (introducing phi nodes)
167 // if one of the PHIs has a constant for the index. The index may be
168 // substantially cheaper to compute for the constants, so making it a
169 // variable index could pessimize the path. This also handles the case
170 // for struct indices, which must always be constant.
171 if (isa<ConstantInt>(FirstInst->getOperand(op)) ||
172 isa<ConstantInt>(GEP->getOperand(op)))
Craig Topperf40110f2014-04-25 05:29:35 +0000173 return nullptr;
Jim Grosbachbdbd7342013-04-05 21:20:12 +0000174
Chris Lattnerde1fede2010-01-05 05:31:55 +0000175 if (FirstInst->getOperand(op)->getType() !=GEP->getOperand(op)->getType())
Craig Topperf40110f2014-04-25 05:29:35 +0000176 return nullptr;
Chris Lattnerde1fede2010-01-05 05:31:55 +0000177
178 // If we already needed a PHI for an earlier operand, and another operand
179 // also requires a PHI, we'd be introducing more PHIs than we're
180 // eliminating, which increases register pressure on entry to the PHI's
181 // block.
182 if (NeededPhi)
Craig Topperf40110f2014-04-25 05:29:35 +0000183 return nullptr;
Chris Lattnerde1fede2010-01-05 05:31:55 +0000184
Craig Topperf40110f2014-04-25 05:29:35 +0000185 FixedOperands[op] = nullptr; // Needs a PHI.
Chris Lattnerde1fede2010-01-05 05:31:55 +0000186 NeededPhi = true;
187 }
188 }
Jim Grosbachbdbd7342013-04-05 21:20:12 +0000189
Chris Lattnerde1fede2010-01-05 05:31:55 +0000190 // If all of the base pointers of the PHI'd GEPs are from allocas, don't
191 // bother doing this transformation. At best, this will just save a bit of
192 // offset calculation, but all the predecessors will have to materialize the
193 // stack address into a register anyway. We'd actually rather *clone* the
194 // load up into the predecessors so that we have a load of a gep of an alloca,
195 // which can usually all be folded into the load.
196 if (AllBasePointersAreAllocas)
Craig Topperf40110f2014-04-25 05:29:35 +0000197 return nullptr;
Jim Grosbachbdbd7342013-04-05 21:20:12 +0000198
Chris Lattnerde1fede2010-01-05 05:31:55 +0000199 // Otherwise, this is safe to transform. Insert PHI nodes for each operand
200 // that is variable.
201 SmallVector<PHINode*, 16> OperandPhis(FixedOperands.size());
Jim Grosbachbdbd7342013-04-05 21:20:12 +0000202
Chris Lattnerde1fede2010-01-05 05:31:55 +0000203 bool HasAnyPHIs = false;
204 for (unsigned i = 0, e = FixedOperands.size(); i != e; ++i) {
205 if (FixedOperands[i]) continue; // operand doesn't need a phi.
206 Value *FirstOp = FirstInst->getOperand(i);
Jay Foad52131342011-03-30 11:28:46 +0000207 PHINode *NewPN = PHINode::Create(FirstOp->getType(), e,
Chris Lattnerde1fede2010-01-05 05:31:55 +0000208 FirstOp->getName()+".pn");
209 InsertNewInstBefore(NewPN, PN);
Jim Grosbachbdbd7342013-04-05 21:20:12 +0000210
Chris Lattnerde1fede2010-01-05 05:31:55 +0000211 NewPN->addIncoming(FirstOp, PN.getIncomingBlock(0));
212 OperandPhis[i] = NewPN;
213 FixedOperands[i] = NewPN;
214 HasAnyPHIs = true;
215 }
216
Jim Grosbachbdbd7342013-04-05 21:20:12 +0000217
Chris Lattnerde1fede2010-01-05 05:31:55 +0000218 // Add all operands to the new PHIs.
219 if (HasAnyPHIs) {
220 for (unsigned i = 1, e = PN.getNumIncomingValues(); i != e; ++i) {
221 GetElementPtrInst *InGEP =cast<GetElementPtrInst>(PN.getIncomingValue(i));
222 BasicBlock *InBB = PN.getIncomingBlock(i);
Jim Grosbachbdbd7342013-04-05 21:20:12 +0000223
Chris Lattnerde1fede2010-01-05 05:31:55 +0000224 for (unsigned op = 0, e = OperandPhis.size(); op != e; ++op)
225 if (PHINode *OpPhi = OperandPhis[op])
226 OpPhi->addIncoming(InGEP->getOperand(op), InBB);
227 }
228 }
Jim Grosbachbdbd7342013-04-05 21:20:12 +0000229
Chris Lattnerde1fede2010-01-05 05:31:55 +0000230 Value *Base = FixedOperands[0];
Jim Grosbachbdbd7342013-04-05 21:20:12 +0000231 GetElementPtrInst *NewGEP =
David Blaikie741c8f82015-03-14 01:53:18 +0000232 GetElementPtrInst::Create(FirstInst->getSourceElementType(), Base,
233 makeArrayRef(FixedOperands).slice(1));
Chris Lattner75ae5a42011-02-17 22:32:54 +0000234 if (AllInBounds) NewGEP->setIsInBounds();
Eli Friedman35211c62011-05-27 00:19:40 +0000235 NewGEP->setDebugLoc(FirstInst->getDebugLoc());
Chris Lattnerabb8eb22011-02-17 22:21:26 +0000236 return NewGEP;
Chris Lattnerde1fede2010-01-05 05:31:55 +0000237}
238
239
Sanjay Patel9b7e6772015-06-23 23:05:08 +0000240/// Return true if we know that it is safe to sink the load out of the block
241/// that defines it. This means that it must be obvious the value of the load is
242/// not changed from the point of the load to the end of the block it is in.
Chris Lattnerde1fede2010-01-05 05:31:55 +0000243///
Chris Lattner0ab5e2c2011-04-15 05:18:47 +0000244/// Finally, it is safe, but not profitable, to sink a load targeting a
Chris Lattnerde1fede2010-01-05 05:31:55 +0000245/// non-address-taken alloca. Doing so will cause us to not promote the alloca
246/// to a register.
247static bool isSafeAndProfitableToSinkLoad(LoadInst *L) {
248 BasicBlock::iterator BBI = L, E = L->getParent()->end();
Jim Grosbachbdbd7342013-04-05 21:20:12 +0000249
Chris Lattnerde1fede2010-01-05 05:31:55 +0000250 for (++BBI; BBI != E; ++BBI)
251 if (BBI->mayWriteToMemory())
252 return false;
Jim Grosbachbdbd7342013-04-05 21:20:12 +0000253
Chris Lattnerde1fede2010-01-05 05:31:55 +0000254 // Check for non-address taken alloca. If not address-taken already, it isn't
255 // profitable to do this xform.
256 if (AllocaInst *AI = dyn_cast<AllocaInst>(L->getOperand(0))) {
257 bool isAddressTaken = false;
Chandler Carruthcdf47882014-03-09 03:16:01 +0000258 for (User *U : AI->users()) {
Gabor Greif96fedcb2010-07-12 14:15:58 +0000259 if (isa<LoadInst>(U)) continue;
260 if (StoreInst *SI = dyn_cast<StoreInst>(U)) {
Chris Lattnerde1fede2010-01-05 05:31:55 +0000261 // If storing TO the alloca, then the address isn't taken.
262 if (SI->getOperand(1) == AI) continue;
263 }
264 isAddressTaken = true;
265 break;
266 }
Jim Grosbachbdbd7342013-04-05 21:20:12 +0000267
Chris Lattnerde1fede2010-01-05 05:31:55 +0000268 if (!isAddressTaken && AI->isStaticAlloca())
269 return false;
270 }
Jim Grosbachbdbd7342013-04-05 21:20:12 +0000271
Chris Lattnerde1fede2010-01-05 05:31:55 +0000272 // If this load is a load from a GEP with a constant offset from an alloca,
273 // then we don't want to sink it. In its present form, it will be
274 // load [constant stack offset]. Sinking it will cause us to have to
275 // materialize the stack addresses in each predecessor in a register only to
276 // do a shared load from register in the successor.
277 if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(L->getOperand(0)))
278 if (AllocaInst *AI = dyn_cast<AllocaInst>(GEP->getOperand(0)))
279 if (AI->isStaticAlloca() && GEP->hasAllConstantIndices())
280 return false;
Jim Grosbachbdbd7342013-04-05 21:20:12 +0000281
Chris Lattnerde1fede2010-01-05 05:31:55 +0000282 return true;
283}
284
285Instruction *InstCombiner::FoldPHIArgLoadIntoPHI(PHINode &PN) {
286 LoadInst *FirstLI = cast<LoadInst>(PN.getIncomingValue(0));
Eli Friedman8bc586e2011-08-15 22:09:40 +0000287
288 // FIXME: This is overconservative; this transform is allowed in some cases
289 // for atomic operations.
290 if (FirstLI->isAtomic())
Craig Topperf40110f2014-04-25 05:29:35 +0000291 return nullptr;
Eli Friedman8bc586e2011-08-15 22:09:40 +0000292
Chris Lattnerde1fede2010-01-05 05:31:55 +0000293 // When processing loads, we need to propagate two bits of information to the
294 // sunk load: whether it is volatile, and what its alignment is. We currently
295 // don't sink loads when some have their alignment specified and some don't.
296 // visitLoadInst will propagate an alignment onto the load when TD is around,
297 // and if TD isn't around, we can't handle the mixed case.
298 bool isVolatile = FirstLI->isVolatile();
299 unsigned LoadAlignment = FirstLI->getAlignment();
Chris Lattnerf6befff2010-03-05 18:53:28 +0000300 unsigned LoadAddrSpace = FirstLI->getPointerAddressSpace();
Jim Grosbachbdbd7342013-04-05 21:20:12 +0000301
Chris Lattnerde1fede2010-01-05 05:31:55 +0000302 // We can't sink the load if the loaded value could be modified between the
303 // load and the PHI.
304 if (FirstLI->getParent() != PN.getIncomingBlock(0) ||
305 !isSafeAndProfitableToSinkLoad(FirstLI))
Craig Topperf40110f2014-04-25 05:29:35 +0000306 return nullptr;
Jim Grosbachbdbd7342013-04-05 21:20:12 +0000307
Chris Lattnerde1fede2010-01-05 05:31:55 +0000308 // If the PHI is of volatile loads and the load block has multiple
309 // successors, sinking it would remove a load of the volatile value from
310 // the path through the other successor.
Jim Grosbachbdbd7342013-04-05 21:20:12 +0000311 if (isVolatile &&
Chris Lattnerde1fede2010-01-05 05:31:55 +0000312 FirstLI->getParent()->getTerminator()->getNumSuccessors() != 1)
Craig Topperf40110f2014-04-25 05:29:35 +0000313 return nullptr;
Jim Grosbachbdbd7342013-04-05 21:20:12 +0000314
Chris Lattnerde1fede2010-01-05 05:31:55 +0000315 // Check to see if all arguments are the same operation.
316 for (unsigned i = 1, e = PN.getNumIncomingValues(); i != e; ++i) {
317 LoadInst *LI = dyn_cast<LoadInst>(PN.getIncomingValue(i));
318 if (!LI || !LI->hasOneUse())
Craig Topperf40110f2014-04-25 05:29:35 +0000319 return nullptr;
Jim Grosbachbdbd7342013-04-05 21:20:12 +0000320
321 // We can't sink the load if the loaded value could be modified between
Chris Lattnerde1fede2010-01-05 05:31:55 +0000322 // the load and the PHI.
323 if (LI->isVolatile() != isVolatile ||
324 LI->getParent() != PN.getIncomingBlock(i) ||
Chris Lattnerf6befff2010-03-05 18:53:28 +0000325 LI->getPointerAddressSpace() != LoadAddrSpace ||
Chris Lattnerde1fede2010-01-05 05:31:55 +0000326 !isSafeAndProfitableToSinkLoad(LI))
Craig Topperf40110f2014-04-25 05:29:35 +0000327 return nullptr;
Jim Grosbachbdbd7342013-04-05 21:20:12 +0000328
Chris Lattnerde1fede2010-01-05 05:31:55 +0000329 // If some of the loads have an alignment specified but not all of them,
330 // we can't do the transformation.
331 if ((LoadAlignment != 0) != (LI->getAlignment() != 0))
Craig Topperf40110f2014-04-25 05:29:35 +0000332 return nullptr;
Jim Grosbachbdbd7342013-04-05 21:20:12 +0000333
Chris Lattnerde1fede2010-01-05 05:31:55 +0000334 LoadAlignment = std::min(LoadAlignment, LI->getAlignment());
Jim Grosbachbdbd7342013-04-05 21:20:12 +0000335
Chris Lattnerde1fede2010-01-05 05:31:55 +0000336 // If the PHI is of volatile loads and the load block has multiple
337 // successors, sinking it would remove a load of the volatile value from
338 // the path through the other successor.
339 if (isVolatile &&
340 LI->getParent()->getTerminator()->getNumSuccessors() != 1)
Craig Topperf40110f2014-04-25 05:29:35 +0000341 return nullptr;
Chris Lattnerde1fede2010-01-05 05:31:55 +0000342 }
Jim Grosbachbdbd7342013-04-05 21:20:12 +0000343
Chris Lattnerde1fede2010-01-05 05:31:55 +0000344 // Okay, they are all the same operation. Create a new PHI node of the
345 // correct type, and PHI together all of the LHS's of the instructions.
346 PHINode *NewPN = PHINode::Create(FirstLI->getOperand(0)->getType(),
Jay Foad52131342011-03-30 11:28:46 +0000347 PN.getNumIncomingValues(),
Chris Lattnerde1fede2010-01-05 05:31:55 +0000348 PN.getName()+".in");
Jim Grosbachbdbd7342013-04-05 21:20:12 +0000349
Chris Lattnerde1fede2010-01-05 05:31:55 +0000350 Value *InVal = FirstLI->getOperand(0);
351 NewPN->addIncoming(InVal, PN.getIncomingBlock(0));
Jim Grosbachbdbd7342013-04-05 21:20:12 +0000352
Chris Lattnerde1fede2010-01-05 05:31:55 +0000353 // Add all operands to the new PHI.
354 for (unsigned i = 1, e = PN.getNumIncomingValues(); i != e; ++i) {
355 Value *NewInVal = cast<LoadInst>(PN.getIncomingValue(i))->getOperand(0);
356 if (NewInVal != InVal)
Craig Topperf40110f2014-04-25 05:29:35 +0000357 InVal = nullptr;
Chris Lattnerde1fede2010-01-05 05:31:55 +0000358 NewPN->addIncoming(NewInVal, PN.getIncomingBlock(i));
359 }
Jim Grosbachbdbd7342013-04-05 21:20:12 +0000360
Chris Lattnerde1fede2010-01-05 05:31:55 +0000361 Value *PhiVal;
362 if (InVal) {
363 // The new PHI unions all of the same values together. This is really
364 // common, so we handle it intelligently here for compile-time speed.
365 PhiVal = InVal;
366 delete NewPN;
367 } else {
368 InsertNewInstBefore(NewPN, PN);
369 PhiVal = NewPN;
370 }
Jim Grosbachbdbd7342013-04-05 21:20:12 +0000371
Chris Lattnerde1fede2010-01-05 05:31:55 +0000372 // If this was a volatile load that we are merging, make sure to loop through
373 // and mark all the input loads as non-volatile. If we don't do this, we will
374 // insert a new volatile load and the old ones will not be deletable.
375 if (isVolatile)
Pete Cooper833f34d2015-05-12 20:05:31 +0000376 for (Value *IncValue : PN.incoming_values())
377 cast<LoadInst>(IncValue)->setVolatile(false);
Jim Grosbachbdbd7342013-04-05 21:20:12 +0000378
Eli Friedman35211c62011-05-27 00:19:40 +0000379 LoadInst *NewLI = new LoadInst(PhiVal, "", isVolatile, LoadAlignment);
380 NewLI->setDebugLoc(FirstLI->getDebugLoc());
381 return NewLI;
Chris Lattnerde1fede2010-01-05 05:31:55 +0000382}
383
384
385
Sanjay Patel9b7e6772015-06-23 23:05:08 +0000386/// If all operands to a PHI node are the same "unary" operator and they all are
387/// only used by the PHI, PHI together their inputs, and do the operation once,
388/// to the result of the PHI.
Chris Lattnerde1fede2010-01-05 05:31:55 +0000389Instruction *InstCombiner::FoldPHIArgOpIntoPHI(PHINode &PN) {
390 Instruction *FirstInst = cast<Instruction>(PN.getIncomingValue(0));
391
392 if (isa<GetElementPtrInst>(FirstInst))
393 return FoldPHIArgGEPIntoPHI(PN);
394 if (isa<LoadInst>(FirstInst))
395 return FoldPHIArgLoadIntoPHI(PN);
Jim Grosbachbdbd7342013-04-05 21:20:12 +0000396
Chris Lattnerde1fede2010-01-05 05:31:55 +0000397 // Scan the instruction, looking for input operations that can be folded away.
398 // If all input operands to the phi are the same instruction (e.g. a cast from
399 // the same type or "+42") we can pull the operation through the PHI, reducing
400 // code size and simplifying code.
Craig Topperf40110f2014-04-25 05:29:35 +0000401 Constant *ConstantOp = nullptr;
402 Type *CastSrcTy = nullptr;
Chris Lattnera8fed472011-02-17 23:01:49 +0000403 bool isNUW = false, isNSW = false, isExact = false;
Jim Grosbachbdbd7342013-04-05 21:20:12 +0000404
Chris Lattnerde1fede2010-01-05 05:31:55 +0000405 if (isa<CastInst>(FirstInst)) {
406 CastSrcTy = FirstInst->getOperand(0)->getType();
407
408 // Be careful about transforming integer PHIs. We don't want to pessimize
409 // the code by turning an i32 into an i1293.
Duncan Sands19d0b472010-02-16 11:11:14 +0000410 if (PN.getType()->isIntegerTy() && CastSrcTy->isIntegerTy()) {
Chris Lattnerde1fede2010-01-05 05:31:55 +0000411 if (!ShouldChangeType(PN.getType(), CastSrcTy))
Craig Topperf40110f2014-04-25 05:29:35 +0000412 return nullptr;
Chris Lattnerde1fede2010-01-05 05:31:55 +0000413 }
414 } else if (isa<BinaryOperator>(FirstInst) || isa<CmpInst>(FirstInst)) {
Jim Grosbachbdbd7342013-04-05 21:20:12 +0000415 // Can fold binop, compare or shift here if the RHS is a constant,
Chris Lattnerde1fede2010-01-05 05:31:55 +0000416 // otherwise call FoldPHIArgBinOpIntoPHI.
417 ConstantOp = dyn_cast<Constant>(FirstInst->getOperand(1));
Craig Topperf40110f2014-04-25 05:29:35 +0000418 if (!ConstantOp)
Chris Lattnerde1fede2010-01-05 05:31:55 +0000419 return FoldPHIArgBinOpIntoPHI(PN);
Jim Grosbachbdbd7342013-04-05 21:20:12 +0000420
Chris Lattnera8fed472011-02-17 23:01:49 +0000421 if (OverflowingBinaryOperator *BO =
422 dyn_cast<OverflowingBinaryOperator>(FirstInst)) {
423 isNUW = BO->hasNoUnsignedWrap();
424 isNSW = BO->hasNoSignedWrap();
425 } else if (PossiblyExactOperator *PEO =
426 dyn_cast<PossiblyExactOperator>(FirstInst))
427 isExact = PEO->isExact();
Chris Lattnerde1fede2010-01-05 05:31:55 +0000428 } else {
Craig Topperf40110f2014-04-25 05:29:35 +0000429 return nullptr; // Cannot fold this operation.
Chris Lattnerde1fede2010-01-05 05:31:55 +0000430 }
431
432 // Check to see if all arguments are the same operation.
433 for (unsigned i = 1, e = PN.getNumIncomingValues(); i != e; ++i) {
434 Instruction *I = dyn_cast<Instruction>(PN.getIncomingValue(i));
Craig Topperf40110f2014-04-25 05:29:35 +0000435 if (!I || !I->hasOneUse() || !I->isSameOperationAs(FirstInst))
436 return nullptr;
Chris Lattnerde1fede2010-01-05 05:31:55 +0000437 if (CastSrcTy) {
438 if (I->getOperand(0)->getType() != CastSrcTy)
Craig Topperf40110f2014-04-25 05:29:35 +0000439 return nullptr; // Cast operation must match.
Chris Lattnerde1fede2010-01-05 05:31:55 +0000440 } else if (I->getOperand(1) != ConstantOp) {
Craig Topperf40110f2014-04-25 05:29:35 +0000441 return nullptr;
Chris Lattnerde1fede2010-01-05 05:31:55 +0000442 }
Jim Grosbachbdbd7342013-04-05 21:20:12 +0000443
Chris Lattnera8fed472011-02-17 23:01:49 +0000444 if (isNUW)
445 isNUW = cast<OverflowingBinaryOperator>(I)->hasNoUnsignedWrap();
446 if (isNSW)
447 isNSW = cast<OverflowingBinaryOperator>(I)->hasNoSignedWrap();
448 if (isExact)
449 isExact = cast<PossiblyExactOperator>(I)->isExact();
Chris Lattnerde1fede2010-01-05 05:31:55 +0000450 }
451
452 // Okay, they are all the same operation. Create a new PHI node of the
453 // correct type, and PHI together all of the LHS's of the instructions.
454 PHINode *NewPN = PHINode::Create(FirstInst->getOperand(0)->getType(),
Jay Foad52131342011-03-30 11:28:46 +0000455 PN.getNumIncomingValues(),
Chris Lattnerde1fede2010-01-05 05:31:55 +0000456 PN.getName()+".in");
Chris Lattnerde1fede2010-01-05 05:31:55 +0000457
458 Value *InVal = FirstInst->getOperand(0);
459 NewPN->addIncoming(InVal, PN.getIncomingBlock(0));
460
461 // Add all operands to the new PHI.
462 for (unsigned i = 1, e = PN.getNumIncomingValues(); i != e; ++i) {
463 Value *NewInVal = cast<Instruction>(PN.getIncomingValue(i))->getOperand(0);
464 if (NewInVal != InVal)
Craig Topperf40110f2014-04-25 05:29:35 +0000465 InVal = nullptr;
Chris Lattnerde1fede2010-01-05 05:31:55 +0000466 NewPN->addIncoming(NewInVal, PN.getIncomingBlock(i));
467 }
468
469 Value *PhiVal;
470 if (InVal) {
471 // The new PHI unions all of the same values together. This is really
472 // common, so we handle it intelligently here for compile-time speed.
473 PhiVal = InVal;
474 delete NewPN;
475 } else {
476 InsertNewInstBefore(NewPN, PN);
477 PhiVal = NewPN;
478 }
479
480 // Insert and return the new operation.
Eli Friedman35211c62011-05-27 00:19:40 +0000481 if (CastInst *FirstCI = dyn_cast<CastInst>(FirstInst)) {
482 CastInst *NewCI = CastInst::Create(FirstCI->getOpcode(), PhiVal,
483 PN.getType());
484 NewCI->setDebugLoc(FirstInst->getDebugLoc());
485 return NewCI;
486 }
Jim Grosbachbdbd7342013-04-05 21:20:12 +0000487
Chris Lattnera8fed472011-02-17 23:01:49 +0000488 if (BinaryOperator *BinOp = dyn_cast<BinaryOperator>(FirstInst)) {
489 BinOp = BinaryOperator::Create(BinOp->getOpcode(), PhiVal, ConstantOp);
490 if (isNUW) BinOp->setHasNoUnsignedWrap();
491 if (isNSW) BinOp->setHasNoSignedWrap();
492 if (isExact) BinOp->setIsExact();
Eli Friedman35211c62011-05-27 00:19:40 +0000493 BinOp->setDebugLoc(FirstInst->getDebugLoc());
Chris Lattnera8fed472011-02-17 23:01:49 +0000494 return BinOp;
495 }
Jim Grosbachbdbd7342013-04-05 21:20:12 +0000496
Chris Lattnerde1fede2010-01-05 05:31:55 +0000497 CmpInst *CIOp = cast<CmpInst>(FirstInst);
Eli Friedman35211c62011-05-27 00:19:40 +0000498 CmpInst *NewCI = CmpInst::Create(CIOp->getOpcode(), CIOp->getPredicate(),
499 PhiVal, ConstantOp);
500 NewCI->setDebugLoc(FirstInst->getDebugLoc());
501 return NewCI;
Chris Lattnerde1fede2010-01-05 05:31:55 +0000502}
503
Sanjay Patel9b7e6772015-06-23 23:05:08 +0000504/// Return true if this PHI node is only used by a PHI node cycle that is dead.
Chris Lattnerde1fede2010-01-05 05:31:55 +0000505static bool DeadPHICycle(PHINode *PN,
Craig Topper71b7b682014-08-21 05:55:13 +0000506 SmallPtrSetImpl<PHINode*> &PotentiallyDeadPHIs) {
Chris Lattnerde1fede2010-01-05 05:31:55 +0000507 if (PN->use_empty()) return true;
508 if (!PN->hasOneUse()) return false;
509
510 // Remember this node, and if we find the cycle, return.
David Blaikie70573dc2014-11-19 07:49:26 +0000511 if (!PotentiallyDeadPHIs.insert(PN).second)
Chris Lattnerde1fede2010-01-05 05:31:55 +0000512 return true;
Jim Grosbachbdbd7342013-04-05 21:20:12 +0000513
Chris Lattnerde1fede2010-01-05 05:31:55 +0000514 // Don't scan crazily complex things.
515 if (PotentiallyDeadPHIs.size() == 16)
516 return false;
517
Chandler Carruthcdf47882014-03-09 03:16:01 +0000518 if (PHINode *PU = dyn_cast<PHINode>(PN->user_back()))
Chris Lattnerde1fede2010-01-05 05:31:55 +0000519 return DeadPHICycle(PU, PotentiallyDeadPHIs);
520
521 return false;
522}
523
Sanjay Patel9b7e6772015-06-23 23:05:08 +0000524/// Return true if this phi node is always equal to NonPhiInVal.
525/// This happens with mutually cyclic phi nodes like:
Chris Lattnerde1fede2010-01-05 05:31:55 +0000526/// z = some value; x = phi (y, z); y = phi (x, z)
Jim Grosbachbdbd7342013-04-05 21:20:12 +0000527static bool PHIsEqualValue(PHINode *PN, Value *NonPhiInVal,
Craig Topper71b7b682014-08-21 05:55:13 +0000528 SmallPtrSetImpl<PHINode*> &ValueEqualPHIs) {
Chris Lattnerde1fede2010-01-05 05:31:55 +0000529 // See if we already saw this PHI node.
David Blaikie70573dc2014-11-19 07:49:26 +0000530 if (!ValueEqualPHIs.insert(PN).second)
Chris Lattnerde1fede2010-01-05 05:31:55 +0000531 return true;
Jim Grosbachbdbd7342013-04-05 21:20:12 +0000532
Chris Lattnerde1fede2010-01-05 05:31:55 +0000533 // Don't scan crazily complex things.
534 if (ValueEqualPHIs.size() == 16)
535 return false;
Jim Grosbachbdbd7342013-04-05 21:20:12 +0000536
Chris Lattnerde1fede2010-01-05 05:31:55 +0000537 // Scan the operands to see if they are either phi nodes or are equal to
538 // the value.
Pete Cooper833f34d2015-05-12 20:05:31 +0000539 for (Value *Op : PN->incoming_values()) {
Chris Lattnerde1fede2010-01-05 05:31:55 +0000540 if (PHINode *OpPN = dyn_cast<PHINode>(Op)) {
541 if (!PHIsEqualValue(OpPN, NonPhiInVal, ValueEqualPHIs))
542 return false;
543 } else if (Op != NonPhiInVal)
544 return false;
545 }
Jim Grosbachbdbd7342013-04-05 21:20:12 +0000546
Chris Lattnerde1fede2010-01-05 05:31:55 +0000547 return true;
548}
549
550
551namespace {
552struct PHIUsageRecord {
553 unsigned PHIId; // The ID # of the PHI (something determinstic to sort on)
554 unsigned Shift; // The amount shifted.
555 Instruction *Inst; // The trunc instruction.
Jim Grosbachbdbd7342013-04-05 21:20:12 +0000556
Chris Lattnerde1fede2010-01-05 05:31:55 +0000557 PHIUsageRecord(unsigned pn, unsigned Sh, Instruction *User)
558 : PHIId(pn), Shift(Sh), Inst(User) {}
Jim Grosbachbdbd7342013-04-05 21:20:12 +0000559
Chris Lattnerde1fede2010-01-05 05:31:55 +0000560 bool operator<(const PHIUsageRecord &RHS) const {
561 if (PHIId < RHS.PHIId) return true;
562 if (PHIId > RHS.PHIId) return false;
563 if (Shift < RHS.Shift) return true;
564 if (Shift > RHS.Shift) return false;
565 return Inst->getType()->getPrimitiveSizeInBits() <
566 RHS.Inst->getType()->getPrimitiveSizeInBits();
567 }
568};
Jim Grosbachbdbd7342013-04-05 21:20:12 +0000569
Chris Lattnerde1fede2010-01-05 05:31:55 +0000570struct LoweredPHIRecord {
571 PHINode *PN; // The PHI that was lowered.
572 unsigned Shift; // The amount shifted.
573 unsigned Width; // The width extracted.
Jim Grosbachbdbd7342013-04-05 21:20:12 +0000574
Chris Lattner229907c2011-07-18 04:54:35 +0000575 LoweredPHIRecord(PHINode *pn, unsigned Sh, Type *Ty)
Chris Lattnerde1fede2010-01-05 05:31:55 +0000576 : PN(pn), Shift(Sh), Width(Ty->getPrimitiveSizeInBits()) {}
Jim Grosbachbdbd7342013-04-05 21:20:12 +0000577
Chris Lattnerde1fede2010-01-05 05:31:55 +0000578 // Ctor form used by DenseMap.
579 LoweredPHIRecord(PHINode *pn, unsigned Sh)
580 : PN(pn), Shift(Sh), Width(0) {}
581};
Alexander Kornienkof00654e2015-06-23 09:49:53 +0000582}
Chris Lattnerde1fede2010-01-05 05:31:55 +0000583
584namespace llvm {
585 template<>
586 struct DenseMapInfo<LoweredPHIRecord> {
587 static inline LoweredPHIRecord getEmptyKey() {
Craig Topperf40110f2014-04-25 05:29:35 +0000588 return LoweredPHIRecord(nullptr, 0);
Chris Lattnerde1fede2010-01-05 05:31:55 +0000589 }
590 static inline LoweredPHIRecord getTombstoneKey() {
Craig Topperf40110f2014-04-25 05:29:35 +0000591 return LoweredPHIRecord(nullptr, 1);
Chris Lattnerde1fede2010-01-05 05:31:55 +0000592 }
593 static unsigned getHashValue(const LoweredPHIRecord &Val) {
594 return DenseMapInfo<PHINode*>::getHashValue(Val.PN) ^ (Val.Shift>>3) ^
595 (Val.Width>>3);
596 }
597 static bool isEqual(const LoweredPHIRecord &LHS,
598 const LoweredPHIRecord &RHS) {
599 return LHS.PN == RHS.PN && LHS.Shift == RHS.Shift &&
600 LHS.Width == RHS.Width;
601 }
602 };
Alexander Kornienkof00654e2015-06-23 09:49:53 +0000603}
Chris Lattnerde1fede2010-01-05 05:31:55 +0000604
605
Sanjay Patel9b7e6772015-06-23 23:05:08 +0000606/// This is an integer PHI and we know that it has an illegal type: see if it is
607/// only used by trunc or trunc(lshr) operations. If so, we split the PHI into
608/// the various pieces being extracted. This sort of thing is introduced when
609/// SROA promotes an aggregate to large integer values.
Chris Lattnerde1fede2010-01-05 05:31:55 +0000610///
611/// TODO: The user of the trunc may be an bitcast to float/double/vector or an
612/// inttoptr. We should produce new PHIs in the right type.
613///
614Instruction *InstCombiner::SliceUpIllegalIntegerPHI(PHINode &FirstPhi) {
615 // PHIUsers - Keep track of all of the truncated values extracted from a set
616 // of PHIs, along with their offset. These are the things we want to rewrite.
617 SmallVector<PHIUsageRecord, 16> PHIUsers;
Jim Grosbachbdbd7342013-04-05 21:20:12 +0000618
Chris Lattnerde1fede2010-01-05 05:31:55 +0000619 // PHIs are often mutually cyclic, so we keep track of a whole set of PHI
620 // nodes which are extracted from. PHIsToSlice is a set we use to avoid
621 // revisiting PHIs, PHIsInspected is a ordered list of PHIs that we need to
622 // check the uses of (to ensure they are all extracts).
623 SmallVector<PHINode*, 8> PHIsToSlice;
624 SmallPtrSet<PHINode*, 8> PHIsInspected;
Jim Grosbachbdbd7342013-04-05 21:20:12 +0000625
Chris Lattnerde1fede2010-01-05 05:31:55 +0000626 PHIsToSlice.push_back(&FirstPhi);
627 PHIsInspected.insert(&FirstPhi);
Jim Grosbachbdbd7342013-04-05 21:20:12 +0000628
Chris Lattnerde1fede2010-01-05 05:31:55 +0000629 for (unsigned PHIId = 0; PHIId != PHIsToSlice.size(); ++PHIId) {
630 PHINode *PN = PHIsToSlice[PHIId];
Jim Grosbachbdbd7342013-04-05 21:20:12 +0000631
Chris Lattnerde1fede2010-01-05 05:31:55 +0000632 // Scan the input list of the PHI. If any input is an invoke, and if the
633 // input is defined in the predecessor, then we won't be split the critical
634 // edge which is required to insert a truncate. Because of this, we have to
635 // bail out.
636 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) {
637 InvokeInst *II = dyn_cast<InvokeInst>(PN->getIncomingValue(i));
Craig Topperf40110f2014-04-25 05:29:35 +0000638 if (!II) continue;
Chris Lattnerde1fede2010-01-05 05:31:55 +0000639 if (II->getParent() != PN->getIncomingBlock(i))
640 continue;
Jim Grosbachbdbd7342013-04-05 21:20:12 +0000641
Chris Lattnerde1fede2010-01-05 05:31:55 +0000642 // If we have a phi, and if it's directly in the predecessor, then we have
643 // a critical edge where we need to put the truncate. Since we can't
644 // split the edge in instcombine, we have to bail out.
Craig Topperf40110f2014-04-25 05:29:35 +0000645 return nullptr;
Chris Lattnerde1fede2010-01-05 05:31:55 +0000646 }
Jim Grosbachbdbd7342013-04-05 21:20:12 +0000647
Chandler Carruthcdf47882014-03-09 03:16:01 +0000648 for (User *U : PN->users()) {
649 Instruction *UserI = cast<Instruction>(U);
Jim Grosbachbdbd7342013-04-05 21:20:12 +0000650
Chris Lattnerde1fede2010-01-05 05:31:55 +0000651 // If the user is a PHI, inspect its uses recursively.
Chandler Carruthcdf47882014-03-09 03:16:01 +0000652 if (PHINode *UserPN = dyn_cast<PHINode>(UserI)) {
David Blaikie70573dc2014-11-19 07:49:26 +0000653 if (PHIsInspected.insert(UserPN).second)
Chris Lattnerde1fede2010-01-05 05:31:55 +0000654 PHIsToSlice.push_back(UserPN);
655 continue;
656 }
Jim Grosbachbdbd7342013-04-05 21:20:12 +0000657
Chris Lattnerde1fede2010-01-05 05:31:55 +0000658 // Truncates are always ok.
Chandler Carruthcdf47882014-03-09 03:16:01 +0000659 if (isa<TruncInst>(UserI)) {
660 PHIUsers.push_back(PHIUsageRecord(PHIId, 0, UserI));
Chris Lattnerde1fede2010-01-05 05:31:55 +0000661 continue;
662 }
Jim Grosbachbdbd7342013-04-05 21:20:12 +0000663
Chris Lattnerde1fede2010-01-05 05:31:55 +0000664 // Otherwise it must be a lshr which can only be used by one trunc.
Chandler Carruthcdf47882014-03-09 03:16:01 +0000665 if (UserI->getOpcode() != Instruction::LShr ||
666 !UserI->hasOneUse() || !isa<TruncInst>(UserI->user_back()) ||
667 !isa<ConstantInt>(UserI->getOperand(1)))
Craig Topperf40110f2014-04-25 05:29:35 +0000668 return nullptr;
Jim Grosbachbdbd7342013-04-05 21:20:12 +0000669
Chandler Carruthcdf47882014-03-09 03:16:01 +0000670 unsigned Shift = cast<ConstantInt>(UserI->getOperand(1))->getZExtValue();
671 PHIUsers.push_back(PHIUsageRecord(PHIId, Shift, UserI->user_back()));
Chris Lattnerde1fede2010-01-05 05:31:55 +0000672 }
673 }
Jim Grosbachbdbd7342013-04-05 21:20:12 +0000674
Chris Lattnerde1fede2010-01-05 05:31:55 +0000675 // If we have no users, they must be all self uses, just nuke the PHI.
676 if (PHIUsers.empty())
677 return ReplaceInstUsesWith(FirstPhi, UndefValue::get(FirstPhi.getType()));
Jim Grosbachbdbd7342013-04-05 21:20:12 +0000678
Chris Lattnerde1fede2010-01-05 05:31:55 +0000679 // If this phi node is transformable, create new PHIs for all the pieces
680 // extracted out of it. First, sort the users by their offset and size.
681 array_pod_sort(PHIUsers.begin(), PHIUsers.end());
Jim Grosbachbdbd7342013-04-05 21:20:12 +0000682
Matt Arsenaulte6db7602013-09-05 19:48:28 +0000683 DEBUG(dbgs() << "SLICING UP PHI: " << FirstPhi << '\n';
684 for (unsigned i = 1, e = PHIsToSlice.size(); i != e; ++i)
685 dbgs() << "AND USER PHI #" << i << ": " << *PHIsToSlice[i] << '\n';
686 );
Jim Grosbachbdbd7342013-04-05 21:20:12 +0000687
Chris Lattnerde1fede2010-01-05 05:31:55 +0000688 // PredValues - This is a temporary used when rewriting PHI nodes. It is
689 // hoisted out here to avoid construction/destruction thrashing.
690 DenseMap<BasicBlock*, Value*> PredValues;
Jim Grosbachbdbd7342013-04-05 21:20:12 +0000691
Chris Lattnerde1fede2010-01-05 05:31:55 +0000692 // ExtractedVals - Each new PHI we introduce is saved here so we don't
693 // introduce redundant PHIs.
694 DenseMap<LoweredPHIRecord, PHINode*> ExtractedVals;
Jim Grosbachbdbd7342013-04-05 21:20:12 +0000695
Chris Lattnerde1fede2010-01-05 05:31:55 +0000696 for (unsigned UserI = 0, UserE = PHIUsers.size(); UserI != UserE; ++UserI) {
697 unsigned PHIId = PHIUsers[UserI].PHIId;
698 PHINode *PN = PHIsToSlice[PHIId];
699 unsigned Offset = PHIUsers[UserI].Shift;
Chris Lattner229907c2011-07-18 04:54:35 +0000700 Type *Ty = PHIUsers[UserI].Inst->getType();
Jim Grosbachbdbd7342013-04-05 21:20:12 +0000701
Chris Lattnerde1fede2010-01-05 05:31:55 +0000702 PHINode *EltPHI;
Jim Grosbachbdbd7342013-04-05 21:20:12 +0000703
Chris Lattnerde1fede2010-01-05 05:31:55 +0000704 // If we've already lowered a user like this, reuse the previously lowered
705 // value.
Craig Topperf40110f2014-04-25 05:29:35 +0000706 if ((EltPHI = ExtractedVals[LoweredPHIRecord(PN, Offset, Ty)]) == nullptr) {
Jim Grosbachbdbd7342013-04-05 21:20:12 +0000707
Chris Lattnerde1fede2010-01-05 05:31:55 +0000708 // Otherwise, Create the new PHI node for this user.
Jay Foad52131342011-03-30 11:28:46 +0000709 EltPHI = PHINode::Create(Ty, PN->getNumIncomingValues(),
710 PN->getName()+".off"+Twine(Offset), PN);
Chris Lattnerde1fede2010-01-05 05:31:55 +0000711 assert(EltPHI->getType() != PN->getType() &&
712 "Truncate didn't shrink phi?");
Jim Grosbachbdbd7342013-04-05 21:20:12 +0000713
Chris Lattnerde1fede2010-01-05 05:31:55 +0000714 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) {
715 BasicBlock *Pred = PN->getIncomingBlock(i);
716 Value *&PredVal = PredValues[Pred];
Jim Grosbachbdbd7342013-04-05 21:20:12 +0000717
Chris Lattnerde1fede2010-01-05 05:31:55 +0000718 // If we already have a value for this predecessor, reuse it.
719 if (PredVal) {
720 EltPHI->addIncoming(PredVal, Pred);
721 continue;
722 }
723
724 // Handle the PHI self-reuse case.
725 Value *InVal = PN->getIncomingValue(i);
726 if (InVal == PN) {
727 PredVal = EltPHI;
728 EltPHI->addIncoming(PredVal, Pred);
729 continue;
730 }
Jim Grosbachbdbd7342013-04-05 21:20:12 +0000731
Chris Lattnerde1fede2010-01-05 05:31:55 +0000732 if (PHINode *InPHI = dyn_cast<PHINode>(PN)) {
733 // If the incoming value was a PHI, and if it was one of the PHIs we
734 // already rewrote it, just use the lowered value.
735 if (Value *Res = ExtractedVals[LoweredPHIRecord(InPHI, Offset, Ty)]) {
736 PredVal = Res;
737 EltPHI->addIncoming(PredVal, Pred);
738 continue;
739 }
740 }
Jim Grosbachbdbd7342013-04-05 21:20:12 +0000741
Chris Lattnerde1fede2010-01-05 05:31:55 +0000742 // Otherwise, do an extract in the predecessor.
743 Builder->SetInsertPoint(Pred, Pred->getTerminator());
744 Value *Res = InVal;
745 if (Offset)
746 Res = Builder->CreateLShr(Res, ConstantInt::get(InVal->getType(),
747 Offset), "extract");
748 Res = Builder->CreateTrunc(Res, Ty, "extract.t");
749 PredVal = Res;
750 EltPHI->addIncoming(Res, Pred);
Jim Grosbachbdbd7342013-04-05 21:20:12 +0000751
Chris Lattnerde1fede2010-01-05 05:31:55 +0000752 // If the incoming value was a PHI, and if it was one of the PHIs we are
753 // rewriting, we will ultimately delete the code we inserted. This
754 // means we need to revisit that PHI to make sure we extract out the
755 // needed piece.
756 if (PHINode *OldInVal = dyn_cast<PHINode>(PN->getIncomingValue(i)))
757 if (PHIsInspected.count(OldInVal)) {
758 unsigned RefPHIId = std::find(PHIsToSlice.begin(),PHIsToSlice.end(),
759 OldInVal)-PHIsToSlice.begin();
Jim Grosbachbdbd7342013-04-05 21:20:12 +0000760 PHIUsers.push_back(PHIUsageRecord(RefPHIId, Offset,
Chris Lattnerde1fede2010-01-05 05:31:55 +0000761 cast<Instruction>(Res)));
762 ++UserE;
763 }
764 }
765 PredValues.clear();
Jim Grosbachbdbd7342013-04-05 21:20:12 +0000766
Matt Arsenaulte6db7602013-09-05 19:48:28 +0000767 DEBUG(dbgs() << " Made element PHI for offset " << Offset << ": "
Chris Lattnerde1fede2010-01-05 05:31:55 +0000768 << *EltPHI << '\n');
769 ExtractedVals[LoweredPHIRecord(PN, Offset, Ty)] = EltPHI;
770 }
Jim Grosbachbdbd7342013-04-05 21:20:12 +0000771
Chris Lattnerde1fede2010-01-05 05:31:55 +0000772 // Replace the use of this piece with the PHI node.
773 ReplaceInstUsesWith(*PHIUsers[UserI].Inst, EltPHI);
774 }
Jim Grosbachbdbd7342013-04-05 21:20:12 +0000775
Chris Lattnerde1fede2010-01-05 05:31:55 +0000776 // Replace all the remaining uses of the PHI nodes (self uses and the lshrs)
777 // with undefs.
778 Value *Undef = UndefValue::get(FirstPhi.getType());
779 for (unsigned i = 1, e = PHIsToSlice.size(); i != e; ++i)
780 ReplaceInstUsesWith(*PHIsToSlice[i], Undef);
781 return ReplaceInstUsesWith(FirstPhi, Undef);
782}
783
784// PHINode simplification
785//
786Instruction *InstCombiner::visitPHINode(PHINode &PN) {
Chandler Carruth66b31302015-01-04 12:03:27 +0000787 if (Value *V = SimplifyInstruction(&PN, DL, TLI, DT, AC))
Chris Lattnerde1fede2010-01-05 05:31:55 +0000788 return ReplaceInstUsesWith(PN, V);
789
790 // If all PHI operands are the same operation, pull them through the PHI,
791 // reducing code size.
792 if (isa<Instruction>(PN.getIncomingValue(0)) &&
793 isa<Instruction>(PN.getIncomingValue(1)) &&
794 cast<Instruction>(PN.getIncomingValue(0))->getOpcode() ==
795 cast<Instruction>(PN.getIncomingValue(1))->getOpcode() &&
796 // FIXME: The hasOneUse check will fail for PHIs that use the value more
797 // than themselves more than once.
798 PN.getIncomingValue(0)->hasOneUse())
799 if (Instruction *Result = FoldPHIArgOpIntoPHI(PN))
800 return Result;
801
802 // If this is a trivial cycle in the PHI node graph, remove it. Basically, if
803 // this PHI only has a single use (a PHI), and if that PHI only has one use (a
804 // PHI)... break the cycle.
805 if (PN.hasOneUse()) {
Chandler Carruthcdf47882014-03-09 03:16:01 +0000806 Instruction *PHIUser = cast<Instruction>(PN.user_back());
Chris Lattnerde1fede2010-01-05 05:31:55 +0000807 if (PHINode *PU = dyn_cast<PHINode>(PHIUser)) {
808 SmallPtrSet<PHINode*, 16> PotentiallyDeadPHIs;
809 PotentiallyDeadPHIs.insert(&PN);
810 if (DeadPHICycle(PU, PotentiallyDeadPHIs))
811 return ReplaceInstUsesWith(PN, UndefValue::get(PN.getType()));
812 }
Jim Grosbachbdbd7342013-04-05 21:20:12 +0000813
Chris Lattnerde1fede2010-01-05 05:31:55 +0000814 // If this phi has a single use, and if that use just computes a value for
815 // the next iteration of a loop, delete the phi. This occurs with unused
816 // induction variables, e.g. "for (int j = 0; ; ++j);". Detecting this
817 // common case here is good because the only other things that catch this
818 // are induction variable analysis (sometimes) and ADCE, which is only run
819 // late.
820 if (PHIUser->hasOneUse() &&
821 (isa<BinaryOperator>(PHIUser) || isa<GetElementPtrInst>(PHIUser)) &&
Chandler Carruthcdf47882014-03-09 03:16:01 +0000822 PHIUser->user_back() == &PN) {
Chris Lattnerde1fede2010-01-05 05:31:55 +0000823 return ReplaceInstUsesWith(PN, UndefValue::get(PN.getType()));
824 }
825 }
826
827 // We sometimes end up with phi cycles that non-obviously end up being the
828 // same value, for example:
829 // z = some value; x = phi (y, z); y = phi (x, z)
830 // where the phi nodes don't necessarily need to be in the same block. Do a
831 // quick check to see if the PHI node only contains a single non-phi value, if
832 // so, scan to see if the phi cycle is actually equal to that value.
833 {
Frits van Bommeld6d4f982011-04-16 14:32:34 +0000834 unsigned InValNo = 0, NumIncomingVals = PN.getNumIncomingValues();
Chris Lattnerde1fede2010-01-05 05:31:55 +0000835 // Scan for the first non-phi operand.
Frits van Bommeld6d4f982011-04-16 14:32:34 +0000836 while (InValNo != NumIncomingVals &&
Chris Lattnerde1fede2010-01-05 05:31:55 +0000837 isa<PHINode>(PN.getIncomingValue(InValNo)))
838 ++InValNo;
839
Frits van Bommeld6d4f982011-04-16 14:32:34 +0000840 if (InValNo != NumIncomingVals) {
Jay Foad7d03e9b2011-04-16 14:17:37 +0000841 Value *NonPhiInVal = PN.getIncomingValue(InValNo);
Jim Grosbachbdbd7342013-04-05 21:20:12 +0000842
Chris Lattnerde1fede2010-01-05 05:31:55 +0000843 // Scan the rest of the operands to see if there are any conflicts, if so
844 // there is no need to recursively scan other phis.
Frits van Bommeld6d4f982011-04-16 14:32:34 +0000845 for (++InValNo; InValNo != NumIncomingVals; ++InValNo) {
Chris Lattnerde1fede2010-01-05 05:31:55 +0000846 Value *OpVal = PN.getIncomingValue(InValNo);
847 if (OpVal != NonPhiInVal && !isa<PHINode>(OpVal))
848 break;
849 }
Jim Grosbachbdbd7342013-04-05 21:20:12 +0000850
Chris Lattnerde1fede2010-01-05 05:31:55 +0000851 // If we scanned over all operands, then we have one unique value plus
852 // phi values. Scan PHI nodes to see if they all merge in each other or
853 // the value.
Frits van Bommeld6d4f982011-04-16 14:32:34 +0000854 if (InValNo == NumIncomingVals) {
Chris Lattnerde1fede2010-01-05 05:31:55 +0000855 SmallPtrSet<PHINode*, 16> ValueEqualPHIs;
856 if (PHIsEqualValue(&PN, NonPhiInVal, ValueEqualPHIs))
857 return ReplaceInstUsesWith(PN, NonPhiInVal);
858 }
859 }
860 }
861
862 // If there are multiple PHIs, sort their operands so that they all list
863 // the blocks in the same order. This will help identical PHIs be eliminated
864 // by other passes. Other passes shouldn't depend on this for correctness
865 // however.
866 PHINode *FirstPN = cast<PHINode>(PN.getParent()->begin());
867 if (&PN != FirstPN)
868 for (unsigned i = 0, e = FirstPN->getNumIncomingValues(); i != e; ++i) {
869 BasicBlock *BBA = PN.getIncomingBlock(i);
870 BasicBlock *BBB = FirstPN->getIncomingBlock(i);
871 if (BBA != BBB) {
872 Value *VA = PN.getIncomingValue(i);
873 unsigned j = PN.getBasicBlockIndex(BBB);
874 Value *VB = PN.getIncomingValue(j);
875 PN.setIncomingBlock(i, BBB);
876 PN.setIncomingValue(i, VB);
877 PN.setIncomingBlock(j, BBA);
878 PN.setIncomingValue(j, VA);
879 // NOTE: Instcombine normally would want us to "return &PN" if we
880 // modified any of the operands of an instruction. However, since we
881 // aren't adding or removing uses (just rearranging them) we don't do
882 // this in this case.
883 }
884 }
885
886 // If this is an integer PHI and we know that it has an illegal type, see if
887 // it is only used by trunc or trunc(lshr) operations. If so, we split the
888 // PHI into the various pieces being extracted. This sort of thing is
889 // introduced when SROA promotes an aggregate to a single large integer type.
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000890 if (PN.getType()->isIntegerTy() &&
891 !DL.isLegalInteger(PN.getType()->getPrimitiveSizeInBits()))
Chris Lattnerde1fede2010-01-05 05:31:55 +0000892 if (Instruction *Res = SliceUpIllegalIntegerPHI(PN))
893 return Res;
Jim Grosbachbdbd7342013-04-05 21:20:12 +0000894
Craig Topperf40110f2014-04-25 05:29:35 +0000895 return nullptr;
Benjamin Kramerf7cc6982010-01-05 13:32:48 +0000896}