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