blob: 79a4912332ff30014939d7839987dd783af5ebf2 [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"
Jun Bum Lim339e9722016-02-11 15:50:07 +000018#include "llvm/Analysis/ValueTracking.h"
19#include "llvm/IR/PatternMatch.h"
Akira Hatanakaf6afd112015-09-23 18:40:57 +000020#include "llvm/Transforms/Utils/Local.h"
Chris Lattnerde1fede2010-01-05 05:31:55 +000021using namespace llvm;
Jun Bum Lim339e9722016-02-11 15:50:07 +000022using namespace llvm::PatternMatch;
Chris Lattnerde1fede2010-01-05 05:31:55 +000023
Chandler Carruth964daaa2014-04-22 02:55:47 +000024#define DEBUG_TYPE "instcombine"
25
Sanjay Patel9b7e6772015-06-23 23:05:08 +000026/// If we have something like phi [add (a,b), add(a,c)] and if a/b/c and the
27/// adds all have a single use, turn this into a phi and a single binop.
Chris Lattnerde1fede2010-01-05 05:31:55 +000028Instruction *InstCombiner::FoldPHIArgBinOpIntoPHI(PHINode &PN) {
29 Instruction *FirstInst = cast<Instruction>(PN.getIncomingValue(0));
30 assert(isa<BinaryOperator>(FirstInst) || isa<CmpInst>(FirstInst));
31 unsigned Opc = FirstInst->getOpcode();
32 Value *LHSVal = FirstInst->getOperand(0);
33 Value *RHSVal = FirstInst->getOperand(1);
Jim Grosbachbdbd7342013-04-05 21:20:12 +000034
Chris Lattner229907c2011-07-18 04:54:35 +000035 Type *LHSType = LHSVal->getType();
36 Type *RHSType = RHSVal->getType();
Jim Grosbachbdbd7342013-04-05 21:20:12 +000037
Chris Lattnerde1fede2010-01-05 05:31:55 +000038 // Scan to see if all operands are the same opcode, and all have one use.
39 for (unsigned i = 1; i != PN.getNumIncomingValues(); ++i) {
40 Instruction *I = dyn_cast<Instruction>(PN.getIncomingValue(i));
41 if (!I || I->getOpcode() != Opc || !I->hasOneUse() ||
42 // Verify type of the LHS matches so we don't fold cmp's of different
Chris Lattnera8fed472011-02-17 23:01:49 +000043 // types.
Chris Lattnerde1fede2010-01-05 05:31:55 +000044 I->getOperand(0)->getType() != LHSType ||
45 I->getOperand(1)->getType() != RHSType)
Craig Topperf40110f2014-04-25 05:29:35 +000046 return nullptr;
Chris Lattnerde1fede2010-01-05 05:31:55 +000047
48 // If they are CmpInst instructions, check their predicates
Chris Lattnera8fed472011-02-17 23:01:49 +000049 if (CmpInst *CI = dyn_cast<CmpInst>(I))
50 if (CI->getPredicate() != cast<CmpInst>(FirstInst)->getPredicate())
Craig Topperf40110f2014-04-25 05:29:35 +000051 return nullptr;
Jim Grosbachbdbd7342013-04-05 21:20:12 +000052
Chris Lattnerde1fede2010-01-05 05:31:55 +000053 // Keep track of which operand needs a phi node.
Craig Topperf40110f2014-04-25 05:29:35 +000054 if (I->getOperand(0) != LHSVal) LHSVal = nullptr;
55 if (I->getOperand(1) != RHSVal) RHSVal = nullptr;
Chris Lattnerde1fede2010-01-05 05:31:55 +000056 }
57
58 // If both LHS and RHS would need a PHI, don't do this transformation,
59 // because it would increase the number of PHIs entering the block,
60 // which leads to higher register pressure. This is especially
61 // bad when the PHIs are in the header of a loop.
62 if (!LHSVal && !RHSVal)
Craig Topperf40110f2014-04-25 05:29:35 +000063 return nullptr;
Jim Grosbachbdbd7342013-04-05 21:20:12 +000064
Chris Lattnerde1fede2010-01-05 05:31:55 +000065 // Otherwise, this is safe to transform!
Jim Grosbachbdbd7342013-04-05 21:20:12 +000066
Chris Lattnerde1fede2010-01-05 05:31:55 +000067 Value *InLHS = FirstInst->getOperand(0);
68 Value *InRHS = FirstInst->getOperand(1);
Craig Topperf40110f2014-04-25 05:29:35 +000069 PHINode *NewLHS = nullptr, *NewRHS = nullptr;
70 if (!LHSVal) {
Jay Foad52131342011-03-30 11:28:46 +000071 NewLHS = PHINode::Create(LHSType, PN.getNumIncomingValues(),
Chris Lattnerde1fede2010-01-05 05:31:55 +000072 FirstInst->getOperand(0)->getName() + ".pn");
Chris Lattnerde1fede2010-01-05 05:31:55 +000073 NewLHS->addIncoming(InLHS, PN.getIncomingBlock(0));
74 InsertNewInstBefore(NewLHS, PN);
75 LHSVal = NewLHS;
76 }
Jim Grosbachbdbd7342013-04-05 21:20:12 +000077
Craig Topperf40110f2014-04-25 05:29:35 +000078 if (!RHSVal) {
Jay Foad52131342011-03-30 11:28:46 +000079 NewRHS = PHINode::Create(RHSType, PN.getNumIncomingValues(),
Chris Lattnerde1fede2010-01-05 05:31:55 +000080 FirstInst->getOperand(1)->getName() + ".pn");
Chris Lattnerde1fede2010-01-05 05:31:55 +000081 NewRHS->addIncoming(InRHS, PN.getIncomingBlock(0));
82 InsertNewInstBefore(NewRHS, PN);
83 RHSVal = NewRHS;
84 }
Jim Grosbachbdbd7342013-04-05 21:20:12 +000085
Chris Lattnerde1fede2010-01-05 05:31:55 +000086 // Add all operands to the new PHIs.
87 if (NewLHS || NewRHS) {
88 for (unsigned i = 1, e = PN.getNumIncomingValues(); i != e; ++i) {
89 Instruction *InInst = cast<Instruction>(PN.getIncomingValue(i));
90 if (NewLHS) {
91 Value *NewInLHS = InInst->getOperand(0);
92 NewLHS->addIncoming(NewInLHS, PN.getIncomingBlock(i));
93 }
94 if (NewRHS) {
95 Value *NewInRHS = InInst->getOperand(1);
96 NewRHS->addIncoming(NewInRHS, PN.getIncomingBlock(i));
97 }
98 }
99 }
Jim Grosbachbdbd7342013-04-05 21:20:12 +0000100
Eli Friedman35211c62011-05-27 00:19:40 +0000101 if (CmpInst *CIOp = dyn_cast<CmpInst>(FirstInst)) {
102 CmpInst *NewCI = CmpInst::Create(CIOp->getOpcode(), CIOp->getPredicate(),
103 LHSVal, RHSVal);
104 NewCI->setDebugLoc(FirstInst->getDebugLoc());
105 return NewCI;
106 }
107
Chris Lattnera8fed472011-02-17 23:01:49 +0000108 BinaryOperator *BinOp = cast<BinaryOperator>(FirstInst);
109 BinaryOperator *NewBinOp =
110 BinaryOperator::Create(BinOp->getOpcode(), LHSVal, RHSVal);
Silviu Barangae985c762016-04-22 11:21:36 +0000111
112 NewBinOp->copyIRFlags(PN.getIncomingValue(0));
113
114 for (unsigned i = 1, e = PN.getNumIncomingValues(); i != e; ++i)
115 NewBinOp->andIRFlags(PN.getIncomingValue(i));
116
Eli Friedman35211c62011-05-27 00:19:40 +0000117 NewBinOp->setDebugLoc(FirstInst->getDebugLoc());
Chris Lattnera8fed472011-02-17 23:01:49 +0000118 return NewBinOp;
Chris Lattnerde1fede2010-01-05 05:31:55 +0000119}
120
121Instruction *InstCombiner::FoldPHIArgGEPIntoPHI(PHINode &PN) {
122 GetElementPtrInst *FirstInst =cast<GetElementPtrInst>(PN.getIncomingValue(0));
Jim Grosbachbdbd7342013-04-05 21:20:12 +0000123
124 SmallVector<Value*, 16> FixedOperands(FirstInst->op_begin(),
Chris Lattnerde1fede2010-01-05 05:31:55 +0000125 FirstInst->op_end());
126 // This is true if all GEP bases are allocas and if all indices into them are
127 // constants.
128 bool AllBasePointersAreAllocas = true;
129
130 // We don't want to replace this phi if the replacement would require
131 // more than one phi, which leads to higher register pressure. This is
132 // especially bad when the PHIs are in the header of a loop.
133 bool NeededPhi = false;
Jim Grosbachbdbd7342013-04-05 21:20:12 +0000134
Chris Lattnerabb8eb22011-02-17 22:21:26 +0000135 bool AllInBounds = true;
Jim Grosbachbdbd7342013-04-05 21:20:12 +0000136
Chris Lattnerde1fede2010-01-05 05:31:55 +0000137 // Scan to see if all operands are the same opcode, and all have one use.
138 for (unsigned i = 1; i != PN.getNumIncomingValues(); ++i) {
139 GetElementPtrInst *GEP= dyn_cast<GetElementPtrInst>(PN.getIncomingValue(i));
140 if (!GEP || !GEP->hasOneUse() || GEP->getType() != FirstInst->getType() ||
141 GEP->getNumOperands() != FirstInst->getNumOperands())
Craig Topperf40110f2014-04-25 05:29:35 +0000142 return nullptr;
Chris Lattnerde1fede2010-01-05 05:31:55 +0000143
Chris Lattnerabb8eb22011-02-17 22:21:26 +0000144 AllInBounds &= GEP->isInBounds();
Jim Grosbachbdbd7342013-04-05 21:20:12 +0000145
Chris Lattnerde1fede2010-01-05 05:31:55 +0000146 // Keep track of whether or not all GEPs are of alloca pointers.
147 if (AllBasePointersAreAllocas &&
148 (!isa<AllocaInst>(GEP->getOperand(0)) ||
149 !GEP->hasAllConstantIndices()))
150 AllBasePointersAreAllocas = false;
Jim Grosbachbdbd7342013-04-05 21:20:12 +0000151
Chris Lattnerde1fede2010-01-05 05:31:55 +0000152 // Compare the operand lists.
153 for (unsigned op = 0, e = FirstInst->getNumOperands(); op != e; ++op) {
154 if (FirstInst->getOperand(op) == GEP->getOperand(op))
155 continue;
Jim Grosbachbdbd7342013-04-05 21:20:12 +0000156
Chris Lattnerde1fede2010-01-05 05:31:55 +0000157 // Don't merge two GEPs when two operands differ (introducing phi nodes)
158 // if one of the PHIs has a constant for the index. The index may be
159 // substantially cheaper to compute for the constants, so making it a
160 // variable index could pessimize the path. This also handles the case
161 // for struct indices, which must always be constant.
162 if (isa<ConstantInt>(FirstInst->getOperand(op)) ||
163 isa<ConstantInt>(GEP->getOperand(op)))
Craig Topperf40110f2014-04-25 05:29:35 +0000164 return nullptr;
Jim Grosbachbdbd7342013-04-05 21:20:12 +0000165
Chris Lattnerde1fede2010-01-05 05:31:55 +0000166 if (FirstInst->getOperand(op)->getType() !=GEP->getOperand(op)->getType())
Craig Topperf40110f2014-04-25 05:29:35 +0000167 return nullptr;
Chris Lattnerde1fede2010-01-05 05:31:55 +0000168
169 // If we already needed a PHI for an earlier operand, and another operand
170 // also requires a PHI, we'd be introducing more PHIs than we're
171 // eliminating, which increases register pressure on entry to the PHI's
172 // block.
173 if (NeededPhi)
Craig Topperf40110f2014-04-25 05:29:35 +0000174 return nullptr;
Chris Lattnerde1fede2010-01-05 05:31:55 +0000175
Craig Topperf40110f2014-04-25 05:29:35 +0000176 FixedOperands[op] = nullptr; // Needs a PHI.
Chris Lattnerde1fede2010-01-05 05:31:55 +0000177 NeededPhi = true;
178 }
179 }
Jim Grosbachbdbd7342013-04-05 21:20:12 +0000180
Chris Lattnerde1fede2010-01-05 05:31:55 +0000181 // If all of the base pointers of the PHI'd GEPs are from allocas, don't
182 // bother doing this transformation. At best, this will just save a bit of
183 // offset calculation, but all the predecessors will have to materialize the
184 // stack address into a register anyway. We'd actually rather *clone* the
185 // load up into the predecessors so that we have a load of a gep of an alloca,
186 // which can usually all be folded into the load.
187 if (AllBasePointersAreAllocas)
Craig Topperf40110f2014-04-25 05:29:35 +0000188 return nullptr;
Jim Grosbachbdbd7342013-04-05 21:20:12 +0000189
Chris Lattnerde1fede2010-01-05 05:31:55 +0000190 // Otherwise, this is safe to transform. Insert PHI nodes for each operand
191 // that is variable.
192 SmallVector<PHINode*, 16> OperandPhis(FixedOperands.size());
Jim Grosbachbdbd7342013-04-05 21:20:12 +0000193
Chris Lattnerde1fede2010-01-05 05:31:55 +0000194 bool HasAnyPHIs = false;
195 for (unsigned i = 0, e = FixedOperands.size(); i != e; ++i) {
196 if (FixedOperands[i]) continue; // operand doesn't need a phi.
197 Value *FirstOp = FirstInst->getOperand(i);
Jay Foad52131342011-03-30 11:28:46 +0000198 PHINode *NewPN = PHINode::Create(FirstOp->getType(), e,
Chris Lattnerde1fede2010-01-05 05:31:55 +0000199 FirstOp->getName()+".pn");
200 InsertNewInstBefore(NewPN, PN);
Jim Grosbachbdbd7342013-04-05 21:20:12 +0000201
Chris Lattnerde1fede2010-01-05 05:31:55 +0000202 NewPN->addIncoming(FirstOp, PN.getIncomingBlock(0));
203 OperandPhis[i] = NewPN;
204 FixedOperands[i] = NewPN;
205 HasAnyPHIs = true;
206 }
207
Jim Grosbachbdbd7342013-04-05 21:20:12 +0000208
Chris Lattnerde1fede2010-01-05 05:31:55 +0000209 // Add all operands to the new PHIs.
210 if (HasAnyPHIs) {
211 for (unsigned i = 1, e = PN.getNumIncomingValues(); i != e; ++i) {
212 GetElementPtrInst *InGEP =cast<GetElementPtrInst>(PN.getIncomingValue(i));
213 BasicBlock *InBB = PN.getIncomingBlock(i);
Jim Grosbachbdbd7342013-04-05 21:20:12 +0000214
Chris Lattnerde1fede2010-01-05 05:31:55 +0000215 for (unsigned op = 0, e = OperandPhis.size(); op != e; ++op)
216 if (PHINode *OpPhi = OperandPhis[op])
217 OpPhi->addIncoming(InGEP->getOperand(op), InBB);
218 }
219 }
Jim Grosbachbdbd7342013-04-05 21:20:12 +0000220
Chris Lattnerde1fede2010-01-05 05:31:55 +0000221 Value *Base = FixedOperands[0];
Jim Grosbachbdbd7342013-04-05 21:20:12 +0000222 GetElementPtrInst *NewGEP =
David Blaikie741c8f82015-03-14 01:53:18 +0000223 GetElementPtrInst::Create(FirstInst->getSourceElementType(), Base,
224 makeArrayRef(FixedOperands).slice(1));
Chris Lattner75ae5a42011-02-17 22:32:54 +0000225 if (AllInBounds) NewGEP->setIsInBounds();
Eli Friedman35211c62011-05-27 00:19:40 +0000226 NewGEP->setDebugLoc(FirstInst->getDebugLoc());
Chris Lattnerabb8eb22011-02-17 22:21:26 +0000227 return NewGEP;
Chris Lattnerde1fede2010-01-05 05:31:55 +0000228}
229
230
Sanjay Patel9b7e6772015-06-23 23:05:08 +0000231/// Return true if we know that it is safe to sink the load out of the block
232/// that defines it. This means that it must be obvious the value of the load is
233/// not changed from the point of the load to the end of the block it is in.
Chris Lattnerde1fede2010-01-05 05:31:55 +0000234///
Chris Lattner0ab5e2c2011-04-15 05:18:47 +0000235/// Finally, it is safe, but not profitable, to sink a load targeting a
Chris Lattnerde1fede2010-01-05 05:31:55 +0000236/// non-address-taken alloca. Doing so will cause us to not promote the alloca
237/// to a register.
238static bool isSafeAndProfitableToSinkLoad(LoadInst *L) {
Duncan P. N. Exon Smith9f8aaf22015-10-13 16:59:33 +0000239 BasicBlock::iterator BBI = L->getIterator(), E = L->getParent()->end();
Jim Grosbachbdbd7342013-04-05 21:20:12 +0000240
Chris Lattnerde1fede2010-01-05 05:31:55 +0000241 for (++BBI; BBI != E; ++BBI)
242 if (BBI->mayWriteToMemory())
243 return false;
Jim Grosbachbdbd7342013-04-05 21:20:12 +0000244
Chris Lattnerde1fede2010-01-05 05:31:55 +0000245 // Check for non-address taken alloca. If not address-taken already, it isn't
246 // profitable to do this xform.
247 if (AllocaInst *AI = dyn_cast<AllocaInst>(L->getOperand(0))) {
248 bool isAddressTaken = false;
Chandler Carruthcdf47882014-03-09 03:16:01 +0000249 for (User *U : AI->users()) {
Gabor Greif96fedcb2010-07-12 14:15:58 +0000250 if (isa<LoadInst>(U)) continue;
251 if (StoreInst *SI = dyn_cast<StoreInst>(U)) {
Chris Lattnerde1fede2010-01-05 05:31:55 +0000252 // If storing TO the alloca, then the address isn't taken.
253 if (SI->getOperand(1) == AI) continue;
254 }
255 isAddressTaken = true;
256 break;
257 }
Jim Grosbachbdbd7342013-04-05 21:20:12 +0000258
Chris Lattnerde1fede2010-01-05 05:31:55 +0000259 if (!isAddressTaken && AI->isStaticAlloca())
260 return false;
261 }
Jim Grosbachbdbd7342013-04-05 21:20:12 +0000262
Chris Lattnerde1fede2010-01-05 05:31:55 +0000263 // If this load is a load from a GEP with a constant offset from an alloca,
264 // then we don't want to sink it. In its present form, it will be
265 // load [constant stack offset]. Sinking it will cause us to have to
266 // materialize the stack addresses in each predecessor in a register only to
267 // do a shared load from register in the successor.
268 if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(L->getOperand(0)))
269 if (AllocaInst *AI = dyn_cast<AllocaInst>(GEP->getOperand(0)))
270 if (AI->isStaticAlloca() && GEP->hasAllConstantIndices())
271 return false;
Jim Grosbachbdbd7342013-04-05 21:20:12 +0000272
Chris Lattnerde1fede2010-01-05 05:31:55 +0000273 return true;
274}
275
276Instruction *InstCombiner::FoldPHIArgLoadIntoPHI(PHINode &PN) {
277 LoadInst *FirstLI = cast<LoadInst>(PN.getIncomingValue(0));
Eli Friedman8bc586e2011-08-15 22:09:40 +0000278
279 // FIXME: This is overconservative; this transform is allowed in some cases
280 // for atomic operations.
281 if (FirstLI->isAtomic())
Craig Topperf40110f2014-04-25 05:29:35 +0000282 return nullptr;
Eli Friedman8bc586e2011-08-15 22:09:40 +0000283
Chris Lattnerde1fede2010-01-05 05:31:55 +0000284 // When processing loads, we need to propagate two bits of information to the
285 // sunk load: whether it is volatile, and what its alignment is. We currently
286 // don't sink loads when some have their alignment specified and some don't.
287 // visitLoadInst will propagate an alignment onto the load when TD is around,
288 // and if TD isn't around, we can't handle the mixed case.
289 bool isVolatile = FirstLI->isVolatile();
290 unsigned LoadAlignment = FirstLI->getAlignment();
Chris Lattnerf6befff2010-03-05 18:53:28 +0000291 unsigned LoadAddrSpace = FirstLI->getPointerAddressSpace();
Jim Grosbachbdbd7342013-04-05 21:20:12 +0000292
Chris Lattnerde1fede2010-01-05 05:31:55 +0000293 // We can't sink the load if the loaded value could be modified between the
294 // load and the PHI.
295 if (FirstLI->getParent() != PN.getIncomingBlock(0) ||
296 !isSafeAndProfitableToSinkLoad(FirstLI))
Craig Topperf40110f2014-04-25 05:29:35 +0000297 return nullptr;
Jim Grosbachbdbd7342013-04-05 21:20:12 +0000298
Chris Lattnerde1fede2010-01-05 05:31:55 +0000299 // If the PHI is of volatile loads and the load block has multiple
300 // successors, sinking it would remove a load of the volatile value from
301 // the path through the other successor.
Jim Grosbachbdbd7342013-04-05 21:20:12 +0000302 if (isVolatile &&
Chris Lattnerde1fede2010-01-05 05:31:55 +0000303 FirstLI->getParent()->getTerminator()->getNumSuccessors() != 1)
Craig Topperf40110f2014-04-25 05:29:35 +0000304 return nullptr;
Jim Grosbachbdbd7342013-04-05 21:20:12 +0000305
Chris Lattnerde1fede2010-01-05 05:31:55 +0000306 // Check to see if all arguments are the same operation.
307 for (unsigned i = 1, e = PN.getNumIncomingValues(); i != e; ++i) {
308 LoadInst *LI = dyn_cast<LoadInst>(PN.getIncomingValue(i));
309 if (!LI || !LI->hasOneUse())
Craig Topperf40110f2014-04-25 05:29:35 +0000310 return nullptr;
Jim Grosbachbdbd7342013-04-05 21:20:12 +0000311
312 // We can't sink the load if the loaded value could be modified between
Chris Lattnerde1fede2010-01-05 05:31:55 +0000313 // the load and the PHI.
314 if (LI->isVolatile() != isVolatile ||
315 LI->getParent() != PN.getIncomingBlock(i) ||
Chris Lattnerf6befff2010-03-05 18:53:28 +0000316 LI->getPointerAddressSpace() != LoadAddrSpace ||
Chris Lattnerde1fede2010-01-05 05:31:55 +0000317 !isSafeAndProfitableToSinkLoad(LI))
Craig Topperf40110f2014-04-25 05:29:35 +0000318 return nullptr;
Jim Grosbachbdbd7342013-04-05 21:20:12 +0000319
Chris Lattnerde1fede2010-01-05 05:31:55 +0000320 // If some of the loads have an alignment specified but not all of them,
321 // we can't do the transformation.
322 if ((LoadAlignment != 0) != (LI->getAlignment() != 0))
Craig Topperf40110f2014-04-25 05:29:35 +0000323 return nullptr;
Jim Grosbachbdbd7342013-04-05 21:20:12 +0000324
Chris Lattnerde1fede2010-01-05 05:31:55 +0000325 LoadAlignment = std::min(LoadAlignment, LI->getAlignment());
Jim Grosbachbdbd7342013-04-05 21:20:12 +0000326
Chris Lattnerde1fede2010-01-05 05:31:55 +0000327 // If the PHI is of volatile loads and the load block has multiple
328 // successors, sinking it would remove a load of the volatile value from
329 // the path through the other successor.
330 if (isVolatile &&
331 LI->getParent()->getTerminator()->getNumSuccessors() != 1)
Craig Topperf40110f2014-04-25 05:29:35 +0000332 return nullptr;
Chris Lattnerde1fede2010-01-05 05:31:55 +0000333 }
Jim Grosbachbdbd7342013-04-05 21:20:12 +0000334
Chris Lattnerde1fede2010-01-05 05:31:55 +0000335 // Okay, they are all the same operation. Create a new PHI node of the
336 // correct type, and PHI together all of the LHS's of the instructions.
337 PHINode *NewPN = PHINode::Create(FirstLI->getOperand(0)->getType(),
Jay Foad52131342011-03-30 11:28:46 +0000338 PN.getNumIncomingValues(),
Chris Lattnerde1fede2010-01-05 05:31:55 +0000339 PN.getName()+".in");
Jim Grosbachbdbd7342013-04-05 21:20:12 +0000340
Chris Lattnerde1fede2010-01-05 05:31:55 +0000341 Value *InVal = FirstLI->getOperand(0);
342 NewPN->addIncoming(InVal, PN.getIncomingBlock(0));
Akira Hatanakaf6afd112015-09-23 18:40:57 +0000343 LoadInst *NewLI = new LoadInst(NewPN, "", isVolatile, LoadAlignment);
Jim Grosbachbdbd7342013-04-05 21:20:12 +0000344
Akira Hatanakaf6afd112015-09-23 18:40:57 +0000345 unsigned KnownIDs[] = {
346 LLVMContext::MD_tbaa,
347 LLVMContext::MD_range,
348 LLVMContext::MD_invariant_load,
349 LLVMContext::MD_alias_scope,
350 LLVMContext::MD_noalias,
Artur Pilipenko5c5011d2015-11-02 17:53:51 +0000351 LLVMContext::MD_nonnull,
352 LLVMContext::MD_align,
353 LLVMContext::MD_dereferenceable,
354 LLVMContext::MD_dereferenceable_or_null,
Akira Hatanakaf6afd112015-09-23 18:40:57 +0000355 };
356
357 for (unsigned ID : KnownIDs)
358 NewLI->setMetadata(ID, FirstLI->getMetadata(ID));
359
360 // Add all operands to the new PHI and combine TBAA metadata.
Chris Lattnerde1fede2010-01-05 05:31:55 +0000361 for (unsigned i = 1, e = PN.getNumIncomingValues(); i != e; ++i) {
Akira Hatanakaf6afd112015-09-23 18:40:57 +0000362 LoadInst *LI = cast<LoadInst>(PN.getIncomingValue(i));
363 combineMetadata(NewLI, LI, KnownIDs);
364 Value *NewInVal = LI->getOperand(0);
Chris Lattnerde1fede2010-01-05 05:31:55 +0000365 if (NewInVal != InVal)
Craig Topperf40110f2014-04-25 05:29:35 +0000366 InVal = nullptr;
Chris Lattnerde1fede2010-01-05 05:31:55 +0000367 NewPN->addIncoming(NewInVal, PN.getIncomingBlock(i));
368 }
Jim Grosbachbdbd7342013-04-05 21:20:12 +0000369
Chris Lattnerde1fede2010-01-05 05:31:55 +0000370 if (InVal) {
371 // The new PHI unions all of the same values together. This is really
372 // common, so we handle it intelligently here for compile-time speed.
Akira Hatanakaf6afd112015-09-23 18:40:57 +0000373 NewLI->setOperand(0, InVal);
Chris Lattnerde1fede2010-01-05 05:31:55 +0000374 delete NewPN;
375 } else {
376 InsertNewInstBefore(NewPN, PN);
Chris Lattnerde1fede2010-01-05 05:31:55 +0000377 }
Jim Grosbachbdbd7342013-04-05 21:20:12 +0000378
Chris Lattnerde1fede2010-01-05 05:31:55 +0000379 // If this was a volatile load that we are merging, make sure to loop through
380 // and mark all the input loads as non-volatile. If we don't do this, we will
381 // insert a new volatile load and the old ones will not be deletable.
382 if (isVolatile)
Pete Cooper833f34d2015-05-12 20:05:31 +0000383 for (Value *IncValue : PN.incoming_values())
384 cast<LoadInst>(IncValue)->setVolatile(false);
Jim Grosbachbdbd7342013-04-05 21:20:12 +0000385
Eli Friedman35211c62011-05-27 00:19:40 +0000386 NewLI->setDebugLoc(FirstLI->getDebugLoc());
387 return NewLI;
Chris Lattnerde1fede2010-01-05 05:31:55 +0000388}
389
Sanjay Patel95334072015-09-27 20:34:31 +0000390/// TODO: This function could handle other cast types, but then it might
391/// require special-casing a cast from the 'i1' type. See the comment in
392/// FoldPHIArgOpIntoPHI() about pessimizing illegal integer types.
393Instruction *InstCombiner::FoldPHIArgZextsIntoPHI(PHINode &Phi) {
David Majnemereafa28a2015-11-07 00:52:53 +0000394 // We cannot create a new instruction after the PHI if the terminator is an
395 // EHPad because there is no valid insertion point.
396 if (TerminatorInst *TI = Phi.getParent()->getTerminator())
397 if (TI->isEHPad())
398 return nullptr;
399
Sanjay Patel95334072015-09-27 20:34:31 +0000400 // Early exit for the common case of a phi with two operands. These are
401 // handled elsewhere. See the comment below where we check the count of zexts
402 // and constants for more details.
403 unsigned NumIncomingValues = Phi.getNumIncomingValues();
404 if (NumIncomingValues < 3)
405 return nullptr;
Chris Lattnerde1fede2010-01-05 05:31:55 +0000406
Sanjay Patel95334072015-09-27 20:34:31 +0000407 // Find the narrower type specified by the first zext.
408 Type *NarrowType = nullptr;
409 for (Value *V : Phi.incoming_values()) {
410 if (auto *Zext = dyn_cast<ZExtInst>(V)) {
411 NarrowType = Zext->getSrcTy();
412 break;
413 }
414 }
415 if (!NarrowType)
416 return nullptr;
417
418 // Walk the phi operands checking that we only have zexts or constants that
419 // we can shrink for free. Store the new operands for the new phi.
420 SmallVector<Value *, 4> NewIncoming;
421 unsigned NumZexts = 0;
422 unsigned NumConsts = 0;
423 for (Value *V : Phi.incoming_values()) {
424 if (auto *Zext = dyn_cast<ZExtInst>(V)) {
425 // All zexts must be identical and have one use.
426 if (Zext->getSrcTy() != NarrowType || !Zext->hasOneUse())
427 return nullptr;
428 NewIncoming.push_back(Zext->getOperand(0));
429 NumZexts++;
430 } else if (auto *C = dyn_cast<Constant>(V)) {
431 // Make sure that constants can fit in the new type.
432 Constant *Trunc = ConstantExpr::getTrunc(C, NarrowType);
433 if (ConstantExpr::getZExt(Trunc, C->getType()) != C)
434 return nullptr;
435 NewIncoming.push_back(Trunc);
436 NumConsts++;
437 } else {
438 // If it's not a cast or a constant, bail out.
439 return nullptr;
440 }
441 }
442
443 // The more common cases of a phi with no constant operands or just one
444 // variable operand are handled by FoldPHIArgOpIntoPHI() and FoldOpIntoPhi()
445 // respectively. FoldOpIntoPhi() wants to do the opposite transform that is
446 // performed here. It tries to replicate a cast in the phi operand's basic
447 // block to expose other folding opportunities. Thus, InstCombine will
448 // infinite loop without this check.
449 if (NumConsts == 0 || NumZexts < 2)
450 return nullptr;
451
452 // All incoming values are zexts or constants that are safe to truncate.
453 // Create a new phi node of the narrow type, phi together all of the new
454 // operands, and zext the result back to the original type.
455 PHINode *NewPhi = PHINode::Create(NarrowType, NumIncomingValues,
456 Phi.getName() + ".shrunk");
457 for (unsigned i = 0; i != NumIncomingValues; ++i)
458 NewPhi->addIncoming(NewIncoming[i], Phi.getIncomingBlock(i));
459
460 InsertNewInstBefore(NewPhi, Phi);
461 return CastInst::CreateZExtOrBitCast(NewPhi, Phi.getType());
462}
Chris Lattnerde1fede2010-01-05 05:31:55 +0000463
Sanjay Patel9b7e6772015-06-23 23:05:08 +0000464/// If all operands to a PHI node are the same "unary" operator and they all are
465/// only used by the PHI, PHI together their inputs, and do the operation once,
466/// to the result of the PHI.
Chris Lattnerde1fede2010-01-05 05:31:55 +0000467Instruction *InstCombiner::FoldPHIArgOpIntoPHI(PHINode &PN) {
David Majnemer27f24472015-11-06 23:59:23 +0000468 // We cannot create a new instruction after the PHI if the terminator is an
469 // EHPad because there is no valid insertion point.
470 if (TerminatorInst *TI = PN.getParent()->getTerminator())
471 if (TI->isEHPad())
472 return nullptr;
473
Chris Lattnerde1fede2010-01-05 05:31:55 +0000474 Instruction *FirstInst = cast<Instruction>(PN.getIncomingValue(0));
475
476 if (isa<GetElementPtrInst>(FirstInst))
477 return FoldPHIArgGEPIntoPHI(PN);
478 if (isa<LoadInst>(FirstInst))
479 return FoldPHIArgLoadIntoPHI(PN);
Jim Grosbachbdbd7342013-04-05 21:20:12 +0000480
Chris Lattnerde1fede2010-01-05 05:31:55 +0000481 // Scan the instruction, looking for input operations that can be folded away.
482 // If all input operands to the phi are the same instruction (e.g. a cast from
483 // the same type or "+42") we can pull the operation through the PHI, reducing
484 // code size and simplifying code.
Craig Topperf40110f2014-04-25 05:29:35 +0000485 Constant *ConstantOp = nullptr;
486 Type *CastSrcTy = nullptr;
Jim Grosbachbdbd7342013-04-05 21:20:12 +0000487
Chris Lattnerde1fede2010-01-05 05:31:55 +0000488 if (isa<CastInst>(FirstInst)) {
489 CastSrcTy = FirstInst->getOperand(0)->getType();
490
491 // Be careful about transforming integer PHIs. We don't want to pessimize
492 // the code by turning an i32 into an i1293.
Duncan Sands19d0b472010-02-16 11:11:14 +0000493 if (PN.getType()->isIntegerTy() && CastSrcTy->isIntegerTy()) {
Chris Lattnerde1fede2010-01-05 05:31:55 +0000494 if (!ShouldChangeType(PN.getType(), CastSrcTy))
Craig Topperf40110f2014-04-25 05:29:35 +0000495 return nullptr;
Chris Lattnerde1fede2010-01-05 05:31:55 +0000496 }
497 } else if (isa<BinaryOperator>(FirstInst) || isa<CmpInst>(FirstInst)) {
Jim Grosbachbdbd7342013-04-05 21:20:12 +0000498 // Can fold binop, compare or shift here if the RHS is a constant,
Chris Lattnerde1fede2010-01-05 05:31:55 +0000499 // otherwise call FoldPHIArgBinOpIntoPHI.
500 ConstantOp = dyn_cast<Constant>(FirstInst->getOperand(1));
Craig Topperf40110f2014-04-25 05:29:35 +0000501 if (!ConstantOp)
Chris Lattnerde1fede2010-01-05 05:31:55 +0000502 return FoldPHIArgBinOpIntoPHI(PN);
503 } else {
Craig Topperf40110f2014-04-25 05:29:35 +0000504 return nullptr; // Cannot fold this operation.
Chris Lattnerde1fede2010-01-05 05:31:55 +0000505 }
506
507 // Check to see if all arguments are the same operation.
508 for (unsigned i = 1, e = PN.getNumIncomingValues(); i != e; ++i) {
509 Instruction *I = dyn_cast<Instruction>(PN.getIncomingValue(i));
Craig Topperf40110f2014-04-25 05:29:35 +0000510 if (!I || !I->hasOneUse() || !I->isSameOperationAs(FirstInst))
511 return nullptr;
Chris Lattnerde1fede2010-01-05 05:31:55 +0000512 if (CastSrcTy) {
513 if (I->getOperand(0)->getType() != CastSrcTy)
Craig Topperf40110f2014-04-25 05:29:35 +0000514 return nullptr; // Cast operation must match.
Chris Lattnerde1fede2010-01-05 05:31:55 +0000515 } else if (I->getOperand(1) != ConstantOp) {
Craig Topperf40110f2014-04-25 05:29:35 +0000516 return nullptr;
Chris Lattnerde1fede2010-01-05 05:31:55 +0000517 }
518 }
519
520 // Okay, they are all the same operation. Create a new PHI node of the
521 // correct type, and PHI together all of the LHS's of the instructions.
522 PHINode *NewPN = PHINode::Create(FirstInst->getOperand(0)->getType(),
Jay Foad52131342011-03-30 11:28:46 +0000523 PN.getNumIncomingValues(),
Chris Lattnerde1fede2010-01-05 05:31:55 +0000524 PN.getName()+".in");
Chris Lattnerde1fede2010-01-05 05:31:55 +0000525
526 Value *InVal = FirstInst->getOperand(0);
527 NewPN->addIncoming(InVal, PN.getIncomingBlock(0));
528
529 // Add all operands to the new PHI.
530 for (unsigned i = 1, e = PN.getNumIncomingValues(); i != e; ++i) {
531 Value *NewInVal = cast<Instruction>(PN.getIncomingValue(i))->getOperand(0);
532 if (NewInVal != InVal)
Craig Topperf40110f2014-04-25 05:29:35 +0000533 InVal = nullptr;
Chris Lattnerde1fede2010-01-05 05:31:55 +0000534 NewPN->addIncoming(NewInVal, PN.getIncomingBlock(i));
535 }
536
537 Value *PhiVal;
538 if (InVal) {
539 // The new PHI unions all of the same values together. This is really
540 // common, so we handle it intelligently here for compile-time speed.
541 PhiVal = InVal;
542 delete NewPN;
543 } else {
544 InsertNewInstBefore(NewPN, PN);
545 PhiVal = NewPN;
546 }
547
548 // Insert and return the new operation.
Eli Friedman35211c62011-05-27 00:19:40 +0000549 if (CastInst *FirstCI = dyn_cast<CastInst>(FirstInst)) {
550 CastInst *NewCI = CastInst::Create(FirstCI->getOpcode(), PhiVal,
551 PN.getType());
552 NewCI->setDebugLoc(FirstInst->getDebugLoc());
553 return NewCI;
554 }
Jim Grosbachbdbd7342013-04-05 21:20:12 +0000555
Chris Lattnera8fed472011-02-17 23:01:49 +0000556 if (BinaryOperator *BinOp = dyn_cast<BinaryOperator>(FirstInst)) {
557 BinOp = BinaryOperator::Create(BinOp->getOpcode(), PhiVal, ConstantOp);
Silviu Barangae985c762016-04-22 11:21:36 +0000558 BinOp->copyIRFlags(PN.getIncomingValue(0));
559
560 for (unsigned i = 1, e = PN.getNumIncomingValues(); i != e; ++i)
561 BinOp->andIRFlags(PN.getIncomingValue(i));
562
Eli Friedman35211c62011-05-27 00:19:40 +0000563 BinOp->setDebugLoc(FirstInst->getDebugLoc());
Chris Lattnera8fed472011-02-17 23:01:49 +0000564 return BinOp;
565 }
Jim Grosbachbdbd7342013-04-05 21:20:12 +0000566
Chris Lattnerde1fede2010-01-05 05:31:55 +0000567 CmpInst *CIOp = cast<CmpInst>(FirstInst);
Eli Friedman35211c62011-05-27 00:19:40 +0000568 CmpInst *NewCI = CmpInst::Create(CIOp->getOpcode(), CIOp->getPredicate(),
569 PhiVal, ConstantOp);
570 NewCI->setDebugLoc(FirstInst->getDebugLoc());
571 return NewCI;
Chris Lattnerde1fede2010-01-05 05:31:55 +0000572}
573
Sanjay Patel9b7e6772015-06-23 23:05:08 +0000574/// Return true if this PHI node is only used by a PHI node cycle that is dead.
Chris Lattnerde1fede2010-01-05 05:31:55 +0000575static bool DeadPHICycle(PHINode *PN,
Craig Topper71b7b682014-08-21 05:55:13 +0000576 SmallPtrSetImpl<PHINode*> &PotentiallyDeadPHIs) {
Chris Lattnerde1fede2010-01-05 05:31:55 +0000577 if (PN->use_empty()) return true;
578 if (!PN->hasOneUse()) return false;
579
580 // Remember this node, and if we find the cycle, return.
David Blaikie70573dc2014-11-19 07:49:26 +0000581 if (!PotentiallyDeadPHIs.insert(PN).second)
Chris Lattnerde1fede2010-01-05 05:31:55 +0000582 return true;
Jim Grosbachbdbd7342013-04-05 21:20:12 +0000583
Chris Lattnerde1fede2010-01-05 05:31:55 +0000584 // Don't scan crazily complex things.
585 if (PotentiallyDeadPHIs.size() == 16)
586 return false;
587
Chandler Carruthcdf47882014-03-09 03:16:01 +0000588 if (PHINode *PU = dyn_cast<PHINode>(PN->user_back()))
Chris Lattnerde1fede2010-01-05 05:31:55 +0000589 return DeadPHICycle(PU, PotentiallyDeadPHIs);
590
591 return false;
592}
593
Sanjay Patel9b7e6772015-06-23 23:05:08 +0000594/// Return true if this phi node is always equal to NonPhiInVal.
595/// This happens with mutually cyclic phi nodes like:
Chris Lattnerde1fede2010-01-05 05:31:55 +0000596/// z = some value; x = phi (y, z); y = phi (x, z)
Jim Grosbachbdbd7342013-04-05 21:20:12 +0000597static bool PHIsEqualValue(PHINode *PN, Value *NonPhiInVal,
Craig Topper71b7b682014-08-21 05:55:13 +0000598 SmallPtrSetImpl<PHINode*> &ValueEqualPHIs) {
Chris Lattnerde1fede2010-01-05 05:31:55 +0000599 // See if we already saw this PHI node.
David Blaikie70573dc2014-11-19 07:49:26 +0000600 if (!ValueEqualPHIs.insert(PN).second)
Chris Lattnerde1fede2010-01-05 05:31:55 +0000601 return true;
Jim Grosbachbdbd7342013-04-05 21:20:12 +0000602
Chris Lattnerde1fede2010-01-05 05:31:55 +0000603 // Don't scan crazily complex things.
604 if (ValueEqualPHIs.size() == 16)
605 return false;
Jim Grosbachbdbd7342013-04-05 21:20:12 +0000606
Chris Lattnerde1fede2010-01-05 05:31:55 +0000607 // Scan the operands to see if they are either phi nodes or are equal to
608 // the value.
Pete Cooper833f34d2015-05-12 20:05:31 +0000609 for (Value *Op : PN->incoming_values()) {
Chris Lattnerde1fede2010-01-05 05:31:55 +0000610 if (PHINode *OpPN = dyn_cast<PHINode>(Op)) {
611 if (!PHIsEqualValue(OpPN, NonPhiInVal, ValueEqualPHIs))
612 return false;
613 } else if (Op != NonPhiInVal)
614 return false;
615 }
Jim Grosbachbdbd7342013-04-05 21:20:12 +0000616
Chris Lattnerde1fede2010-01-05 05:31:55 +0000617 return true;
618}
619
Jun Bum Lim10e58e82016-02-11 16:46:13 +0000620/// Return an existing non-zero constant if this phi node has one, otherwise
621/// return constant 1.
Jun Bum Lim339e9722016-02-11 15:50:07 +0000622static ConstantInt *GetAnyNonZeroConstInt(PHINode &PN) {
623 assert(isa<IntegerType>(PN.getType()) && "Expect only intger type phi");
624 for (Value *V : PN.operands())
625 if (auto *ConstVA = dyn_cast<ConstantInt>(V))
626 if (!ConstVA->isZeroValue())
627 return ConstVA;
628 return ConstantInt::get(cast<IntegerType>(PN.getType()), 1);
629}
Chris Lattnerde1fede2010-01-05 05:31:55 +0000630
631namespace {
632struct PHIUsageRecord {
633 unsigned PHIId; // The ID # of the PHI (something determinstic to sort on)
634 unsigned Shift; // The amount shifted.
635 Instruction *Inst; // The trunc instruction.
Jim Grosbachbdbd7342013-04-05 21:20:12 +0000636
Chris Lattnerde1fede2010-01-05 05:31:55 +0000637 PHIUsageRecord(unsigned pn, unsigned Sh, Instruction *User)
638 : PHIId(pn), Shift(Sh), Inst(User) {}
Jim Grosbachbdbd7342013-04-05 21:20:12 +0000639
Chris Lattnerde1fede2010-01-05 05:31:55 +0000640 bool operator<(const PHIUsageRecord &RHS) const {
641 if (PHIId < RHS.PHIId) return true;
642 if (PHIId > RHS.PHIId) return false;
643 if (Shift < RHS.Shift) return true;
644 if (Shift > RHS.Shift) return false;
645 return Inst->getType()->getPrimitiveSizeInBits() <
646 RHS.Inst->getType()->getPrimitiveSizeInBits();
647 }
648};
Jim Grosbachbdbd7342013-04-05 21:20:12 +0000649
Chris Lattnerde1fede2010-01-05 05:31:55 +0000650struct LoweredPHIRecord {
651 PHINode *PN; // The PHI that was lowered.
652 unsigned Shift; // The amount shifted.
653 unsigned Width; // The width extracted.
Jim Grosbachbdbd7342013-04-05 21:20:12 +0000654
Chris Lattner229907c2011-07-18 04:54:35 +0000655 LoweredPHIRecord(PHINode *pn, unsigned Sh, Type *Ty)
Chris Lattnerde1fede2010-01-05 05:31:55 +0000656 : PN(pn), Shift(Sh), Width(Ty->getPrimitiveSizeInBits()) {}
Jim Grosbachbdbd7342013-04-05 21:20:12 +0000657
Chris Lattnerde1fede2010-01-05 05:31:55 +0000658 // Ctor form used by DenseMap.
659 LoweredPHIRecord(PHINode *pn, unsigned Sh)
660 : PN(pn), Shift(Sh), Width(0) {}
661};
Alexander Kornienkof00654e2015-06-23 09:49:53 +0000662}
Chris Lattnerde1fede2010-01-05 05:31:55 +0000663
664namespace llvm {
665 template<>
666 struct DenseMapInfo<LoweredPHIRecord> {
667 static inline LoweredPHIRecord getEmptyKey() {
Craig Topperf40110f2014-04-25 05:29:35 +0000668 return LoweredPHIRecord(nullptr, 0);
Chris Lattnerde1fede2010-01-05 05:31:55 +0000669 }
670 static inline LoweredPHIRecord getTombstoneKey() {
Craig Topperf40110f2014-04-25 05:29:35 +0000671 return LoweredPHIRecord(nullptr, 1);
Chris Lattnerde1fede2010-01-05 05:31:55 +0000672 }
673 static unsigned getHashValue(const LoweredPHIRecord &Val) {
674 return DenseMapInfo<PHINode*>::getHashValue(Val.PN) ^ (Val.Shift>>3) ^
675 (Val.Width>>3);
676 }
677 static bool isEqual(const LoweredPHIRecord &LHS,
678 const LoweredPHIRecord &RHS) {
679 return LHS.PN == RHS.PN && LHS.Shift == RHS.Shift &&
680 LHS.Width == RHS.Width;
681 }
682 };
Alexander Kornienkof00654e2015-06-23 09:49:53 +0000683}
Chris Lattnerde1fede2010-01-05 05:31:55 +0000684
685
Sanjay Patel9b7e6772015-06-23 23:05:08 +0000686/// This is an integer PHI and we know that it has an illegal type: see if it is
687/// only used by trunc or trunc(lshr) operations. If so, we split the PHI into
688/// the various pieces being extracted. This sort of thing is introduced when
689/// SROA promotes an aggregate to large integer values.
Chris Lattnerde1fede2010-01-05 05:31:55 +0000690///
691/// TODO: The user of the trunc may be an bitcast to float/double/vector or an
692/// inttoptr. We should produce new PHIs in the right type.
693///
694Instruction *InstCombiner::SliceUpIllegalIntegerPHI(PHINode &FirstPhi) {
695 // PHIUsers - Keep track of all of the truncated values extracted from a set
696 // of PHIs, along with their offset. These are the things we want to rewrite.
697 SmallVector<PHIUsageRecord, 16> PHIUsers;
Jim Grosbachbdbd7342013-04-05 21:20:12 +0000698
Chris Lattnerde1fede2010-01-05 05:31:55 +0000699 // PHIs are often mutually cyclic, so we keep track of a whole set of PHI
700 // nodes which are extracted from. PHIsToSlice is a set we use to avoid
701 // revisiting PHIs, PHIsInspected is a ordered list of PHIs that we need to
702 // check the uses of (to ensure they are all extracts).
703 SmallVector<PHINode*, 8> PHIsToSlice;
704 SmallPtrSet<PHINode*, 8> PHIsInspected;
Jim Grosbachbdbd7342013-04-05 21:20:12 +0000705
Chris Lattnerde1fede2010-01-05 05:31:55 +0000706 PHIsToSlice.push_back(&FirstPhi);
707 PHIsInspected.insert(&FirstPhi);
Jim Grosbachbdbd7342013-04-05 21:20:12 +0000708
Chris Lattnerde1fede2010-01-05 05:31:55 +0000709 for (unsigned PHIId = 0; PHIId != PHIsToSlice.size(); ++PHIId) {
710 PHINode *PN = PHIsToSlice[PHIId];
Jim Grosbachbdbd7342013-04-05 21:20:12 +0000711
Chris Lattnerde1fede2010-01-05 05:31:55 +0000712 // Scan the input list of the PHI. If any input is an invoke, and if the
713 // input is defined in the predecessor, then we won't be split the critical
714 // edge which is required to insert a truncate. Because of this, we have to
715 // bail out.
716 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) {
717 InvokeInst *II = dyn_cast<InvokeInst>(PN->getIncomingValue(i));
Craig Topperf40110f2014-04-25 05:29:35 +0000718 if (!II) continue;
Chris Lattnerde1fede2010-01-05 05:31:55 +0000719 if (II->getParent() != PN->getIncomingBlock(i))
720 continue;
Jim Grosbachbdbd7342013-04-05 21:20:12 +0000721
Chris Lattnerde1fede2010-01-05 05:31:55 +0000722 // If we have a phi, and if it's directly in the predecessor, then we have
723 // a critical edge where we need to put the truncate. Since we can't
724 // split the edge in instcombine, we have to bail out.
Craig Topperf40110f2014-04-25 05:29:35 +0000725 return nullptr;
Chris Lattnerde1fede2010-01-05 05:31:55 +0000726 }
Jim Grosbachbdbd7342013-04-05 21:20:12 +0000727
Chandler Carruthcdf47882014-03-09 03:16:01 +0000728 for (User *U : PN->users()) {
729 Instruction *UserI = cast<Instruction>(U);
Jim Grosbachbdbd7342013-04-05 21:20:12 +0000730
Chris Lattnerde1fede2010-01-05 05:31:55 +0000731 // If the user is a PHI, inspect its uses recursively.
Chandler Carruthcdf47882014-03-09 03:16:01 +0000732 if (PHINode *UserPN = dyn_cast<PHINode>(UserI)) {
David Blaikie70573dc2014-11-19 07:49:26 +0000733 if (PHIsInspected.insert(UserPN).second)
Chris Lattnerde1fede2010-01-05 05:31:55 +0000734 PHIsToSlice.push_back(UserPN);
735 continue;
736 }
Jim Grosbachbdbd7342013-04-05 21:20:12 +0000737
Chris Lattnerde1fede2010-01-05 05:31:55 +0000738 // Truncates are always ok.
Chandler Carruthcdf47882014-03-09 03:16:01 +0000739 if (isa<TruncInst>(UserI)) {
740 PHIUsers.push_back(PHIUsageRecord(PHIId, 0, UserI));
Chris Lattnerde1fede2010-01-05 05:31:55 +0000741 continue;
742 }
Jim Grosbachbdbd7342013-04-05 21:20:12 +0000743
Chris Lattnerde1fede2010-01-05 05:31:55 +0000744 // Otherwise it must be a lshr which can only be used by one trunc.
Chandler Carruthcdf47882014-03-09 03:16:01 +0000745 if (UserI->getOpcode() != Instruction::LShr ||
746 !UserI->hasOneUse() || !isa<TruncInst>(UserI->user_back()) ||
747 !isa<ConstantInt>(UserI->getOperand(1)))
Craig Topperf40110f2014-04-25 05:29:35 +0000748 return nullptr;
Jim Grosbachbdbd7342013-04-05 21:20:12 +0000749
Chandler Carruthcdf47882014-03-09 03:16:01 +0000750 unsigned Shift = cast<ConstantInt>(UserI->getOperand(1))->getZExtValue();
751 PHIUsers.push_back(PHIUsageRecord(PHIId, Shift, UserI->user_back()));
Chris Lattnerde1fede2010-01-05 05:31:55 +0000752 }
753 }
Jim Grosbachbdbd7342013-04-05 21:20:12 +0000754
Chris Lattnerde1fede2010-01-05 05:31:55 +0000755 // If we have no users, they must be all self uses, just nuke the PHI.
756 if (PHIUsers.empty())
Sanjay Patel4b198802016-02-01 22:23:39 +0000757 return replaceInstUsesWith(FirstPhi, UndefValue::get(FirstPhi.getType()));
Jim Grosbachbdbd7342013-04-05 21:20:12 +0000758
Chris Lattnerde1fede2010-01-05 05:31:55 +0000759 // If this phi node is transformable, create new PHIs for all the pieces
760 // extracted out of it. First, sort the users by their offset and size.
761 array_pod_sort(PHIUsers.begin(), PHIUsers.end());
Jim Grosbachbdbd7342013-04-05 21:20:12 +0000762
Matt Arsenaulte6db7602013-09-05 19:48:28 +0000763 DEBUG(dbgs() << "SLICING UP PHI: " << FirstPhi << '\n';
764 for (unsigned i = 1, e = PHIsToSlice.size(); i != e; ++i)
765 dbgs() << "AND USER PHI #" << i << ": " << *PHIsToSlice[i] << '\n';
766 );
Jim Grosbachbdbd7342013-04-05 21:20:12 +0000767
Chris Lattnerde1fede2010-01-05 05:31:55 +0000768 // PredValues - This is a temporary used when rewriting PHI nodes. It is
769 // hoisted out here to avoid construction/destruction thrashing.
770 DenseMap<BasicBlock*, Value*> PredValues;
Jim Grosbachbdbd7342013-04-05 21:20:12 +0000771
Chris Lattnerde1fede2010-01-05 05:31:55 +0000772 // ExtractedVals - Each new PHI we introduce is saved here so we don't
773 // introduce redundant PHIs.
774 DenseMap<LoweredPHIRecord, PHINode*> ExtractedVals;
Jim Grosbachbdbd7342013-04-05 21:20:12 +0000775
Chris Lattnerde1fede2010-01-05 05:31:55 +0000776 for (unsigned UserI = 0, UserE = PHIUsers.size(); UserI != UserE; ++UserI) {
777 unsigned PHIId = PHIUsers[UserI].PHIId;
778 PHINode *PN = PHIsToSlice[PHIId];
779 unsigned Offset = PHIUsers[UserI].Shift;
Chris Lattner229907c2011-07-18 04:54:35 +0000780 Type *Ty = PHIUsers[UserI].Inst->getType();
Jim Grosbachbdbd7342013-04-05 21:20:12 +0000781
Chris Lattnerde1fede2010-01-05 05:31:55 +0000782 PHINode *EltPHI;
Jim Grosbachbdbd7342013-04-05 21:20:12 +0000783
Chris Lattnerde1fede2010-01-05 05:31:55 +0000784 // If we've already lowered a user like this, reuse the previously lowered
785 // value.
Craig Topperf40110f2014-04-25 05:29:35 +0000786 if ((EltPHI = ExtractedVals[LoweredPHIRecord(PN, Offset, Ty)]) == nullptr) {
Jim Grosbachbdbd7342013-04-05 21:20:12 +0000787
Chris Lattnerde1fede2010-01-05 05:31:55 +0000788 // Otherwise, Create the new PHI node for this user.
Jay Foad52131342011-03-30 11:28:46 +0000789 EltPHI = PHINode::Create(Ty, PN->getNumIncomingValues(),
790 PN->getName()+".off"+Twine(Offset), PN);
Chris Lattnerde1fede2010-01-05 05:31:55 +0000791 assert(EltPHI->getType() != PN->getType() &&
792 "Truncate didn't shrink phi?");
Jim Grosbachbdbd7342013-04-05 21:20:12 +0000793
Chris Lattnerde1fede2010-01-05 05:31:55 +0000794 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) {
795 BasicBlock *Pred = PN->getIncomingBlock(i);
796 Value *&PredVal = PredValues[Pred];
Jim Grosbachbdbd7342013-04-05 21:20:12 +0000797
Chris Lattnerde1fede2010-01-05 05:31:55 +0000798 // If we already have a value for this predecessor, reuse it.
799 if (PredVal) {
800 EltPHI->addIncoming(PredVal, Pred);
801 continue;
802 }
803
804 // Handle the PHI self-reuse case.
805 Value *InVal = PN->getIncomingValue(i);
806 if (InVal == PN) {
807 PredVal = EltPHI;
808 EltPHI->addIncoming(PredVal, Pred);
809 continue;
810 }
Jim Grosbachbdbd7342013-04-05 21:20:12 +0000811
Chris Lattnerde1fede2010-01-05 05:31:55 +0000812 if (PHINode *InPHI = dyn_cast<PHINode>(PN)) {
813 // If the incoming value was a PHI, and if it was one of the PHIs we
814 // already rewrote it, just use the lowered value.
815 if (Value *Res = ExtractedVals[LoweredPHIRecord(InPHI, Offset, Ty)]) {
816 PredVal = Res;
817 EltPHI->addIncoming(PredVal, Pred);
818 continue;
819 }
820 }
Jim Grosbachbdbd7342013-04-05 21:20:12 +0000821
Chris Lattnerde1fede2010-01-05 05:31:55 +0000822 // Otherwise, do an extract in the predecessor.
Duncan P. N. Exon Smith9f8aaf22015-10-13 16:59:33 +0000823 Builder->SetInsertPoint(Pred->getTerminator());
Chris Lattnerde1fede2010-01-05 05:31:55 +0000824 Value *Res = InVal;
825 if (Offset)
826 Res = Builder->CreateLShr(Res, ConstantInt::get(InVal->getType(),
827 Offset), "extract");
828 Res = Builder->CreateTrunc(Res, Ty, "extract.t");
829 PredVal = Res;
830 EltPHI->addIncoming(Res, Pred);
Jim Grosbachbdbd7342013-04-05 21:20:12 +0000831
Chris Lattnerde1fede2010-01-05 05:31:55 +0000832 // If the incoming value was a PHI, and if it was one of the PHIs we are
833 // rewriting, we will ultimately delete the code we inserted. This
834 // means we need to revisit that PHI to make sure we extract out the
835 // needed piece.
836 if (PHINode *OldInVal = dyn_cast<PHINode>(PN->getIncomingValue(i)))
837 if (PHIsInspected.count(OldInVal)) {
838 unsigned RefPHIId = std::find(PHIsToSlice.begin(),PHIsToSlice.end(),
839 OldInVal)-PHIsToSlice.begin();
Jim Grosbachbdbd7342013-04-05 21:20:12 +0000840 PHIUsers.push_back(PHIUsageRecord(RefPHIId, Offset,
Chris Lattnerde1fede2010-01-05 05:31:55 +0000841 cast<Instruction>(Res)));
842 ++UserE;
843 }
844 }
845 PredValues.clear();
Jim Grosbachbdbd7342013-04-05 21:20:12 +0000846
Matt Arsenaulte6db7602013-09-05 19:48:28 +0000847 DEBUG(dbgs() << " Made element PHI for offset " << Offset << ": "
Chris Lattnerde1fede2010-01-05 05:31:55 +0000848 << *EltPHI << '\n');
849 ExtractedVals[LoweredPHIRecord(PN, Offset, Ty)] = EltPHI;
850 }
Jim Grosbachbdbd7342013-04-05 21:20:12 +0000851
Chris Lattnerde1fede2010-01-05 05:31:55 +0000852 // Replace the use of this piece with the PHI node.
Sanjay Patel4b198802016-02-01 22:23:39 +0000853 replaceInstUsesWith(*PHIUsers[UserI].Inst, EltPHI);
Chris Lattnerde1fede2010-01-05 05:31:55 +0000854 }
Jim Grosbachbdbd7342013-04-05 21:20:12 +0000855
Chris Lattnerde1fede2010-01-05 05:31:55 +0000856 // Replace all the remaining uses of the PHI nodes (self uses and the lshrs)
857 // with undefs.
858 Value *Undef = UndefValue::get(FirstPhi.getType());
859 for (unsigned i = 1, e = PHIsToSlice.size(); i != e; ++i)
Sanjay Patel4b198802016-02-01 22:23:39 +0000860 replaceInstUsesWith(*PHIsToSlice[i], Undef);
861 return replaceInstUsesWith(FirstPhi, Undef);
Chris Lattnerde1fede2010-01-05 05:31:55 +0000862}
863
864// PHINode simplification
865//
866Instruction *InstCombiner::visitPHINode(PHINode &PN) {
Chandler Carruth66b31302015-01-04 12:03:27 +0000867 if (Value *V = SimplifyInstruction(&PN, DL, TLI, DT, AC))
Sanjay Patel4b198802016-02-01 22:23:39 +0000868 return replaceInstUsesWith(PN, V);
Chris Lattnerde1fede2010-01-05 05:31:55 +0000869
Sanjay Patel95334072015-09-27 20:34:31 +0000870 if (Instruction *Result = FoldPHIArgZextsIntoPHI(PN))
871 return Result;
872
Chris Lattnerde1fede2010-01-05 05:31:55 +0000873 // If all PHI operands are the same operation, pull them through the PHI,
874 // reducing code size.
875 if (isa<Instruction>(PN.getIncomingValue(0)) &&
876 isa<Instruction>(PN.getIncomingValue(1)) &&
877 cast<Instruction>(PN.getIncomingValue(0))->getOpcode() ==
878 cast<Instruction>(PN.getIncomingValue(1))->getOpcode() &&
879 // FIXME: The hasOneUse check will fail for PHIs that use the value more
880 // than themselves more than once.
881 PN.getIncomingValue(0)->hasOneUse())
882 if (Instruction *Result = FoldPHIArgOpIntoPHI(PN))
883 return Result;
884
885 // If this is a trivial cycle in the PHI node graph, remove it. Basically, if
886 // this PHI only has a single use (a PHI), and if that PHI only has one use (a
887 // PHI)... break the cycle.
888 if (PN.hasOneUse()) {
Chandler Carruthcdf47882014-03-09 03:16:01 +0000889 Instruction *PHIUser = cast<Instruction>(PN.user_back());
Chris Lattnerde1fede2010-01-05 05:31:55 +0000890 if (PHINode *PU = dyn_cast<PHINode>(PHIUser)) {
891 SmallPtrSet<PHINode*, 16> PotentiallyDeadPHIs;
892 PotentiallyDeadPHIs.insert(&PN);
893 if (DeadPHICycle(PU, PotentiallyDeadPHIs))
Sanjay Patel4b198802016-02-01 22:23:39 +0000894 return replaceInstUsesWith(PN, UndefValue::get(PN.getType()));
Chris Lattnerde1fede2010-01-05 05:31:55 +0000895 }
Jim Grosbachbdbd7342013-04-05 21:20:12 +0000896
Chris Lattnerde1fede2010-01-05 05:31:55 +0000897 // If this phi has a single use, and if that use just computes a value for
898 // the next iteration of a loop, delete the phi. This occurs with unused
899 // induction variables, e.g. "for (int j = 0; ; ++j);". Detecting this
900 // common case here is good because the only other things that catch this
901 // are induction variable analysis (sometimes) and ADCE, which is only run
902 // late.
903 if (PHIUser->hasOneUse() &&
904 (isa<BinaryOperator>(PHIUser) || isa<GetElementPtrInst>(PHIUser)) &&
Chandler Carruthcdf47882014-03-09 03:16:01 +0000905 PHIUser->user_back() == &PN) {
Sanjay Patel4b198802016-02-01 22:23:39 +0000906 return replaceInstUsesWith(PN, UndefValue::get(PN.getType()));
Chris Lattnerde1fede2010-01-05 05:31:55 +0000907 }
Jun Bum Lim339e9722016-02-11 15:50:07 +0000908 // When a PHI is used only to be compared with zero, it is safe to replace
909 // an incoming value proved as known nonzero with any non-zero constant.
Jun Bum Lim10e58e82016-02-11 16:46:13 +0000910 // For example, in the code below, the incoming value %v can be replaced
911 // with any non-zero constant based on the fact that the PHI is only used to
912 // be compared with zero and %v is a known non-zero value:
Jun Bum Lim339e9722016-02-11 15:50:07 +0000913 // %v = select %cond, 1, 2
914 // %p = phi [%v, BB] ...
915 // icmp eq, %p, 0
916 auto *CmpInst = dyn_cast<ICmpInst>(PHIUser);
917 // FIXME: To be simple, handle only integer type for now.
918 if (CmpInst && isa<IntegerType>(PN.getType()) && CmpInst->isEquality() &&
919 match(CmpInst->getOperand(1), m_Zero())) {
920 ConstantInt *NonZeroConst = nullptr;
921 for (unsigned i = 0, e = PN.getNumIncomingValues(); i != e; ++i) {
922 Instruction *CtxI = PN.getIncomingBlock(i)->getTerminator();
923 Value *VA = PN.getIncomingValue(i);
924 if (isKnownNonZero(VA, DL, 0, AC, CtxI, DT)) {
925 if (!NonZeroConst)
926 NonZeroConst = GetAnyNonZeroConstInt(PN);
927 PN.setIncomingValue(i, NonZeroConst);
928 }
929 }
930 }
Chris Lattnerde1fede2010-01-05 05:31:55 +0000931 }
932
933 // We sometimes end up with phi cycles that non-obviously end up being the
934 // same value, for example:
935 // z = some value; x = phi (y, z); y = phi (x, z)
936 // where the phi nodes don't necessarily need to be in the same block. Do a
937 // quick check to see if the PHI node only contains a single non-phi value, if
938 // so, scan to see if the phi cycle is actually equal to that value.
939 {
Frits van Bommeld6d4f982011-04-16 14:32:34 +0000940 unsigned InValNo = 0, NumIncomingVals = PN.getNumIncomingValues();
Chris Lattnerde1fede2010-01-05 05:31:55 +0000941 // Scan for the first non-phi operand.
Frits van Bommeld6d4f982011-04-16 14:32:34 +0000942 while (InValNo != NumIncomingVals &&
Chris Lattnerde1fede2010-01-05 05:31:55 +0000943 isa<PHINode>(PN.getIncomingValue(InValNo)))
944 ++InValNo;
945
Frits van Bommeld6d4f982011-04-16 14:32:34 +0000946 if (InValNo != NumIncomingVals) {
Jay Foad7d03e9b2011-04-16 14:17:37 +0000947 Value *NonPhiInVal = PN.getIncomingValue(InValNo);
Jim Grosbachbdbd7342013-04-05 21:20:12 +0000948
Chris Lattnerde1fede2010-01-05 05:31:55 +0000949 // Scan the rest of the operands to see if there are any conflicts, if so
950 // there is no need to recursively scan other phis.
Frits van Bommeld6d4f982011-04-16 14:32:34 +0000951 for (++InValNo; InValNo != NumIncomingVals; ++InValNo) {
Chris Lattnerde1fede2010-01-05 05:31:55 +0000952 Value *OpVal = PN.getIncomingValue(InValNo);
953 if (OpVal != NonPhiInVal && !isa<PHINode>(OpVal))
954 break;
955 }
Jim Grosbachbdbd7342013-04-05 21:20:12 +0000956
Chris Lattnerde1fede2010-01-05 05:31:55 +0000957 // If we scanned over all operands, then we have one unique value plus
958 // phi values. Scan PHI nodes to see if they all merge in each other or
959 // the value.
Frits van Bommeld6d4f982011-04-16 14:32:34 +0000960 if (InValNo == NumIncomingVals) {
Chris Lattnerde1fede2010-01-05 05:31:55 +0000961 SmallPtrSet<PHINode*, 16> ValueEqualPHIs;
962 if (PHIsEqualValue(&PN, NonPhiInVal, ValueEqualPHIs))
Sanjay Patel4b198802016-02-01 22:23:39 +0000963 return replaceInstUsesWith(PN, NonPhiInVal);
Chris Lattnerde1fede2010-01-05 05:31:55 +0000964 }
965 }
966 }
967
968 // If there are multiple PHIs, sort their operands so that they all list
969 // the blocks in the same order. This will help identical PHIs be eliminated
970 // by other passes. Other passes shouldn't depend on this for correctness
971 // however.
972 PHINode *FirstPN = cast<PHINode>(PN.getParent()->begin());
973 if (&PN != FirstPN)
974 for (unsigned i = 0, e = FirstPN->getNumIncomingValues(); i != e; ++i) {
975 BasicBlock *BBA = PN.getIncomingBlock(i);
976 BasicBlock *BBB = FirstPN->getIncomingBlock(i);
977 if (BBA != BBB) {
978 Value *VA = PN.getIncomingValue(i);
979 unsigned j = PN.getBasicBlockIndex(BBB);
980 Value *VB = PN.getIncomingValue(j);
981 PN.setIncomingBlock(i, BBB);
982 PN.setIncomingValue(i, VB);
983 PN.setIncomingBlock(j, BBA);
984 PN.setIncomingValue(j, VA);
985 // NOTE: Instcombine normally would want us to "return &PN" if we
986 // modified any of the operands of an instruction. However, since we
987 // aren't adding or removing uses (just rearranging them) we don't do
988 // this in this case.
989 }
990 }
991
992 // If this is an integer PHI and we know that it has an illegal type, see if
993 // it is only used by trunc or trunc(lshr) operations. If so, we split the
994 // PHI into the various pieces being extracted. This sort of thing is
995 // introduced when SROA promotes an aggregate to a single large integer type.
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000996 if (PN.getType()->isIntegerTy() &&
997 !DL.isLegalInteger(PN.getType()->getPrimitiveSizeInBits()))
Chris Lattnerde1fede2010-01-05 05:31:55 +0000998 if (Instruction *Res = SliceUpIllegalIntegerPHI(PN))
999 return Res;
Jim Grosbachbdbd7342013-04-05 21:20:12 +00001000
Craig Topperf40110f2014-04-25 05:29:35 +00001001 return nullptr;
Benjamin Kramerf7cc6982010-01-05 13:32:48 +00001002}