1 //===- InstCombinePHI.cpp -------------------------------------------------===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
10 // This file implements the visitPHINode function.
12 //===----------------------------------------------------------------------===//
14 #include "InstCombine.h"
15 #include "llvm/Analysis/InstructionSimplify.h"
16 #include "llvm/Target/TargetData.h"
17 #include "llvm/ADT/SmallPtrSet.h"
18 #include "llvm/ADT/STLExtras.h"
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.
24 Instruction *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);
31 const Type *LHSType = LHSVal->getType();
32 const Type *RHSType = RHSVal->getType();
34 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();
43 // 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
49 I->getOperand(0)->getType() != LHSType ||
50 I->getOperand(1)->getType() != RHSType)
53 // If they are CmpInst instructions, check their predicates
54 if (CmpInst *CI = dyn_cast<CmpInst>(I))
55 if (CI->getPredicate() != cast<CmpInst>(FirstInst)->getPredicate())
59 isNUW = cast<OverflowingBinaryOperator>(I)->hasNoUnsignedWrap();
61 isNSW = cast<OverflowingBinaryOperator>(I)->hasNoSignedWrap();
63 isExact = cast<PossiblyExactOperator>(I)->isExact();
65 // 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;
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)
77 // Otherwise, this is safe to transform!
79 Value *InLHS = FirstInst->getOperand(0);
80 Value *InRHS = FirstInst->getOperand(1);
81 PHINode *NewLHS = 0, *NewRHS = 0;
83 NewLHS = PHINode::Create(LHSType,
84 FirstInst->getOperand(0)->getName() + ".pn");
85 NewLHS->reserveOperandSpace(PN.getNumOperands()/2);
86 NewLHS->addIncoming(InLHS, PN.getIncomingBlock(0));
87 InsertNewInstBefore(NewLHS, PN);
92 NewRHS = PHINode::Create(RHSType,
93 FirstInst->getOperand(1)->getName() + ".pn");
94 NewRHS->reserveOperandSpace(PN.getNumOperands()/2);
95 NewRHS->addIncoming(InRHS, PN.getIncomingBlock(0));
96 InsertNewInstBefore(NewRHS, PN);
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));
105 Value *NewInLHS = InInst->getOperand(0);
106 NewLHS->addIncoming(NewInLHS, PN.getIncomingBlock(i));
109 Value *NewInRHS = InInst->getOperand(1);
110 NewRHS->addIncoming(NewInRHS, PN.getIncomingBlock(i));
115 if (CmpInst *CIOp = dyn_cast<CmpInst>(FirstInst))
116 return CmpInst::Create(CIOp->getOpcode(), CIOp->getPredicate(),
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();
128 Instruction *InstCombiner::FoldPHIArgGEPIntoPHI(PHINode &PN) {
129 GetElementPtrInst *FirstInst =cast<GetElementPtrInst>(PN.getIncomingValue(0));
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
135 bool AllBasePointersAreAllocas = true;
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;
142 bool AllInBounds = true;
144 // 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())
151 AllInBounds &= GEP->isInBounds();
153 // 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;
159 // Compare the operand lists.
160 for (unsigned op = 0, e = FirstInst->getNumOperands(); op != e; ++op) {
161 if (FirstInst->getOperand(op) == GEP->getOperand(op))
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)))
173 if (FirstInst->getOperand(op)->getType() !=GEP->getOperand(op)->getType())
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
183 FixedOperands[op] = 0; // Needs a PHI.
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)
197 // Otherwise, this is safe to transform. Insert PHI nodes for each operand
199 SmallVector<PHINode*, 16> OperandPhis(FixedOperands.size());
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);
209 NewPN->reserveOperandSpace(e);
210 NewPN->addIncoming(FirstOp, PN.getIncomingBlock(0));
211 OperandPhis[i] = NewPN;
212 FixedOperands[i] = NewPN;
217 // Add all operands to the new PHIs.
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);
223 for (unsigned op = 0, e = OperandPhis.size(); op != e; ++op)
224 if (PHINode *OpPhi = OperandPhis[op])
225 OpPhi->addIncoming(InGEP->getOperand(op), InBB);
229 Value *Base = FixedOperands[0];
230 GetElementPtrInst *NewGEP =
231 GetElementPtrInst::Create(Base, FixedOperands.begin()+1,
232 FixedOperands.end());
233 if (AllInBounds) NewGEP->setIsInBounds();
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.
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
246 static bool isSafeAndProfitableToSinkLoad(LoadInst *L) {
247 BasicBlock::iterator BBI = L, E = L->getParent()->end();
249 for (++BBI; BBI != E; ++BBI)
250 if (BBI->mayWriteToMemory())
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();
260 if (isa<LoadInst>(U)) continue;
261 if (StoreInst *SI = dyn_cast<StoreInst>(U)) {
262 // If storing TO the alloca, then the address isn't taken.
263 if (SI->getOperand(1) == AI) continue;
265 isAddressTaken = true;
269 if (!isAddressTaken && AI->isStaticAlloca())
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())
286 Instruction *InstCombiner::FoldPHIArgLoadIntoPHI(PHINode &PN) {
287 LoadInst *FirstLI = cast<LoadInst>(PN.getIncomingValue(0));
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();
296 unsigned LoadAddrSpace = FirstLI->getPointerAddressSpace();
298 // We can't sink the load if the loaded value could be modified between the
300 if (FirstLI->getParent() != PN.getIncomingBlock(0) ||
301 !isSafeAndProfitableToSinkLoad(FirstLI))
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.
308 FirstLI->getParent()->getTerminator()->getNumSuccessors() != 1)
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())
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) ||
321 LI->getPointerAddressSpace() != LoadAddrSpace ||
322 !isSafeAndProfitableToSinkLoad(LI))
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))
330 LoadAlignment = std::min(LoadAlignment, LI->getAlignment());
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.
336 LI->getParent()->getTerminator()->getNumSuccessors() != 1)
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(),
344 NewPN->reserveOperandSpace(PN.getNumOperands()/2);
346 Value *InVal = FirstLI->getOperand(0);
347 NewPN->addIncoming(InVal, PN.getIncomingBlock(0));
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)
354 NewPN->addIncoming(NewInVal, PN.getIncomingBlock(i));
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.
364 InsertNewInstBefore(NewPN, PN);
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.
372 for (unsigned i = 0, e = PN.getNumIncomingValues(); i != e; ++i)
373 cast<LoadInst>(PN.getIncomingValue(i))->setVolatile(false);
375 return new LoadInst(PhiVal, "", isVolatile, LoadAlignment);
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.
383 Instruction *InstCombiner::FoldPHIArgOpIntoPHI(PHINode &PN) {
384 Instruction *FirstInst = cast<Instruction>(PN.getIncomingValue(0));
386 if (isa<GetElementPtrInst>(FirstInst))
387 return FoldPHIArgGEPIntoPHI(PN);
388 if (isa<LoadInst>(FirstInst))
389 return FoldPHIArgLoadIntoPHI(PN);
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;
397 bool isNUW = false, isNSW = false, isExact = false;
399 if (isa<CastInst>(FirstInst)) {
400 CastSrcTy = FirstInst->getOperand(0)->getType();
402 // Be careful about transforming integer PHIs. We don't want to pessimize
403 // the code by turning an i32 into an i1293.
404 if (PN.getType()->isIntegerTy() && CastSrcTy->isIntegerTy()) {
405 if (!ShouldChangeType(PN.getType(), CastSrcTy))
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));
413 return FoldPHIArgBinOpIntoPHI(PN);
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();
423 return 0; // Cannot fold this operation.
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))
432 if (I->getOperand(0)->getType() != CastSrcTy)
433 return 0; // Cast operation must match.
434 } else if (I->getOperand(1) != ConstantOp) {
439 isNUW = cast<OverflowingBinaryOperator>(I)->hasNoUnsignedWrap();
441 isNSW = cast<OverflowingBinaryOperator>(I)->hasNoSignedWrap();
443 isExact = cast<PossiblyExactOperator>(I)->isExact();
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(),
450 NewPN->reserveOperandSpace(PN.getNumOperands()/2);
452 Value *InVal = FirstInst->getOperand(0);
453 NewPN->addIncoming(InVal, PN.getIncomingBlock(0));
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)
460 NewPN->addIncoming(NewInVal, PN.getIncomingBlock(i));
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.
470 InsertNewInstBefore(NewPN, PN);
474 // Insert and return the new operation.
475 if (CastInst *FirstCI = dyn_cast<CastInst>(FirstInst))
476 return CastInst::Create(FirstCI->getOpcode(), PhiVal, PN.getType());
478 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();
486 CmpInst *CIOp = cast<CmpInst>(FirstInst);
487 return CmpInst::Create(CIOp->getOpcode(), CIOp->getPredicate(),
491 /// DeadPHICycle - Return true if this PHI node is only used by a PHI node cycle
493 static bool DeadPHICycle(PHINode *PN,
494 SmallPtrSet<PHINode*, 16> &PotentiallyDeadPHIs) {
495 if (PN->use_empty()) return true;
496 if (!PN->hasOneUse()) return false;
498 // Remember this node, and if we find the cycle, return.
499 if (!PotentiallyDeadPHIs.insert(PN))
502 // Don't scan crazily complex things.
503 if (PotentiallyDeadPHIs.size() == 16)
506 if (PHINode *PU = dyn_cast<PHINode>(PN->use_back()))
507 return DeadPHICycle(PU, PotentiallyDeadPHIs);
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)
515 static 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))
521 // Don't scan crazily complex things.
522 if (ValueEqualPHIs.size() == 16)
525 // Scan the operands to see if they are either phi nodes or are equal to
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))
532 } else if (Op != NonPhiInVal)
541 struct 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.
546 PHIUsageRecord(unsigned pn, unsigned Sh, Instruction *User)
547 : PHIId(pn), Shift(Sh), Inst(User) {}
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();
559 struct LoweredPHIRecord {
560 PHINode *PN; // The PHI that was lowered.
561 unsigned Shift; // The amount shifted.
562 unsigned Width; // The width extracted.
564 LoweredPHIRecord(PHINode *pn, unsigned Sh, const Type *Ty)
565 : PN(pn), Shift(Sh), Width(Ty->getPrimitiveSizeInBits()) {}
567 // Ctor form used by DenseMap.
568 LoweredPHIRecord(PHINode *pn, unsigned Sh)
569 : PN(pn), Shift(Sh), Width(0) {}
575 struct DenseMapInfo<LoweredPHIRecord> {
576 static inline LoweredPHIRecord getEmptyKey() {
577 return LoweredPHIRecord(0, 0);
579 static inline LoweredPHIRecord getTombstoneKey() {
580 return LoweredPHIRecord(0, 1);
582 static unsigned getHashValue(const LoweredPHIRecord &Val) {
583 return DenseMapInfo<PHINode*>::getHashValue(Val.PN) ^ (Val.Shift>>3) ^
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;
593 struct isPodLike<LoweredPHIRecord> { static const bool value = true; };
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.
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.
605 Instruction *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;
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;
617 PHIsToSlice.push_back(&FirstPhi);
618 PHIsInspected.insert(&FirstPhi);
620 for (unsigned PHIId = 0; PHIId != PHIsToSlice.size(); ++PHIId) {
621 PHINode *PN = PHIsToSlice[PHIId];
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
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))
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.
640 for (Value::use_iterator UI = PN->use_begin(), E = PN->use_end();
642 Instruction *User = cast<Instruction>(*UI);
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);
651 // Truncates are always ok.
652 if (isa<TruncInst>(User)) {
653 PHIUsers.push_back(PHIUsageRecord(PHIId, 0, User));
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)))
663 unsigned Shift = cast<ConstantInt>(User->getOperand(1))->getZExtValue();
664 PHIUsers.push_back(PHIUsageRecord(PHIId, Shift, User->use_back()));
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()));
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());
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';
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;
685 // ExtractedVals - Each new PHI we introduce is saved here so we don't
686 // introduce redundant PHIs.
687 DenseMap<LoweredPHIRecord, PHINode*> ExtractedVals;
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();
697 // If we've already lowered a user like this, reuse the previously lowered
699 if ((EltPHI = ExtractedVals[LoweredPHIRecord(PN, Offset, Ty)]) == 0) {
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?");
706 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) {
707 BasicBlock *Pred = PN->getIncomingBlock(i);
708 Value *&PredVal = PredValues[Pred];
710 // If we already have a value for this predecessor, reuse it.
712 EltPHI->addIncoming(PredVal, Pred);
716 // Handle the PHI self-reuse case.
717 Value *InVal = PN->getIncomingValue(i);
720 EltPHI->addIncoming(PredVal, Pred);
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)]) {
729 EltPHI->addIncoming(PredVal, Pred);
734 // Otherwise, do an extract in the predecessor.
735 Builder->SetInsertPoint(Pred, Pred->getTerminator());
738 Res = Builder->CreateLShr(Res, ConstantInt::get(InVal->getType(),
740 Res = Builder->CreateTrunc(Res, Ty, "extract.t");
742 EltPHI->addIncoming(Res, Pred);
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
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)));
759 DEBUG(errs() << " Made element PHI for offset " << Offset << ": "
761 ExtractedVals[LoweredPHIRecord(PN, Offset, Ty)] = EltPHI;
764 // Replace the use of this piece with the PHI node.
765 ReplaceInstUsesWith(*PHIUsers[UserI].Inst, EltPHI);
768 // Replace all the remaining uses of the PHI nodes (self uses and the lshrs)
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);
776 // PHINode simplification
778 Instruction *InstCombiner::visitPHINode(PHINode &PN) {
779 // If LCSSA is around, don't mess with Phi nodes
780 if (MustPreserveLCSSA) return 0;
782 if (Value *V = SimplifyInstruction(&PN, TD))
783 return ReplaceInstUsesWith(PN, V);
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))
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()));
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
815 if (PHIUser->hasOneUse() &&
816 (isa<BinaryOperator>(PHIUser) || isa<GetElementPtrInst>(PHIUser)) &&
817 PHIUser->use_back() == &PN) {
818 return ReplaceInstUsesWith(PN, UndefValue::get(PN.getType()));
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.
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)))
835 if (InValNo != NumOperandVals) {
836 Value *NonPhiInVal = PN.getOperand(InValNo);
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))
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
849 if (InValNo == NumOperandVals) {
850 SmallPtrSet<PHINode*, 16> ValueEqualPHIs;
851 if (PHIsEqualValue(&PN, NonPhiInVal, ValueEqualPHIs))
852 return ReplaceInstUsesWith(PN, NonPhiInVal);
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
861 PHINode *FirstPN = cast<PHINode>(PN.getParent()->begin());
863 for (unsigned i = 0, e = FirstPN->getNumIncomingValues(); i != e; ++i) {
864 BasicBlock *BBA = PN.getIncomingBlock(i);
865 BasicBlock *BBB = FirstPN->getIncomingBlock(i);
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.
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.
885 if (PN.getType()->isIntegerTy() && TD &&
886 !TD->isLegalInteger(PN.getType()->getPrimitiveSizeInBits()))
887 if (Instruction *Res = SliceUpIllegalIntegerPHI(PN))