blob: 1d3b837f124d547f2806d83bc034875f0f78a7eb [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"
Akira Hatanakaf6afd112015-09-23 18:40:57 +000018#include "llvm/Transforms/Utils/Local.h"
Chris Lattnerde1fede2010-01-05 05:31:55 +000019using namespace llvm;
20
Chandler Carruth964daaa2014-04-22 02:55:47 +000021#define DEBUG_TYPE "instcombine"
22
Sanjay Patel9b7e6772015-06-23 23:05:08 +000023/// If we have something like phi [add (a,b), add(a,c)] and if a/b/c and the
24/// adds all have a single use, turn this into a phi and a single binop.
Chris Lattnerde1fede2010-01-05 05:31:55 +000025Instruction *InstCombiner::FoldPHIArgBinOpIntoPHI(PHINode &PN) {
26 Instruction *FirstInst = cast<Instruction>(PN.getIncomingValue(0));
27 assert(isa<BinaryOperator>(FirstInst) || isa<CmpInst>(FirstInst));
28 unsigned Opc = FirstInst->getOpcode();
29 Value *LHSVal = FirstInst->getOperand(0);
30 Value *RHSVal = FirstInst->getOperand(1);
Jim Grosbachbdbd7342013-04-05 21:20:12 +000031
Chris Lattner229907c2011-07-18 04:54:35 +000032 Type *LHSType = LHSVal->getType();
33 Type *RHSType = RHSVal->getType();
Jim Grosbachbdbd7342013-04-05 21:20:12 +000034
Chris Lattnera8fed472011-02-17 23:01:49 +000035 bool isNUW = false, isNSW = false, isExact = false;
36 if (OverflowingBinaryOperator *BO =
37 dyn_cast<OverflowingBinaryOperator>(FirstInst)) {
38 isNUW = BO->hasNoUnsignedWrap();
39 isNSW = BO->hasNoSignedWrap();
40 } else if (PossiblyExactOperator *PEO =
41 dyn_cast<PossiblyExactOperator>(FirstInst))
42 isExact = PEO->isExact();
Jim Grosbachbdbd7342013-04-05 21:20:12 +000043
Chris Lattnerde1fede2010-01-05 05:31:55 +000044 // Scan to see if all operands are the same opcode, and all have one use.
45 for (unsigned i = 1; i != PN.getNumIncomingValues(); ++i) {
46 Instruction *I = dyn_cast<Instruction>(PN.getIncomingValue(i));
47 if (!I || I->getOpcode() != Opc || !I->hasOneUse() ||
48 // Verify type of the LHS matches so we don't fold cmp's of different
Chris Lattnera8fed472011-02-17 23:01:49 +000049 // types.
Chris Lattnerde1fede2010-01-05 05:31:55 +000050 I->getOperand(0)->getType() != LHSType ||
51 I->getOperand(1)->getType() != RHSType)
Craig Topperf40110f2014-04-25 05:29:35 +000052 return nullptr;
Chris Lattnerde1fede2010-01-05 05:31:55 +000053
54 // If they are CmpInst instructions, check their predicates
Chris Lattnera8fed472011-02-17 23:01:49 +000055 if (CmpInst *CI = dyn_cast<CmpInst>(I))
56 if (CI->getPredicate() != cast<CmpInst>(FirstInst)->getPredicate())
Craig Topperf40110f2014-04-25 05:29:35 +000057 return nullptr;
Jim Grosbachbdbd7342013-04-05 21:20:12 +000058
Chris Lattnera8fed472011-02-17 23:01:49 +000059 if (isNUW)
60 isNUW = cast<OverflowingBinaryOperator>(I)->hasNoUnsignedWrap();
61 if (isNSW)
62 isNSW = cast<OverflowingBinaryOperator>(I)->hasNoSignedWrap();
63 if (isExact)
64 isExact = cast<PossiblyExactOperator>(I)->isExact();
Jim Grosbachbdbd7342013-04-05 21:20:12 +000065
Chris Lattnerde1fede2010-01-05 05:31:55 +000066 // Keep track of which operand needs a phi node.
Craig Topperf40110f2014-04-25 05:29:35 +000067 if (I->getOperand(0) != LHSVal) LHSVal = nullptr;
68 if (I->getOperand(1) != RHSVal) RHSVal = nullptr;
Chris Lattnerde1fede2010-01-05 05:31:55 +000069 }
70
71 // If both LHS and RHS would need a PHI, don't do this transformation,
72 // because it would increase the number of PHIs entering the block,
73 // which leads to higher register pressure. This is especially
74 // bad when the PHIs are in the header of a loop.
75 if (!LHSVal && !RHSVal)
Craig Topperf40110f2014-04-25 05:29:35 +000076 return nullptr;
Jim Grosbachbdbd7342013-04-05 21:20:12 +000077
Chris Lattnerde1fede2010-01-05 05:31:55 +000078 // Otherwise, this is safe to transform!
Jim Grosbachbdbd7342013-04-05 21:20:12 +000079
Chris Lattnerde1fede2010-01-05 05:31:55 +000080 Value *InLHS = FirstInst->getOperand(0);
81 Value *InRHS = FirstInst->getOperand(1);
Craig Topperf40110f2014-04-25 05:29:35 +000082 PHINode *NewLHS = nullptr, *NewRHS = nullptr;
83 if (!LHSVal) {
Jay Foad52131342011-03-30 11:28:46 +000084 NewLHS = PHINode::Create(LHSType, PN.getNumIncomingValues(),
Chris Lattnerde1fede2010-01-05 05:31:55 +000085 FirstInst->getOperand(0)->getName() + ".pn");
Chris Lattnerde1fede2010-01-05 05:31:55 +000086 NewLHS->addIncoming(InLHS, PN.getIncomingBlock(0));
87 InsertNewInstBefore(NewLHS, PN);
88 LHSVal = NewLHS;
89 }
Jim Grosbachbdbd7342013-04-05 21:20:12 +000090
Craig Topperf40110f2014-04-25 05:29:35 +000091 if (!RHSVal) {
Jay Foad52131342011-03-30 11:28:46 +000092 NewRHS = PHINode::Create(RHSType, PN.getNumIncomingValues(),
Chris Lattnerde1fede2010-01-05 05:31:55 +000093 FirstInst->getOperand(1)->getName() + ".pn");
Chris Lattnerde1fede2010-01-05 05:31:55 +000094 NewRHS->addIncoming(InRHS, PN.getIncomingBlock(0));
95 InsertNewInstBefore(NewRHS, PN);
96 RHSVal = NewRHS;
97 }
Jim Grosbachbdbd7342013-04-05 21:20:12 +000098
Chris Lattnerde1fede2010-01-05 05:31:55 +000099 // Add all operands to the new PHIs.
100 if (NewLHS || NewRHS) {
101 for (unsigned i = 1, e = PN.getNumIncomingValues(); i != e; ++i) {
102 Instruction *InInst = cast<Instruction>(PN.getIncomingValue(i));
103 if (NewLHS) {
104 Value *NewInLHS = InInst->getOperand(0);
105 NewLHS->addIncoming(NewInLHS, PN.getIncomingBlock(i));
106 }
107 if (NewRHS) {
108 Value *NewInRHS = InInst->getOperand(1);
109 NewRHS->addIncoming(NewInRHS, PN.getIncomingBlock(i));
110 }
111 }
112 }
Jim Grosbachbdbd7342013-04-05 21:20:12 +0000113
Eli Friedman35211c62011-05-27 00:19:40 +0000114 if (CmpInst *CIOp = dyn_cast<CmpInst>(FirstInst)) {
115 CmpInst *NewCI = CmpInst::Create(CIOp->getOpcode(), CIOp->getPredicate(),
116 LHSVal, RHSVal);
117 NewCI->setDebugLoc(FirstInst->getDebugLoc());
118 return NewCI;
119 }
120
Chris Lattnera8fed472011-02-17 23:01:49 +0000121 BinaryOperator *BinOp = cast<BinaryOperator>(FirstInst);
122 BinaryOperator *NewBinOp =
123 BinaryOperator::Create(BinOp->getOpcode(), LHSVal, RHSVal);
124 if (isNUW) NewBinOp->setHasNoUnsignedWrap();
125 if (isNSW) NewBinOp->setHasNoSignedWrap();
126 if (isExact) NewBinOp->setIsExact();
Eli Friedman35211c62011-05-27 00:19:40 +0000127 NewBinOp->setDebugLoc(FirstInst->getDebugLoc());
Chris Lattnera8fed472011-02-17 23:01:49 +0000128 return NewBinOp;
Chris Lattnerde1fede2010-01-05 05:31:55 +0000129}
130
131Instruction *InstCombiner::FoldPHIArgGEPIntoPHI(PHINode &PN) {
132 GetElementPtrInst *FirstInst =cast<GetElementPtrInst>(PN.getIncomingValue(0));
Jim Grosbachbdbd7342013-04-05 21:20:12 +0000133
134 SmallVector<Value*, 16> FixedOperands(FirstInst->op_begin(),
Chris Lattnerde1fede2010-01-05 05:31:55 +0000135 FirstInst->op_end());
136 // This is true if all GEP bases are allocas and if all indices into them are
137 // constants.
138 bool AllBasePointersAreAllocas = true;
139
140 // We don't want to replace this phi if the replacement would require
141 // more than one phi, which leads to higher register pressure. This is
142 // especially bad when the PHIs are in the header of a loop.
143 bool NeededPhi = false;
Jim Grosbachbdbd7342013-04-05 21:20:12 +0000144
Chris Lattnerabb8eb22011-02-17 22:21:26 +0000145 bool AllInBounds = true;
Jim Grosbachbdbd7342013-04-05 21:20:12 +0000146
Chris Lattnerde1fede2010-01-05 05:31:55 +0000147 // Scan to see if all operands are the same opcode, and all have one use.
148 for (unsigned i = 1; i != PN.getNumIncomingValues(); ++i) {
149 GetElementPtrInst *GEP= dyn_cast<GetElementPtrInst>(PN.getIncomingValue(i));
150 if (!GEP || !GEP->hasOneUse() || GEP->getType() != FirstInst->getType() ||
151 GEP->getNumOperands() != FirstInst->getNumOperands())
Craig Topperf40110f2014-04-25 05:29:35 +0000152 return nullptr;
Chris Lattnerde1fede2010-01-05 05:31:55 +0000153
Chris Lattnerabb8eb22011-02-17 22:21:26 +0000154 AllInBounds &= GEP->isInBounds();
Jim Grosbachbdbd7342013-04-05 21:20:12 +0000155
Chris Lattnerde1fede2010-01-05 05:31:55 +0000156 // Keep track of whether or not all GEPs are of alloca pointers.
157 if (AllBasePointersAreAllocas &&
158 (!isa<AllocaInst>(GEP->getOperand(0)) ||
159 !GEP->hasAllConstantIndices()))
160 AllBasePointersAreAllocas = false;
Jim Grosbachbdbd7342013-04-05 21:20:12 +0000161
Chris Lattnerde1fede2010-01-05 05:31:55 +0000162 // Compare the operand lists.
163 for (unsigned op = 0, e = FirstInst->getNumOperands(); op != e; ++op) {
164 if (FirstInst->getOperand(op) == GEP->getOperand(op))
165 continue;
Jim Grosbachbdbd7342013-04-05 21:20:12 +0000166
Chris Lattnerde1fede2010-01-05 05:31:55 +0000167 // Don't merge two GEPs when two operands differ (introducing phi nodes)
168 // if one of the PHIs has a constant for the index. The index may be
169 // substantially cheaper to compute for the constants, so making it a
170 // variable index could pessimize the path. This also handles the case
171 // for struct indices, which must always be constant.
172 if (isa<ConstantInt>(FirstInst->getOperand(op)) ||
173 isa<ConstantInt>(GEP->getOperand(op)))
Craig Topperf40110f2014-04-25 05:29:35 +0000174 return nullptr;
Jim Grosbachbdbd7342013-04-05 21:20:12 +0000175
Chris Lattnerde1fede2010-01-05 05:31:55 +0000176 if (FirstInst->getOperand(op)->getType() !=GEP->getOperand(op)->getType())
Craig Topperf40110f2014-04-25 05:29:35 +0000177 return nullptr;
Chris Lattnerde1fede2010-01-05 05:31:55 +0000178
179 // If we already needed a PHI for an earlier operand, and another operand
180 // also requires a PHI, we'd be introducing more PHIs than we're
181 // eliminating, which increases register pressure on entry to the PHI's
182 // block.
183 if (NeededPhi)
Craig Topperf40110f2014-04-25 05:29:35 +0000184 return nullptr;
Chris Lattnerde1fede2010-01-05 05:31:55 +0000185
Craig Topperf40110f2014-04-25 05:29:35 +0000186 FixedOperands[op] = nullptr; // Needs a PHI.
Chris Lattnerde1fede2010-01-05 05:31:55 +0000187 NeededPhi = true;
188 }
189 }
Jim Grosbachbdbd7342013-04-05 21:20:12 +0000190
Chris Lattnerde1fede2010-01-05 05:31:55 +0000191 // If all of the base pointers of the PHI'd GEPs are from allocas, don't
192 // bother doing this transformation. At best, this will just save a bit of
193 // offset calculation, but all the predecessors will have to materialize the
194 // stack address into a register anyway. We'd actually rather *clone* the
195 // load up into the predecessors so that we have a load of a gep of an alloca,
196 // which can usually all be folded into the load.
197 if (AllBasePointersAreAllocas)
Craig Topperf40110f2014-04-25 05:29:35 +0000198 return nullptr;
Jim Grosbachbdbd7342013-04-05 21:20:12 +0000199
Chris Lattnerde1fede2010-01-05 05:31:55 +0000200 // Otherwise, this is safe to transform. Insert PHI nodes for each operand
201 // that is variable.
202 SmallVector<PHINode*, 16> OperandPhis(FixedOperands.size());
Jim Grosbachbdbd7342013-04-05 21:20:12 +0000203
Chris Lattnerde1fede2010-01-05 05:31:55 +0000204 bool HasAnyPHIs = false;
205 for (unsigned i = 0, e = FixedOperands.size(); i != e; ++i) {
206 if (FixedOperands[i]) continue; // operand doesn't need a phi.
207 Value *FirstOp = FirstInst->getOperand(i);
Jay Foad52131342011-03-30 11:28:46 +0000208 PHINode *NewPN = PHINode::Create(FirstOp->getType(), e,
Chris Lattnerde1fede2010-01-05 05:31:55 +0000209 FirstOp->getName()+".pn");
210 InsertNewInstBefore(NewPN, PN);
Jim Grosbachbdbd7342013-04-05 21:20:12 +0000211
Chris Lattnerde1fede2010-01-05 05:31:55 +0000212 NewPN->addIncoming(FirstOp, PN.getIncomingBlock(0));
213 OperandPhis[i] = NewPN;
214 FixedOperands[i] = NewPN;
215 HasAnyPHIs = true;
216 }
217
Jim Grosbachbdbd7342013-04-05 21:20:12 +0000218
Chris Lattnerde1fede2010-01-05 05:31:55 +0000219 // Add all operands to the new PHIs.
220 if (HasAnyPHIs) {
221 for (unsigned i = 1, e = PN.getNumIncomingValues(); i != e; ++i) {
222 GetElementPtrInst *InGEP =cast<GetElementPtrInst>(PN.getIncomingValue(i));
223 BasicBlock *InBB = PN.getIncomingBlock(i);
Jim Grosbachbdbd7342013-04-05 21:20:12 +0000224
Chris Lattnerde1fede2010-01-05 05:31:55 +0000225 for (unsigned op = 0, e = OperandPhis.size(); op != e; ++op)
226 if (PHINode *OpPhi = OperandPhis[op])
227 OpPhi->addIncoming(InGEP->getOperand(op), InBB);
228 }
229 }
Jim Grosbachbdbd7342013-04-05 21:20:12 +0000230
Chris Lattnerde1fede2010-01-05 05:31:55 +0000231 Value *Base = FixedOperands[0];
Jim Grosbachbdbd7342013-04-05 21:20:12 +0000232 GetElementPtrInst *NewGEP =
David Blaikie741c8f82015-03-14 01:53:18 +0000233 GetElementPtrInst::Create(FirstInst->getSourceElementType(), Base,
234 makeArrayRef(FixedOperands).slice(1));
Chris Lattner75ae5a42011-02-17 22:32:54 +0000235 if (AllInBounds) NewGEP->setIsInBounds();
Eli Friedman35211c62011-05-27 00:19:40 +0000236 NewGEP->setDebugLoc(FirstInst->getDebugLoc());
Chris Lattnerabb8eb22011-02-17 22:21:26 +0000237 return NewGEP;
Chris Lattnerde1fede2010-01-05 05:31:55 +0000238}
239
240
Sanjay Patel9b7e6772015-06-23 23:05:08 +0000241/// Return true if we know that it is safe to sink the load out of the block
242/// that defines it. This means that it must be obvious the value of the load is
243/// not changed from the point of the load to the end of the block it is in.
Chris Lattnerde1fede2010-01-05 05:31:55 +0000244///
Chris Lattner0ab5e2c2011-04-15 05:18:47 +0000245/// Finally, it is safe, but not profitable, to sink a load targeting a
Chris Lattnerde1fede2010-01-05 05:31:55 +0000246/// non-address-taken alloca. Doing so will cause us to not promote the alloca
247/// to a register.
248static bool isSafeAndProfitableToSinkLoad(LoadInst *L) {
Duncan P. N. Exon Smith9f8aaf22015-10-13 16:59:33 +0000249 BasicBlock::iterator BBI = L->getIterator(), E = L->getParent()->end();
Jim Grosbachbdbd7342013-04-05 21:20:12 +0000250
Chris Lattnerde1fede2010-01-05 05:31:55 +0000251 for (++BBI; BBI != E; ++BBI)
252 if (BBI->mayWriteToMemory())
253 return false;
Jim Grosbachbdbd7342013-04-05 21:20:12 +0000254
Chris Lattnerde1fede2010-01-05 05:31:55 +0000255 // Check for non-address taken alloca. If not address-taken already, it isn't
256 // profitable to do this xform.
257 if (AllocaInst *AI = dyn_cast<AllocaInst>(L->getOperand(0))) {
258 bool isAddressTaken = false;
Chandler Carruthcdf47882014-03-09 03:16:01 +0000259 for (User *U : AI->users()) {
Gabor Greif96fedcb2010-07-12 14:15:58 +0000260 if (isa<LoadInst>(U)) continue;
261 if (StoreInst *SI = dyn_cast<StoreInst>(U)) {
Chris Lattnerde1fede2010-01-05 05:31:55 +0000262 // If storing TO the alloca, then the address isn't taken.
263 if (SI->getOperand(1) == AI) continue;
264 }
265 isAddressTaken = true;
266 break;
267 }
Jim Grosbachbdbd7342013-04-05 21:20:12 +0000268
Chris Lattnerde1fede2010-01-05 05:31:55 +0000269 if (!isAddressTaken && AI->isStaticAlloca())
270 return false;
271 }
Jim Grosbachbdbd7342013-04-05 21:20:12 +0000272
Chris Lattnerde1fede2010-01-05 05:31:55 +0000273 // If this load is a load from a GEP with a constant offset from an alloca,
274 // then we don't want to sink it. In its present form, it will be
275 // load [constant stack offset]. Sinking it will cause us to have to
276 // materialize the stack addresses in each predecessor in a register only to
277 // do a shared load from register in the successor.
278 if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(L->getOperand(0)))
279 if (AllocaInst *AI = dyn_cast<AllocaInst>(GEP->getOperand(0)))
280 if (AI->isStaticAlloca() && GEP->hasAllConstantIndices())
281 return false;
Jim Grosbachbdbd7342013-04-05 21:20:12 +0000282
Chris Lattnerde1fede2010-01-05 05:31:55 +0000283 return true;
284}
285
286Instruction *InstCombiner::FoldPHIArgLoadIntoPHI(PHINode &PN) {
287 LoadInst *FirstLI = cast<LoadInst>(PN.getIncomingValue(0));
Eli Friedman8bc586e2011-08-15 22:09:40 +0000288
289 // FIXME: This is overconservative; this transform is allowed in some cases
290 // for atomic operations.
291 if (FirstLI->isAtomic())
Craig Topperf40110f2014-04-25 05:29:35 +0000292 return nullptr;
Eli Friedman8bc586e2011-08-15 22:09:40 +0000293
Chris Lattnerde1fede2010-01-05 05:31:55 +0000294 // When processing loads, we need to propagate two bits of information to the
295 // sunk load: whether it is volatile, and what its alignment is. We currently
296 // don't sink loads when some have their alignment specified and some don't.
297 // visitLoadInst will propagate an alignment onto the load when TD is around,
298 // and if TD isn't around, we can't handle the mixed case.
299 bool isVolatile = FirstLI->isVolatile();
300 unsigned LoadAlignment = FirstLI->getAlignment();
Chris Lattnerf6befff2010-03-05 18:53:28 +0000301 unsigned LoadAddrSpace = FirstLI->getPointerAddressSpace();
Jim Grosbachbdbd7342013-04-05 21:20:12 +0000302
Chris Lattnerde1fede2010-01-05 05:31:55 +0000303 // We can't sink the load if the loaded value could be modified between the
304 // load and the PHI.
305 if (FirstLI->getParent() != PN.getIncomingBlock(0) ||
306 !isSafeAndProfitableToSinkLoad(FirstLI))
Craig Topperf40110f2014-04-25 05:29:35 +0000307 return nullptr;
Jim Grosbachbdbd7342013-04-05 21:20:12 +0000308
Chris Lattnerde1fede2010-01-05 05:31:55 +0000309 // If the PHI is of volatile loads and the load block has multiple
310 // successors, sinking it would remove a load of the volatile value from
311 // the path through the other successor.
Jim Grosbachbdbd7342013-04-05 21:20:12 +0000312 if (isVolatile &&
Chris Lattnerde1fede2010-01-05 05:31:55 +0000313 FirstLI->getParent()->getTerminator()->getNumSuccessors() != 1)
Craig Topperf40110f2014-04-25 05:29:35 +0000314 return nullptr;
Jim Grosbachbdbd7342013-04-05 21:20:12 +0000315
Chris Lattnerde1fede2010-01-05 05:31:55 +0000316 // Check to see if all arguments are the same operation.
317 for (unsigned i = 1, e = PN.getNumIncomingValues(); i != e; ++i) {
318 LoadInst *LI = dyn_cast<LoadInst>(PN.getIncomingValue(i));
319 if (!LI || !LI->hasOneUse())
Craig Topperf40110f2014-04-25 05:29:35 +0000320 return nullptr;
Jim Grosbachbdbd7342013-04-05 21:20:12 +0000321
322 // We can't sink the load if the loaded value could be modified between
Chris Lattnerde1fede2010-01-05 05:31:55 +0000323 // the load and the PHI.
324 if (LI->isVolatile() != isVolatile ||
325 LI->getParent() != PN.getIncomingBlock(i) ||
Chris Lattnerf6befff2010-03-05 18:53:28 +0000326 LI->getPointerAddressSpace() != LoadAddrSpace ||
Chris Lattnerde1fede2010-01-05 05:31:55 +0000327 !isSafeAndProfitableToSinkLoad(LI))
Craig Topperf40110f2014-04-25 05:29:35 +0000328 return nullptr;
Jim Grosbachbdbd7342013-04-05 21:20:12 +0000329
Chris Lattnerde1fede2010-01-05 05:31:55 +0000330 // If some of the loads have an alignment specified but not all of them,
331 // we can't do the transformation.
332 if ((LoadAlignment != 0) != (LI->getAlignment() != 0))
Craig Topperf40110f2014-04-25 05:29:35 +0000333 return nullptr;
Jim Grosbachbdbd7342013-04-05 21:20:12 +0000334
Chris Lattnerde1fede2010-01-05 05:31:55 +0000335 LoadAlignment = std::min(LoadAlignment, LI->getAlignment());
Jim Grosbachbdbd7342013-04-05 21:20:12 +0000336
Chris Lattnerde1fede2010-01-05 05:31:55 +0000337 // If the PHI is of volatile loads and the load block has multiple
338 // successors, sinking it would remove a load of the volatile value from
339 // the path through the other successor.
340 if (isVolatile &&
341 LI->getParent()->getTerminator()->getNumSuccessors() != 1)
Craig Topperf40110f2014-04-25 05:29:35 +0000342 return nullptr;
Chris Lattnerde1fede2010-01-05 05:31:55 +0000343 }
Jim Grosbachbdbd7342013-04-05 21:20:12 +0000344
Chris Lattnerde1fede2010-01-05 05:31:55 +0000345 // Okay, they are all the same operation. Create a new PHI node of the
346 // correct type, and PHI together all of the LHS's of the instructions.
347 PHINode *NewPN = PHINode::Create(FirstLI->getOperand(0)->getType(),
Jay Foad52131342011-03-30 11:28:46 +0000348 PN.getNumIncomingValues(),
Chris Lattnerde1fede2010-01-05 05:31:55 +0000349 PN.getName()+".in");
Jim Grosbachbdbd7342013-04-05 21:20:12 +0000350
Chris Lattnerde1fede2010-01-05 05:31:55 +0000351 Value *InVal = FirstLI->getOperand(0);
352 NewPN->addIncoming(InVal, PN.getIncomingBlock(0));
Akira Hatanakaf6afd112015-09-23 18:40:57 +0000353 LoadInst *NewLI = new LoadInst(NewPN, "", isVolatile, LoadAlignment);
Jim Grosbachbdbd7342013-04-05 21:20:12 +0000354
Akira Hatanakaf6afd112015-09-23 18:40:57 +0000355 unsigned KnownIDs[] = {
356 LLVMContext::MD_tbaa,
357 LLVMContext::MD_range,
358 LLVMContext::MD_invariant_load,
359 LLVMContext::MD_alias_scope,
360 LLVMContext::MD_noalias,
Artur Pilipenko5c5011d2015-11-02 17:53:51 +0000361 LLVMContext::MD_nonnull,
362 LLVMContext::MD_align,
363 LLVMContext::MD_dereferenceable,
364 LLVMContext::MD_dereferenceable_or_null,
Akira Hatanakaf6afd112015-09-23 18:40:57 +0000365 };
366
367 for (unsigned ID : KnownIDs)
368 NewLI->setMetadata(ID, FirstLI->getMetadata(ID));
369
370 // Add all operands to the new PHI and combine TBAA metadata.
Chris Lattnerde1fede2010-01-05 05:31:55 +0000371 for (unsigned i = 1, e = PN.getNumIncomingValues(); i != e; ++i) {
Akira Hatanakaf6afd112015-09-23 18:40:57 +0000372 LoadInst *LI = cast<LoadInst>(PN.getIncomingValue(i));
373 combineMetadata(NewLI, LI, KnownIDs);
374 Value *NewInVal = LI->getOperand(0);
Chris Lattnerde1fede2010-01-05 05:31:55 +0000375 if (NewInVal != InVal)
Craig Topperf40110f2014-04-25 05:29:35 +0000376 InVal = nullptr;
Chris Lattnerde1fede2010-01-05 05:31:55 +0000377 NewPN->addIncoming(NewInVal, PN.getIncomingBlock(i));
378 }
Jim Grosbachbdbd7342013-04-05 21:20:12 +0000379
Chris Lattnerde1fede2010-01-05 05:31:55 +0000380 if (InVal) {
381 // The new PHI unions all of the same values together. This is really
382 // common, so we handle it intelligently here for compile-time speed.
Akira Hatanakaf6afd112015-09-23 18:40:57 +0000383 NewLI->setOperand(0, InVal);
Chris Lattnerde1fede2010-01-05 05:31:55 +0000384 delete NewPN;
385 } else {
386 InsertNewInstBefore(NewPN, PN);
Chris Lattnerde1fede2010-01-05 05:31:55 +0000387 }
Jim Grosbachbdbd7342013-04-05 21:20:12 +0000388
Chris Lattnerde1fede2010-01-05 05:31:55 +0000389 // If this was a volatile load that we are merging, make sure to loop through
390 // and mark all the input loads as non-volatile. If we don't do this, we will
391 // insert a new volatile load and the old ones will not be deletable.
392 if (isVolatile)
Pete Cooper833f34d2015-05-12 20:05:31 +0000393 for (Value *IncValue : PN.incoming_values())
394 cast<LoadInst>(IncValue)->setVolatile(false);
Jim Grosbachbdbd7342013-04-05 21:20:12 +0000395
Eli Friedman35211c62011-05-27 00:19:40 +0000396 NewLI->setDebugLoc(FirstLI->getDebugLoc());
397 return NewLI;
Chris Lattnerde1fede2010-01-05 05:31:55 +0000398}
399
Sanjay Patel95334072015-09-27 20:34:31 +0000400/// TODO: This function could handle other cast types, but then it might
401/// require special-casing a cast from the 'i1' type. See the comment in
402/// FoldPHIArgOpIntoPHI() about pessimizing illegal integer types.
403Instruction *InstCombiner::FoldPHIArgZextsIntoPHI(PHINode &Phi) {
404 // Early exit for the common case of a phi with two operands. These are
405 // handled elsewhere. See the comment below where we check the count of zexts
406 // and constants for more details.
407 unsigned NumIncomingValues = Phi.getNumIncomingValues();
408 if (NumIncomingValues < 3)
409 return nullptr;
Chris Lattnerde1fede2010-01-05 05:31:55 +0000410
Sanjay Patel95334072015-09-27 20:34:31 +0000411 // Find the narrower type specified by the first zext.
412 Type *NarrowType = nullptr;
413 for (Value *V : Phi.incoming_values()) {
414 if (auto *Zext = dyn_cast<ZExtInst>(V)) {
415 NarrowType = Zext->getSrcTy();
416 break;
417 }
418 }
419 if (!NarrowType)
420 return nullptr;
421
422 // Walk the phi operands checking that we only have zexts or constants that
423 // we can shrink for free. Store the new operands for the new phi.
424 SmallVector<Value *, 4> NewIncoming;
425 unsigned NumZexts = 0;
426 unsigned NumConsts = 0;
427 for (Value *V : Phi.incoming_values()) {
428 if (auto *Zext = dyn_cast<ZExtInst>(V)) {
429 // All zexts must be identical and have one use.
430 if (Zext->getSrcTy() != NarrowType || !Zext->hasOneUse())
431 return nullptr;
432 NewIncoming.push_back(Zext->getOperand(0));
433 NumZexts++;
434 } else if (auto *C = dyn_cast<Constant>(V)) {
435 // Make sure that constants can fit in the new type.
436 Constant *Trunc = ConstantExpr::getTrunc(C, NarrowType);
437 if (ConstantExpr::getZExt(Trunc, C->getType()) != C)
438 return nullptr;
439 NewIncoming.push_back(Trunc);
440 NumConsts++;
441 } else {
442 // If it's not a cast or a constant, bail out.
443 return nullptr;
444 }
445 }
446
447 // The more common cases of a phi with no constant operands or just one
448 // variable operand are handled by FoldPHIArgOpIntoPHI() and FoldOpIntoPhi()
449 // respectively. FoldOpIntoPhi() wants to do the opposite transform that is
450 // performed here. It tries to replicate a cast in the phi operand's basic
451 // block to expose other folding opportunities. Thus, InstCombine will
452 // infinite loop without this check.
453 if (NumConsts == 0 || NumZexts < 2)
454 return nullptr;
455
456 // All incoming values are zexts or constants that are safe to truncate.
457 // Create a new phi node of the narrow type, phi together all of the new
458 // operands, and zext the result back to the original type.
459 PHINode *NewPhi = PHINode::Create(NarrowType, NumIncomingValues,
460 Phi.getName() + ".shrunk");
461 for (unsigned i = 0; i != NumIncomingValues; ++i)
462 NewPhi->addIncoming(NewIncoming[i], Phi.getIncomingBlock(i));
463
464 InsertNewInstBefore(NewPhi, Phi);
465 return CastInst::CreateZExtOrBitCast(NewPhi, Phi.getType());
466}
Chris Lattnerde1fede2010-01-05 05:31:55 +0000467
Sanjay Patel9b7e6772015-06-23 23:05:08 +0000468/// If all operands to a PHI node are the same "unary" operator and they all are
469/// only used by the PHI, PHI together their inputs, and do the operation once,
470/// to the result of the PHI.
Chris Lattnerde1fede2010-01-05 05:31:55 +0000471Instruction *InstCombiner::FoldPHIArgOpIntoPHI(PHINode &PN) {
472 Instruction *FirstInst = cast<Instruction>(PN.getIncomingValue(0));
473
474 if (isa<GetElementPtrInst>(FirstInst))
475 return FoldPHIArgGEPIntoPHI(PN);
476 if (isa<LoadInst>(FirstInst))
477 return FoldPHIArgLoadIntoPHI(PN);
Jim Grosbachbdbd7342013-04-05 21:20:12 +0000478
Chris Lattnerde1fede2010-01-05 05:31:55 +0000479 // Scan the instruction, looking for input operations that can be folded away.
480 // If all input operands to the phi are the same instruction (e.g. a cast from
481 // the same type or "+42") we can pull the operation through the PHI, reducing
482 // code size and simplifying code.
Craig Topperf40110f2014-04-25 05:29:35 +0000483 Constant *ConstantOp = nullptr;
484 Type *CastSrcTy = nullptr;
Chris Lattnera8fed472011-02-17 23:01:49 +0000485 bool isNUW = false, isNSW = false, isExact = false;
Jim Grosbachbdbd7342013-04-05 21:20:12 +0000486
Chris Lattnerde1fede2010-01-05 05:31:55 +0000487 if (isa<CastInst>(FirstInst)) {
488 CastSrcTy = FirstInst->getOperand(0)->getType();
489
490 // Be careful about transforming integer PHIs. We don't want to pessimize
491 // the code by turning an i32 into an i1293.
Duncan Sands19d0b472010-02-16 11:11:14 +0000492 if (PN.getType()->isIntegerTy() && CastSrcTy->isIntegerTy()) {
Chris Lattnerde1fede2010-01-05 05:31:55 +0000493 if (!ShouldChangeType(PN.getType(), CastSrcTy))
Craig Topperf40110f2014-04-25 05:29:35 +0000494 return nullptr;
Chris Lattnerde1fede2010-01-05 05:31:55 +0000495 }
496 } else if (isa<BinaryOperator>(FirstInst) || isa<CmpInst>(FirstInst)) {
Jim Grosbachbdbd7342013-04-05 21:20:12 +0000497 // Can fold binop, compare or shift here if the RHS is a constant,
Chris Lattnerde1fede2010-01-05 05:31:55 +0000498 // otherwise call FoldPHIArgBinOpIntoPHI.
499 ConstantOp = dyn_cast<Constant>(FirstInst->getOperand(1));
Craig Topperf40110f2014-04-25 05:29:35 +0000500 if (!ConstantOp)
Chris Lattnerde1fede2010-01-05 05:31:55 +0000501 return FoldPHIArgBinOpIntoPHI(PN);
Jim Grosbachbdbd7342013-04-05 21:20:12 +0000502
Chris Lattnera8fed472011-02-17 23:01:49 +0000503 if (OverflowingBinaryOperator *BO =
504 dyn_cast<OverflowingBinaryOperator>(FirstInst)) {
505 isNUW = BO->hasNoUnsignedWrap();
506 isNSW = BO->hasNoSignedWrap();
507 } else if (PossiblyExactOperator *PEO =
508 dyn_cast<PossiblyExactOperator>(FirstInst))
509 isExact = PEO->isExact();
Chris Lattnerde1fede2010-01-05 05:31:55 +0000510 } else {
Craig Topperf40110f2014-04-25 05:29:35 +0000511 return nullptr; // Cannot fold this operation.
Chris Lattnerde1fede2010-01-05 05:31:55 +0000512 }
513
514 // Check to see if all arguments are the same operation.
515 for (unsigned i = 1, e = PN.getNumIncomingValues(); i != e; ++i) {
516 Instruction *I = dyn_cast<Instruction>(PN.getIncomingValue(i));
Craig Topperf40110f2014-04-25 05:29:35 +0000517 if (!I || !I->hasOneUse() || !I->isSameOperationAs(FirstInst))
518 return nullptr;
Chris Lattnerde1fede2010-01-05 05:31:55 +0000519 if (CastSrcTy) {
520 if (I->getOperand(0)->getType() != CastSrcTy)
Craig Topperf40110f2014-04-25 05:29:35 +0000521 return nullptr; // Cast operation must match.
Chris Lattnerde1fede2010-01-05 05:31:55 +0000522 } else if (I->getOperand(1) != ConstantOp) {
Craig Topperf40110f2014-04-25 05:29:35 +0000523 return nullptr;
Chris Lattnerde1fede2010-01-05 05:31:55 +0000524 }
Jim Grosbachbdbd7342013-04-05 21:20:12 +0000525
Chris Lattnera8fed472011-02-17 23:01:49 +0000526 if (isNUW)
527 isNUW = cast<OverflowingBinaryOperator>(I)->hasNoUnsignedWrap();
528 if (isNSW)
529 isNSW = cast<OverflowingBinaryOperator>(I)->hasNoSignedWrap();
530 if (isExact)
531 isExact = cast<PossiblyExactOperator>(I)->isExact();
Chris Lattnerde1fede2010-01-05 05:31:55 +0000532 }
533
534 // Okay, they are all the same operation. Create a new PHI node of the
535 // correct type, and PHI together all of the LHS's of the instructions.
536 PHINode *NewPN = PHINode::Create(FirstInst->getOperand(0)->getType(),
Jay Foad52131342011-03-30 11:28:46 +0000537 PN.getNumIncomingValues(),
Chris Lattnerde1fede2010-01-05 05:31:55 +0000538 PN.getName()+".in");
Chris Lattnerde1fede2010-01-05 05:31:55 +0000539
540 Value *InVal = FirstInst->getOperand(0);
541 NewPN->addIncoming(InVal, PN.getIncomingBlock(0));
542
543 // Add all operands to the new PHI.
544 for (unsigned i = 1, e = PN.getNumIncomingValues(); i != e; ++i) {
545 Value *NewInVal = cast<Instruction>(PN.getIncomingValue(i))->getOperand(0);
546 if (NewInVal != InVal)
Craig Topperf40110f2014-04-25 05:29:35 +0000547 InVal = nullptr;
Chris Lattnerde1fede2010-01-05 05:31:55 +0000548 NewPN->addIncoming(NewInVal, PN.getIncomingBlock(i));
549 }
550
551 Value *PhiVal;
552 if (InVal) {
553 // The new PHI unions all of the same values together. This is really
554 // common, so we handle it intelligently here for compile-time speed.
555 PhiVal = InVal;
556 delete NewPN;
557 } else {
558 InsertNewInstBefore(NewPN, PN);
559 PhiVal = NewPN;
560 }
561
562 // Insert and return the new operation.
Eli Friedman35211c62011-05-27 00:19:40 +0000563 if (CastInst *FirstCI = dyn_cast<CastInst>(FirstInst)) {
564 CastInst *NewCI = CastInst::Create(FirstCI->getOpcode(), PhiVal,
565 PN.getType());
566 NewCI->setDebugLoc(FirstInst->getDebugLoc());
567 return NewCI;
568 }
Jim Grosbachbdbd7342013-04-05 21:20:12 +0000569
Chris Lattnera8fed472011-02-17 23:01:49 +0000570 if (BinaryOperator *BinOp = dyn_cast<BinaryOperator>(FirstInst)) {
571 BinOp = BinaryOperator::Create(BinOp->getOpcode(), PhiVal, ConstantOp);
572 if (isNUW) BinOp->setHasNoUnsignedWrap();
573 if (isNSW) BinOp->setHasNoSignedWrap();
574 if (isExact) BinOp->setIsExact();
Eli Friedman35211c62011-05-27 00:19:40 +0000575 BinOp->setDebugLoc(FirstInst->getDebugLoc());
Chris Lattnera8fed472011-02-17 23:01:49 +0000576 return BinOp;
577 }
Jim Grosbachbdbd7342013-04-05 21:20:12 +0000578
Chris Lattnerde1fede2010-01-05 05:31:55 +0000579 CmpInst *CIOp = cast<CmpInst>(FirstInst);
Eli Friedman35211c62011-05-27 00:19:40 +0000580 CmpInst *NewCI = CmpInst::Create(CIOp->getOpcode(), CIOp->getPredicate(),
581 PhiVal, ConstantOp);
582 NewCI->setDebugLoc(FirstInst->getDebugLoc());
583 return NewCI;
Chris Lattnerde1fede2010-01-05 05:31:55 +0000584}
585
Sanjay Patel9b7e6772015-06-23 23:05:08 +0000586/// Return true if this PHI node is only used by a PHI node cycle that is dead.
Chris Lattnerde1fede2010-01-05 05:31:55 +0000587static bool DeadPHICycle(PHINode *PN,
Craig Topper71b7b682014-08-21 05:55:13 +0000588 SmallPtrSetImpl<PHINode*> &PotentiallyDeadPHIs) {
Chris Lattnerde1fede2010-01-05 05:31:55 +0000589 if (PN->use_empty()) return true;
590 if (!PN->hasOneUse()) return false;
591
592 // Remember this node, and if we find the cycle, return.
David Blaikie70573dc2014-11-19 07:49:26 +0000593 if (!PotentiallyDeadPHIs.insert(PN).second)
Chris Lattnerde1fede2010-01-05 05:31:55 +0000594 return true;
Jim Grosbachbdbd7342013-04-05 21:20:12 +0000595
Chris Lattnerde1fede2010-01-05 05:31:55 +0000596 // Don't scan crazily complex things.
597 if (PotentiallyDeadPHIs.size() == 16)
598 return false;
599
Chandler Carruthcdf47882014-03-09 03:16:01 +0000600 if (PHINode *PU = dyn_cast<PHINode>(PN->user_back()))
Chris Lattnerde1fede2010-01-05 05:31:55 +0000601 return DeadPHICycle(PU, PotentiallyDeadPHIs);
602
603 return false;
604}
605
Sanjay Patel9b7e6772015-06-23 23:05:08 +0000606/// Return true if this phi node is always equal to NonPhiInVal.
607/// This happens with mutually cyclic phi nodes like:
Chris Lattnerde1fede2010-01-05 05:31:55 +0000608/// z = some value; x = phi (y, z); y = phi (x, z)
Jim Grosbachbdbd7342013-04-05 21:20:12 +0000609static bool PHIsEqualValue(PHINode *PN, Value *NonPhiInVal,
Craig Topper71b7b682014-08-21 05:55:13 +0000610 SmallPtrSetImpl<PHINode*> &ValueEqualPHIs) {
Chris Lattnerde1fede2010-01-05 05:31:55 +0000611 // See if we already saw this PHI node.
David Blaikie70573dc2014-11-19 07:49:26 +0000612 if (!ValueEqualPHIs.insert(PN).second)
Chris Lattnerde1fede2010-01-05 05:31:55 +0000613 return true;
Jim Grosbachbdbd7342013-04-05 21:20:12 +0000614
Chris Lattnerde1fede2010-01-05 05:31:55 +0000615 // Don't scan crazily complex things.
616 if (ValueEqualPHIs.size() == 16)
617 return false;
Jim Grosbachbdbd7342013-04-05 21:20:12 +0000618
Chris Lattnerde1fede2010-01-05 05:31:55 +0000619 // Scan the operands to see if they are either phi nodes or are equal to
620 // the value.
Pete Cooper833f34d2015-05-12 20:05:31 +0000621 for (Value *Op : PN->incoming_values()) {
Chris Lattnerde1fede2010-01-05 05:31:55 +0000622 if (PHINode *OpPN = dyn_cast<PHINode>(Op)) {
623 if (!PHIsEqualValue(OpPN, NonPhiInVal, ValueEqualPHIs))
624 return false;
625 } else if (Op != NonPhiInVal)
626 return false;
627 }
Jim Grosbachbdbd7342013-04-05 21:20:12 +0000628
Chris Lattnerde1fede2010-01-05 05:31:55 +0000629 return true;
630}
631
632
633namespace {
634struct PHIUsageRecord {
635 unsigned PHIId; // The ID # of the PHI (something determinstic to sort on)
636 unsigned Shift; // The amount shifted.
637 Instruction *Inst; // The trunc instruction.
Jim Grosbachbdbd7342013-04-05 21:20:12 +0000638
Chris Lattnerde1fede2010-01-05 05:31:55 +0000639 PHIUsageRecord(unsigned pn, unsigned Sh, Instruction *User)
640 : PHIId(pn), Shift(Sh), Inst(User) {}
Jim Grosbachbdbd7342013-04-05 21:20:12 +0000641
Chris Lattnerde1fede2010-01-05 05:31:55 +0000642 bool operator<(const PHIUsageRecord &RHS) const {
643 if (PHIId < RHS.PHIId) return true;
644 if (PHIId > RHS.PHIId) return false;
645 if (Shift < RHS.Shift) return true;
646 if (Shift > RHS.Shift) return false;
647 return Inst->getType()->getPrimitiveSizeInBits() <
648 RHS.Inst->getType()->getPrimitiveSizeInBits();
649 }
650};
Jim Grosbachbdbd7342013-04-05 21:20:12 +0000651
Chris Lattnerde1fede2010-01-05 05:31:55 +0000652struct LoweredPHIRecord {
653 PHINode *PN; // The PHI that was lowered.
654 unsigned Shift; // The amount shifted.
655 unsigned Width; // The width extracted.
Jim Grosbachbdbd7342013-04-05 21:20:12 +0000656
Chris Lattner229907c2011-07-18 04:54:35 +0000657 LoweredPHIRecord(PHINode *pn, unsigned Sh, Type *Ty)
Chris Lattnerde1fede2010-01-05 05:31:55 +0000658 : PN(pn), Shift(Sh), Width(Ty->getPrimitiveSizeInBits()) {}
Jim Grosbachbdbd7342013-04-05 21:20:12 +0000659
Chris Lattnerde1fede2010-01-05 05:31:55 +0000660 // Ctor form used by DenseMap.
661 LoweredPHIRecord(PHINode *pn, unsigned Sh)
662 : PN(pn), Shift(Sh), Width(0) {}
663};
Alexander Kornienkof00654e2015-06-23 09:49:53 +0000664}
Chris Lattnerde1fede2010-01-05 05:31:55 +0000665
666namespace llvm {
667 template<>
668 struct DenseMapInfo<LoweredPHIRecord> {
669 static inline LoweredPHIRecord getEmptyKey() {
Craig Topperf40110f2014-04-25 05:29:35 +0000670 return LoweredPHIRecord(nullptr, 0);
Chris Lattnerde1fede2010-01-05 05:31:55 +0000671 }
672 static inline LoweredPHIRecord getTombstoneKey() {
Craig Topperf40110f2014-04-25 05:29:35 +0000673 return LoweredPHIRecord(nullptr, 1);
Chris Lattnerde1fede2010-01-05 05:31:55 +0000674 }
675 static unsigned getHashValue(const LoweredPHIRecord &Val) {
676 return DenseMapInfo<PHINode*>::getHashValue(Val.PN) ^ (Val.Shift>>3) ^
677 (Val.Width>>3);
678 }
679 static bool isEqual(const LoweredPHIRecord &LHS,
680 const LoweredPHIRecord &RHS) {
681 return LHS.PN == RHS.PN && LHS.Shift == RHS.Shift &&
682 LHS.Width == RHS.Width;
683 }
684 };
Alexander Kornienkof00654e2015-06-23 09:49:53 +0000685}
Chris Lattnerde1fede2010-01-05 05:31:55 +0000686
687
Sanjay Patel9b7e6772015-06-23 23:05:08 +0000688/// This is an integer PHI and we know that it has an illegal type: see if it is
689/// only used by trunc or trunc(lshr) operations. If so, we split the PHI into
690/// the various pieces being extracted. This sort of thing is introduced when
691/// SROA promotes an aggregate to large integer values.
Chris Lattnerde1fede2010-01-05 05:31:55 +0000692///
693/// TODO: The user of the trunc may be an bitcast to float/double/vector or an
694/// inttoptr. We should produce new PHIs in the right type.
695///
696Instruction *InstCombiner::SliceUpIllegalIntegerPHI(PHINode &FirstPhi) {
697 // PHIUsers - Keep track of all of the truncated values extracted from a set
698 // of PHIs, along with their offset. These are the things we want to rewrite.
699 SmallVector<PHIUsageRecord, 16> PHIUsers;
Jim Grosbachbdbd7342013-04-05 21:20:12 +0000700
Chris Lattnerde1fede2010-01-05 05:31:55 +0000701 // PHIs are often mutually cyclic, so we keep track of a whole set of PHI
702 // nodes which are extracted from. PHIsToSlice is a set we use to avoid
703 // revisiting PHIs, PHIsInspected is a ordered list of PHIs that we need to
704 // check the uses of (to ensure they are all extracts).
705 SmallVector<PHINode*, 8> PHIsToSlice;
706 SmallPtrSet<PHINode*, 8> PHIsInspected;
Jim Grosbachbdbd7342013-04-05 21:20:12 +0000707
Chris Lattnerde1fede2010-01-05 05:31:55 +0000708 PHIsToSlice.push_back(&FirstPhi);
709 PHIsInspected.insert(&FirstPhi);
Jim Grosbachbdbd7342013-04-05 21:20:12 +0000710
Chris Lattnerde1fede2010-01-05 05:31:55 +0000711 for (unsigned PHIId = 0; PHIId != PHIsToSlice.size(); ++PHIId) {
712 PHINode *PN = PHIsToSlice[PHIId];
Jim Grosbachbdbd7342013-04-05 21:20:12 +0000713
Chris Lattnerde1fede2010-01-05 05:31:55 +0000714 // Scan the input list of the PHI. If any input is an invoke, and if the
715 // input is defined in the predecessor, then we won't be split the critical
716 // edge which is required to insert a truncate. Because of this, we have to
717 // bail out.
718 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) {
719 InvokeInst *II = dyn_cast<InvokeInst>(PN->getIncomingValue(i));
Craig Topperf40110f2014-04-25 05:29:35 +0000720 if (!II) continue;
Chris Lattnerde1fede2010-01-05 05:31:55 +0000721 if (II->getParent() != PN->getIncomingBlock(i))
722 continue;
Jim Grosbachbdbd7342013-04-05 21:20:12 +0000723
Chris Lattnerde1fede2010-01-05 05:31:55 +0000724 // If we have a phi, and if it's directly in the predecessor, then we have
725 // a critical edge where we need to put the truncate. Since we can't
726 // split the edge in instcombine, we have to bail out.
Craig Topperf40110f2014-04-25 05:29:35 +0000727 return nullptr;
Chris Lattnerde1fede2010-01-05 05:31:55 +0000728 }
Jim Grosbachbdbd7342013-04-05 21:20:12 +0000729
Chandler Carruthcdf47882014-03-09 03:16:01 +0000730 for (User *U : PN->users()) {
731 Instruction *UserI = cast<Instruction>(U);
Jim Grosbachbdbd7342013-04-05 21:20:12 +0000732
Chris Lattnerde1fede2010-01-05 05:31:55 +0000733 // If the user is a PHI, inspect its uses recursively.
Chandler Carruthcdf47882014-03-09 03:16:01 +0000734 if (PHINode *UserPN = dyn_cast<PHINode>(UserI)) {
David Blaikie70573dc2014-11-19 07:49:26 +0000735 if (PHIsInspected.insert(UserPN).second)
Chris Lattnerde1fede2010-01-05 05:31:55 +0000736 PHIsToSlice.push_back(UserPN);
737 continue;
738 }
Jim Grosbachbdbd7342013-04-05 21:20:12 +0000739
Chris Lattnerde1fede2010-01-05 05:31:55 +0000740 // Truncates are always ok.
Chandler Carruthcdf47882014-03-09 03:16:01 +0000741 if (isa<TruncInst>(UserI)) {
742 PHIUsers.push_back(PHIUsageRecord(PHIId, 0, UserI));
Chris Lattnerde1fede2010-01-05 05:31:55 +0000743 continue;
744 }
Jim Grosbachbdbd7342013-04-05 21:20:12 +0000745
Chris Lattnerde1fede2010-01-05 05:31:55 +0000746 // Otherwise it must be a lshr which can only be used by one trunc.
Chandler Carruthcdf47882014-03-09 03:16:01 +0000747 if (UserI->getOpcode() != Instruction::LShr ||
748 !UserI->hasOneUse() || !isa<TruncInst>(UserI->user_back()) ||
749 !isa<ConstantInt>(UserI->getOperand(1)))
Craig Topperf40110f2014-04-25 05:29:35 +0000750 return nullptr;
Jim Grosbachbdbd7342013-04-05 21:20:12 +0000751
Chandler Carruthcdf47882014-03-09 03:16:01 +0000752 unsigned Shift = cast<ConstantInt>(UserI->getOperand(1))->getZExtValue();
753 PHIUsers.push_back(PHIUsageRecord(PHIId, Shift, UserI->user_back()));
Chris Lattnerde1fede2010-01-05 05:31:55 +0000754 }
755 }
Jim Grosbachbdbd7342013-04-05 21:20:12 +0000756
Chris Lattnerde1fede2010-01-05 05:31:55 +0000757 // If we have no users, they must be all self uses, just nuke the PHI.
758 if (PHIUsers.empty())
759 return ReplaceInstUsesWith(FirstPhi, UndefValue::get(FirstPhi.getType()));
Jim Grosbachbdbd7342013-04-05 21:20:12 +0000760
Chris Lattnerde1fede2010-01-05 05:31:55 +0000761 // If this phi node is transformable, create new PHIs for all the pieces
762 // extracted out of it. First, sort the users by their offset and size.
763 array_pod_sort(PHIUsers.begin(), PHIUsers.end());
Jim Grosbachbdbd7342013-04-05 21:20:12 +0000764
Matt Arsenaulte6db7602013-09-05 19:48:28 +0000765 DEBUG(dbgs() << "SLICING UP PHI: " << FirstPhi << '\n';
766 for (unsigned i = 1, e = PHIsToSlice.size(); i != e; ++i)
767 dbgs() << "AND USER PHI #" << i << ": " << *PHIsToSlice[i] << '\n';
768 );
Jim Grosbachbdbd7342013-04-05 21:20:12 +0000769
Chris Lattnerde1fede2010-01-05 05:31:55 +0000770 // PredValues - This is a temporary used when rewriting PHI nodes. It is
771 // hoisted out here to avoid construction/destruction thrashing.
772 DenseMap<BasicBlock*, Value*> PredValues;
Jim Grosbachbdbd7342013-04-05 21:20:12 +0000773
Chris Lattnerde1fede2010-01-05 05:31:55 +0000774 // ExtractedVals - Each new PHI we introduce is saved here so we don't
775 // introduce redundant PHIs.
776 DenseMap<LoweredPHIRecord, PHINode*> ExtractedVals;
Jim Grosbachbdbd7342013-04-05 21:20:12 +0000777
Chris Lattnerde1fede2010-01-05 05:31:55 +0000778 for (unsigned UserI = 0, UserE = PHIUsers.size(); UserI != UserE; ++UserI) {
779 unsigned PHIId = PHIUsers[UserI].PHIId;
780 PHINode *PN = PHIsToSlice[PHIId];
781 unsigned Offset = PHIUsers[UserI].Shift;
Chris Lattner229907c2011-07-18 04:54:35 +0000782 Type *Ty = PHIUsers[UserI].Inst->getType();
Jim Grosbachbdbd7342013-04-05 21:20:12 +0000783
Chris Lattnerde1fede2010-01-05 05:31:55 +0000784 PHINode *EltPHI;
Jim Grosbachbdbd7342013-04-05 21:20:12 +0000785
Chris Lattnerde1fede2010-01-05 05:31:55 +0000786 // If we've already lowered a user like this, reuse the previously lowered
787 // value.
Craig Topperf40110f2014-04-25 05:29:35 +0000788 if ((EltPHI = ExtractedVals[LoweredPHIRecord(PN, Offset, Ty)]) == nullptr) {
Jim Grosbachbdbd7342013-04-05 21:20:12 +0000789
Chris Lattnerde1fede2010-01-05 05:31:55 +0000790 // Otherwise, Create the new PHI node for this user.
Jay Foad52131342011-03-30 11:28:46 +0000791 EltPHI = PHINode::Create(Ty, PN->getNumIncomingValues(),
792 PN->getName()+".off"+Twine(Offset), PN);
Chris Lattnerde1fede2010-01-05 05:31:55 +0000793 assert(EltPHI->getType() != PN->getType() &&
794 "Truncate didn't shrink phi?");
Jim Grosbachbdbd7342013-04-05 21:20:12 +0000795
Chris Lattnerde1fede2010-01-05 05:31:55 +0000796 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) {
797 BasicBlock *Pred = PN->getIncomingBlock(i);
798 Value *&PredVal = PredValues[Pred];
Jim Grosbachbdbd7342013-04-05 21:20:12 +0000799
Chris Lattnerde1fede2010-01-05 05:31:55 +0000800 // If we already have a value for this predecessor, reuse it.
801 if (PredVal) {
802 EltPHI->addIncoming(PredVal, Pred);
803 continue;
804 }
805
806 // Handle the PHI self-reuse case.
807 Value *InVal = PN->getIncomingValue(i);
808 if (InVal == PN) {
809 PredVal = EltPHI;
810 EltPHI->addIncoming(PredVal, Pred);
811 continue;
812 }
Jim Grosbachbdbd7342013-04-05 21:20:12 +0000813
Chris Lattnerde1fede2010-01-05 05:31:55 +0000814 if (PHINode *InPHI = dyn_cast<PHINode>(PN)) {
815 // If the incoming value was a PHI, and if it was one of the PHIs we
816 // already rewrote it, just use the lowered value.
817 if (Value *Res = ExtractedVals[LoweredPHIRecord(InPHI, Offset, Ty)]) {
818 PredVal = Res;
819 EltPHI->addIncoming(PredVal, Pred);
820 continue;
821 }
822 }
Jim Grosbachbdbd7342013-04-05 21:20:12 +0000823
Chris Lattnerde1fede2010-01-05 05:31:55 +0000824 // Otherwise, do an extract in the predecessor.
Duncan P. N. Exon Smith9f8aaf22015-10-13 16:59:33 +0000825 Builder->SetInsertPoint(Pred->getTerminator());
Chris Lattnerde1fede2010-01-05 05:31:55 +0000826 Value *Res = InVal;
827 if (Offset)
828 Res = Builder->CreateLShr(Res, ConstantInt::get(InVal->getType(),
829 Offset), "extract");
830 Res = Builder->CreateTrunc(Res, Ty, "extract.t");
831 PredVal = Res;
832 EltPHI->addIncoming(Res, Pred);
Jim Grosbachbdbd7342013-04-05 21:20:12 +0000833
Chris Lattnerde1fede2010-01-05 05:31:55 +0000834 // If the incoming value was a PHI, and if it was one of the PHIs we are
835 // rewriting, we will ultimately delete the code we inserted. This
836 // means we need to revisit that PHI to make sure we extract out the
837 // needed piece.
838 if (PHINode *OldInVal = dyn_cast<PHINode>(PN->getIncomingValue(i)))
839 if (PHIsInspected.count(OldInVal)) {
840 unsigned RefPHIId = std::find(PHIsToSlice.begin(),PHIsToSlice.end(),
841 OldInVal)-PHIsToSlice.begin();
Jim Grosbachbdbd7342013-04-05 21:20:12 +0000842 PHIUsers.push_back(PHIUsageRecord(RefPHIId, Offset,
Chris Lattnerde1fede2010-01-05 05:31:55 +0000843 cast<Instruction>(Res)));
844 ++UserE;
845 }
846 }
847 PredValues.clear();
Jim Grosbachbdbd7342013-04-05 21:20:12 +0000848
Matt Arsenaulte6db7602013-09-05 19:48:28 +0000849 DEBUG(dbgs() << " Made element PHI for offset " << Offset << ": "
Chris Lattnerde1fede2010-01-05 05:31:55 +0000850 << *EltPHI << '\n');
851 ExtractedVals[LoweredPHIRecord(PN, Offset, Ty)] = EltPHI;
852 }
Jim Grosbachbdbd7342013-04-05 21:20:12 +0000853
Chris Lattnerde1fede2010-01-05 05:31:55 +0000854 // Replace the use of this piece with the PHI node.
855 ReplaceInstUsesWith(*PHIUsers[UserI].Inst, EltPHI);
856 }
Jim Grosbachbdbd7342013-04-05 21:20:12 +0000857
Chris Lattnerde1fede2010-01-05 05:31:55 +0000858 // Replace all the remaining uses of the PHI nodes (self uses and the lshrs)
859 // with undefs.
860 Value *Undef = UndefValue::get(FirstPhi.getType());
861 for (unsigned i = 1, e = PHIsToSlice.size(); i != e; ++i)
862 ReplaceInstUsesWith(*PHIsToSlice[i], Undef);
863 return ReplaceInstUsesWith(FirstPhi, Undef);
864}
865
866// PHINode simplification
867//
868Instruction *InstCombiner::visitPHINode(PHINode &PN) {
Chandler Carruth66b31302015-01-04 12:03:27 +0000869 if (Value *V = SimplifyInstruction(&PN, DL, TLI, DT, AC))
Chris Lattnerde1fede2010-01-05 05:31:55 +0000870 return ReplaceInstUsesWith(PN, V);
871
Sanjay Patel95334072015-09-27 20:34:31 +0000872 if (Instruction *Result = FoldPHIArgZextsIntoPHI(PN))
873 return Result;
874
Chris Lattnerde1fede2010-01-05 05:31:55 +0000875 // If all PHI operands are the same operation, pull them through the PHI,
876 // reducing code size.
877 if (isa<Instruction>(PN.getIncomingValue(0)) &&
878 isa<Instruction>(PN.getIncomingValue(1)) &&
879 cast<Instruction>(PN.getIncomingValue(0))->getOpcode() ==
880 cast<Instruction>(PN.getIncomingValue(1))->getOpcode() &&
881 // FIXME: The hasOneUse check will fail for PHIs that use the value more
882 // than themselves more than once.
883 PN.getIncomingValue(0)->hasOneUse())
884 if (Instruction *Result = FoldPHIArgOpIntoPHI(PN))
885 return Result;
886
887 // If this is a trivial cycle in the PHI node graph, remove it. Basically, if
888 // this PHI only has a single use (a PHI), and if that PHI only has one use (a
889 // PHI)... break the cycle.
890 if (PN.hasOneUse()) {
Chandler Carruthcdf47882014-03-09 03:16:01 +0000891 Instruction *PHIUser = cast<Instruction>(PN.user_back());
Chris Lattnerde1fede2010-01-05 05:31:55 +0000892 if (PHINode *PU = dyn_cast<PHINode>(PHIUser)) {
893 SmallPtrSet<PHINode*, 16> PotentiallyDeadPHIs;
894 PotentiallyDeadPHIs.insert(&PN);
895 if (DeadPHICycle(PU, PotentiallyDeadPHIs))
896 return ReplaceInstUsesWith(PN, UndefValue::get(PN.getType()));
897 }
Jim Grosbachbdbd7342013-04-05 21:20:12 +0000898
Chris Lattnerde1fede2010-01-05 05:31:55 +0000899 // If this phi has a single use, and if that use just computes a value for
900 // the next iteration of a loop, delete the phi. This occurs with unused
901 // induction variables, e.g. "for (int j = 0; ; ++j);". Detecting this
902 // common case here is good because the only other things that catch this
903 // are induction variable analysis (sometimes) and ADCE, which is only run
904 // late.
905 if (PHIUser->hasOneUse() &&
906 (isa<BinaryOperator>(PHIUser) || isa<GetElementPtrInst>(PHIUser)) &&
Chandler Carruthcdf47882014-03-09 03:16:01 +0000907 PHIUser->user_back() == &PN) {
Chris Lattnerde1fede2010-01-05 05:31:55 +0000908 return ReplaceInstUsesWith(PN, UndefValue::get(PN.getType()));
909 }
910 }
911
912 // We sometimes end up with phi cycles that non-obviously end up being the
913 // same value, for example:
914 // z = some value; x = phi (y, z); y = phi (x, z)
915 // where the phi nodes don't necessarily need to be in the same block. Do a
916 // quick check to see if the PHI node only contains a single non-phi value, if
917 // so, scan to see if the phi cycle is actually equal to that value.
918 {
Frits van Bommeld6d4f982011-04-16 14:32:34 +0000919 unsigned InValNo = 0, NumIncomingVals = PN.getNumIncomingValues();
Chris Lattnerde1fede2010-01-05 05:31:55 +0000920 // Scan for the first non-phi operand.
Frits van Bommeld6d4f982011-04-16 14:32:34 +0000921 while (InValNo != NumIncomingVals &&
Chris Lattnerde1fede2010-01-05 05:31:55 +0000922 isa<PHINode>(PN.getIncomingValue(InValNo)))
923 ++InValNo;
924
Frits van Bommeld6d4f982011-04-16 14:32:34 +0000925 if (InValNo != NumIncomingVals) {
Jay Foad7d03e9b2011-04-16 14:17:37 +0000926 Value *NonPhiInVal = PN.getIncomingValue(InValNo);
Jim Grosbachbdbd7342013-04-05 21:20:12 +0000927
Chris Lattnerde1fede2010-01-05 05:31:55 +0000928 // Scan the rest of the operands to see if there are any conflicts, if so
929 // there is no need to recursively scan other phis.
Frits van Bommeld6d4f982011-04-16 14:32:34 +0000930 for (++InValNo; InValNo != NumIncomingVals; ++InValNo) {
Chris Lattnerde1fede2010-01-05 05:31:55 +0000931 Value *OpVal = PN.getIncomingValue(InValNo);
932 if (OpVal != NonPhiInVal && !isa<PHINode>(OpVal))
933 break;
934 }
Jim Grosbachbdbd7342013-04-05 21:20:12 +0000935
Chris Lattnerde1fede2010-01-05 05:31:55 +0000936 // If we scanned over all operands, then we have one unique value plus
937 // phi values. Scan PHI nodes to see if they all merge in each other or
938 // the value.
Frits van Bommeld6d4f982011-04-16 14:32:34 +0000939 if (InValNo == NumIncomingVals) {
Chris Lattnerde1fede2010-01-05 05:31:55 +0000940 SmallPtrSet<PHINode*, 16> ValueEqualPHIs;
941 if (PHIsEqualValue(&PN, NonPhiInVal, ValueEqualPHIs))
942 return ReplaceInstUsesWith(PN, NonPhiInVal);
943 }
944 }
945 }
946
947 // If there are multiple PHIs, sort their operands so that they all list
948 // the blocks in the same order. This will help identical PHIs be eliminated
949 // by other passes. Other passes shouldn't depend on this for correctness
950 // however.
951 PHINode *FirstPN = cast<PHINode>(PN.getParent()->begin());
952 if (&PN != FirstPN)
953 for (unsigned i = 0, e = FirstPN->getNumIncomingValues(); i != e; ++i) {
954 BasicBlock *BBA = PN.getIncomingBlock(i);
955 BasicBlock *BBB = FirstPN->getIncomingBlock(i);
956 if (BBA != BBB) {
957 Value *VA = PN.getIncomingValue(i);
958 unsigned j = PN.getBasicBlockIndex(BBB);
959 Value *VB = PN.getIncomingValue(j);
960 PN.setIncomingBlock(i, BBB);
961 PN.setIncomingValue(i, VB);
962 PN.setIncomingBlock(j, BBA);
963 PN.setIncomingValue(j, VA);
964 // NOTE: Instcombine normally would want us to "return &PN" if we
965 // modified any of the operands of an instruction. However, since we
966 // aren't adding or removing uses (just rearranging them) we don't do
967 // this in this case.
968 }
969 }
970
971 // If this is an integer PHI and we know that it has an illegal type, see if
972 // it is only used by trunc or trunc(lshr) operations. If so, we split the
973 // PHI into the various pieces being extracted. This sort of thing is
974 // introduced when SROA promotes an aggregate to a single large integer type.
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000975 if (PN.getType()->isIntegerTy() &&
976 !DL.isLegalInteger(PN.getType()->getPrimitiveSizeInBits()))
Chris Lattnerde1fede2010-01-05 05:31:55 +0000977 if (Instruction *Res = SliceUpIllegalIntegerPHI(PN))
978 return Res;
Jim Grosbachbdbd7342013-04-05 21:20:12 +0000979
Craig Topperf40110f2014-04-25 05:29:35 +0000980 return nullptr;
Benjamin Kramerf7cc6982010-01-05 13:32:48 +0000981}