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