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/Target/TargetData.h"
16 #include "llvm/ADT/SmallPtrSet.h"
17 #include "llvm/ADT/STLExtras.h"
20 /// FoldPHIArgBinOpIntoPHI - If we have something like phi [add (a,b), add(a,c)]
21 /// and if a/b/c and the add's all have a single use, turn this into a phi
22 /// and a single binop.
23 Instruction *InstCombiner::FoldPHIArgBinOpIntoPHI(PHINode &PN) {
24 Instruction *FirstInst = cast<Instruction>(PN.getIncomingValue(0));
25 assert(isa<BinaryOperator>(FirstInst) || isa<CmpInst>(FirstInst));
26 unsigned Opc = FirstInst->getOpcode();
27 Value *LHSVal = FirstInst->getOperand(0);
28 Value *RHSVal = FirstInst->getOperand(1);
30 const Type *LHSType = LHSVal->getType();
31 const Type *RHSType = RHSVal->getType();
33 // Scan to see if all operands are the same opcode, and all have one use.
34 for (unsigned i = 1; i != PN.getNumIncomingValues(); ++i) {
35 Instruction *I = dyn_cast<Instruction>(PN.getIncomingValue(i));
36 if (!I || I->getOpcode() != Opc || !I->hasOneUse() ||
37 // Verify type of the LHS matches so we don't fold cmp's of different
38 // types or GEP's with different index types.
39 I->getOperand(0)->getType() != LHSType ||
40 I->getOperand(1)->getType() != RHSType)
43 // If they are CmpInst instructions, check their predicates
44 if (Opc == Instruction::ICmp || Opc == Instruction::FCmp)
45 if (cast<CmpInst>(I)->getPredicate() !=
46 cast<CmpInst>(FirstInst)->getPredicate())
49 // Keep track of which operand needs a phi node.
50 if (I->getOperand(0) != LHSVal) LHSVal = 0;
51 if (I->getOperand(1) != RHSVal) RHSVal = 0;
54 // If both LHS and RHS would need a PHI, don't do this transformation,
55 // because it would increase the number of PHIs entering the block,
56 // which leads to higher register pressure. This is especially
57 // bad when the PHIs are in the header of a loop.
58 if (!LHSVal && !RHSVal)
61 // Otherwise, this is safe to transform!
63 Value *InLHS = FirstInst->getOperand(0);
64 Value *InRHS = FirstInst->getOperand(1);
65 PHINode *NewLHS = 0, *NewRHS = 0;
67 NewLHS = PHINode::Create(LHSType,
68 FirstInst->getOperand(0)->getName() + ".pn");
69 NewLHS->reserveOperandSpace(PN.getNumOperands()/2);
70 NewLHS->addIncoming(InLHS, PN.getIncomingBlock(0));
71 InsertNewInstBefore(NewLHS, PN);
76 NewRHS = PHINode::Create(RHSType,
77 FirstInst->getOperand(1)->getName() + ".pn");
78 NewRHS->reserveOperandSpace(PN.getNumOperands()/2);
79 NewRHS->addIncoming(InRHS, PN.getIncomingBlock(0));
80 InsertNewInstBefore(NewRHS, PN);
84 // Add all operands to the new PHIs.
85 if (NewLHS || NewRHS) {
86 for (unsigned i = 1, e = PN.getNumIncomingValues(); i != e; ++i) {
87 Instruction *InInst = cast<Instruction>(PN.getIncomingValue(i));
89 Value *NewInLHS = InInst->getOperand(0);
90 NewLHS->addIncoming(NewInLHS, PN.getIncomingBlock(i));
93 Value *NewInRHS = InInst->getOperand(1);
94 NewRHS->addIncoming(NewInRHS, PN.getIncomingBlock(i));
99 if (BinaryOperator *BinOp = dyn_cast<BinaryOperator>(FirstInst))
100 return BinaryOperator::Create(BinOp->getOpcode(), LHSVal, RHSVal);
101 CmpInst *CIOp = cast<CmpInst>(FirstInst);
102 return CmpInst::Create(CIOp->getOpcode(), CIOp->getPredicate(),
106 Instruction *InstCombiner::FoldPHIArgGEPIntoPHI(PHINode &PN) {
107 GetElementPtrInst *FirstInst =cast<GetElementPtrInst>(PN.getIncomingValue(0));
109 SmallVector<Value*, 16> FixedOperands(FirstInst->op_begin(),
110 FirstInst->op_end());
111 // This is true if all GEP bases are allocas and if all indices into them are
113 bool AllBasePointersAreAllocas = true;
115 // We don't want to replace this phi if the replacement would require
116 // more than one phi, which leads to higher register pressure. This is
117 // especially bad when the PHIs are in the header of a loop.
118 bool NeededPhi = false;
120 // Scan to see if all operands are the same opcode, and all have one use.
121 for (unsigned i = 1; i != PN.getNumIncomingValues(); ++i) {
122 GetElementPtrInst *GEP= dyn_cast<GetElementPtrInst>(PN.getIncomingValue(i));
123 if (!GEP || !GEP->hasOneUse() || GEP->getType() != FirstInst->getType() ||
124 GEP->getNumOperands() != FirstInst->getNumOperands())
127 // Keep track of whether or not all GEPs are of alloca pointers.
128 if (AllBasePointersAreAllocas &&
129 (!isa<AllocaInst>(GEP->getOperand(0)) ||
130 !GEP->hasAllConstantIndices()))
131 AllBasePointersAreAllocas = false;
133 // Compare the operand lists.
134 for (unsigned op = 0, e = FirstInst->getNumOperands(); op != e; ++op) {
135 if (FirstInst->getOperand(op) == GEP->getOperand(op))
138 // Don't merge two GEPs when two operands differ (introducing phi nodes)
139 // if one of the PHIs has a constant for the index. The index may be
140 // substantially cheaper to compute for the constants, so making it a
141 // variable index could pessimize the path. This also handles the case
142 // for struct indices, which must always be constant.
143 if (isa<ConstantInt>(FirstInst->getOperand(op)) ||
144 isa<ConstantInt>(GEP->getOperand(op)))
147 if (FirstInst->getOperand(op)->getType() !=GEP->getOperand(op)->getType())
150 // If we already needed a PHI for an earlier operand, and another operand
151 // also requires a PHI, we'd be introducing more PHIs than we're
152 // eliminating, which increases register pressure on entry to the PHI's
157 FixedOperands[op] = 0; // Needs a PHI.
162 // If all of the base pointers of the PHI'd GEPs are from allocas, don't
163 // bother doing this transformation. At best, this will just save a bit of
164 // offset calculation, but all the predecessors will have to materialize the
165 // stack address into a register anyway. We'd actually rather *clone* the
166 // load up into the predecessors so that we have a load of a gep of an alloca,
167 // which can usually all be folded into the load.
168 if (AllBasePointersAreAllocas)
171 // Otherwise, this is safe to transform. Insert PHI nodes for each operand
173 SmallVector<PHINode*, 16> OperandPhis(FixedOperands.size());
175 bool HasAnyPHIs = false;
176 for (unsigned i = 0, e = FixedOperands.size(); i != e; ++i) {
177 if (FixedOperands[i]) continue; // operand doesn't need a phi.
178 Value *FirstOp = FirstInst->getOperand(i);
179 PHINode *NewPN = PHINode::Create(FirstOp->getType(),
180 FirstOp->getName()+".pn");
181 InsertNewInstBefore(NewPN, PN);
183 NewPN->reserveOperandSpace(e);
184 NewPN->addIncoming(FirstOp, PN.getIncomingBlock(0));
185 OperandPhis[i] = NewPN;
186 FixedOperands[i] = NewPN;
191 // Add all operands to the new PHIs.
193 for (unsigned i = 1, e = PN.getNumIncomingValues(); i != e; ++i) {
194 GetElementPtrInst *InGEP =cast<GetElementPtrInst>(PN.getIncomingValue(i));
195 BasicBlock *InBB = PN.getIncomingBlock(i);
197 for (unsigned op = 0, e = OperandPhis.size(); op != e; ++op)
198 if (PHINode *OpPhi = OperandPhis[op])
199 OpPhi->addIncoming(InGEP->getOperand(op), InBB);
203 Value *Base = FixedOperands[0];
204 return cast<GEPOperator>(FirstInst)->isInBounds() ?
205 GetElementPtrInst::CreateInBounds(Base, FixedOperands.begin()+1,
206 FixedOperands.end()) :
207 GetElementPtrInst::Create(Base, FixedOperands.begin()+1,
208 FixedOperands.end());
212 /// isSafeAndProfitableToSinkLoad - Return true if we know that it is safe to
213 /// sink the load out of the block that defines it. This means that it must be
214 /// obvious the value of the load is not changed from the point of the load to
215 /// the end of the block it is in.
217 /// Finally, it is safe, but not profitable, to sink a load targetting a
218 /// non-address-taken alloca. Doing so will cause us to not promote the alloca
220 static bool isSafeAndProfitableToSinkLoad(LoadInst *L) {
221 BasicBlock::iterator BBI = L, E = L->getParent()->end();
223 for (++BBI; BBI != E; ++BBI)
224 if (BBI->mayWriteToMemory())
227 // Check for non-address taken alloca. If not address-taken already, it isn't
228 // profitable to do this xform.
229 if (AllocaInst *AI = dyn_cast<AllocaInst>(L->getOperand(0))) {
230 bool isAddressTaken = false;
231 for (Value::use_iterator UI = AI->use_begin(), E = AI->use_end();
233 if (isa<LoadInst>(UI)) continue;
234 if (StoreInst *SI = dyn_cast<StoreInst>(*UI)) {
235 // If storing TO the alloca, then the address isn't taken.
236 if (SI->getOperand(1) == AI) continue;
238 isAddressTaken = true;
242 if (!isAddressTaken && AI->isStaticAlloca())
246 // If this load is a load from a GEP with a constant offset from an alloca,
247 // then we don't want to sink it. In its present form, it will be
248 // load [constant stack offset]. Sinking it will cause us to have to
249 // materialize the stack addresses in each predecessor in a register only to
250 // do a shared load from register in the successor.
251 if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(L->getOperand(0)))
252 if (AllocaInst *AI = dyn_cast<AllocaInst>(GEP->getOperand(0)))
253 if (AI->isStaticAlloca() && GEP->hasAllConstantIndices())
259 Instruction *InstCombiner::FoldPHIArgLoadIntoPHI(PHINode &PN) {
260 LoadInst *FirstLI = cast<LoadInst>(PN.getIncomingValue(0));
262 // When processing loads, we need to propagate two bits of information to the
263 // sunk load: whether it is volatile, and what its alignment is. We currently
264 // don't sink loads when some have their alignment specified and some don't.
265 // visitLoadInst will propagate an alignment onto the load when TD is around,
266 // and if TD isn't around, we can't handle the mixed case.
267 bool isVolatile = FirstLI->isVolatile();
268 unsigned LoadAlignment = FirstLI->getAlignment();
270 // We can't sink the load if the loaded value could be modified between the
272 if (FirstLI->getParent() != PN.getIncomingBlock(0) ||
273 !isSafeAndProfitableToSinkLoad(FirstLI))
276 // If the PHI is of volatile loads and the load block has multiple
277 // successors, sinking it would remove a load of the volatile value from
278 // the path through the other successor.
280 FirstLI->getParent()->getTerminator()->getNumSuccessors() != 1)
283 // Check to see if all arguments are the same operation.
284 for (unsigned i = 1, e = PN.getNumIncomingValues(); i != e; ++i) {
285 LoadInst *LI = dyn_cast<LoadInst>(PN.getIncomingValue(i));
286 if (!LI || !LI->hasOneUse())
289 // We can't sink the load if the loaded value could be modified between
290 // the load and the PHI.
291 if (LI->isVolatile() != isVolatile ||
292 LI->getParent() != PN.getIncomingBlock(i) ||
293 !isSafeAndProfitableToSinkLoad(LI))
296 // If some of the loads have an alignment specified but not all of them,
297 // we can't do the transformation.
298 if ((LoadAlignment != 0) != (LI->getAlignment() != 0))
301 LoadAlignment = std::min(LoadAlignment, LI->getAlignment());
303 // If the PHI is of volatile loads and the load block has multiple
304 // successors, sinking it would remove a load of the volatile value from
305 // the path through the other successor.
307 LI->getParent()->getTerminator()->getNumSuccessors() != 1)
311 // Okay, they are all the same operation. Create a new PHI node of the
312 // correct type, and PHI together all of the LHS's of the instructions.
313 PHINode *NewPN = PHINode::Create(FirstLI->getOperand(0)->getType(),
315 NewPN->reserveOperandSpace(PN.getNumOperands()/2);
317 Value *InVal = FirstLI->getOperand(0);
318 NewPN->addIncoming(InVal, PN.getIncomingBlock(0));
320 // Add all operands to the new PHI.
321 for (unsigned i = 1, e = PN.getNumIncomingValues(); i != e; ++i) {
322 Value *NewInVal = cast<LoadInst>(PN.getIncomingValue(i))->getOperand(0);
323 if (NewInVal != InVal)
325 NewPN->addIncoming(NewInVal, PN.getIncomingBlock(i));
330 // The new PHI unions all of the same values together. This is really
331 // common, so we handle it intelligently here for compile-time speed.
335 InsertNewInstBefore(NewPN, PN);
339 // If this was a volatile load that we are merging, make sure to loop through
340 // and mark all the input loads as non-volatile. If we don't do this, we will
341 // insert a new volatile load and the old ones will not be deletable.
343 for (unsigned i = 0, e = PN.getNumIncomingValues(); i != e; ++i)
344 cast<LoadInst>(PN.getIncomingValue(i))->setVolatile(false);
346 return new LoadInst(PhiVal, "", isVolatile, LoadAlignment);
351 /// FoldPHIArgOpIntoPHI - If all operands to a PHI node are the same "unary"
352 /// operator and they all are only used by the PHI, PHI together their
353 /// inputs, and do the operation once, to the result of the PHI.
354 Instruction *InstCombiner::FoldPHIArgOpIntoPHI(PHINode &PN) {
355 Instruction *FirstInst = cast<Instruction>(PN.getIncomingValue(0));
357 if (isa<GetElementPtrInst>(FirstInst))
358 return FoldPHIArgGEPIntoPHI(PN);
359 if (isa<LoadInst>(FirstInst))
360 return FoldPHIArgLoadIntoPHI(PN);
362 // Scan the instruction, looking for input operations that can be folded away.
363 // If all input operands to the phi are the same instruction (e.g. a cast from
364 // the same type or "+42") we can pull the operation through the PHI, reducing
365 // code size and simplifying code.
366 Constant *ConstantOp = 0;
367 const Type *CastSrcTy = 0;
369 if (isa<CastInst>(FirstInst)) {
370 CastSrcTy = FirstInst->getOperand(0)->getType();
372 // Be careful about transforming integer PHIs. We don't want to pessimize
373 // the code by turning an i32 into an i1293.
374 if (isa<IntegerType>(PN.getType()) && isa<IntegerType>(CastSrcTy)) {
375 if (!ShouldChangeType(PN.getType(), CastSrcTy))
378 } else if (isa<BinaryOperator>(FirstInst) || isa<CmpInst>(FirstInst)) {
379 // Can fold binop, compare or shift here if the RHS is a constant,
380 // otherwise call FoldPHIArgBinOpIntoPHI.
381 ConstantOp = dyn_cast<Constant>(FirstInst->getOperand(1));
383 return FoldPHIArgBinOpIntoPHI(PN);
385 return 0; // Cannot fold this operation.
388 // Check to see if all arguments are the same operation.
389 for (unsigned i = 1, e = PN.getNumIncomingValues(); i != e; ++i) {
390 Instruction *I = dyn_cast<Instruction>(PN.getIncomingValue(i));
391 if (I == 0 || !I->hasOneUse() || !I->isSameOperationAs(FirstInst))
394 if (I->getOperand(0)->getType() != CastSrcTy)
395 return 0; // Cast operation must match.
396 } else if (I->getOperand(1) != ConstantOp) {
401 // Okay, they are all the same operation. Create a new PHI node of the
402 // correct type, and PHI together all of the LHS's of the instructions.
403 PHINode *NewPN = PHINode::Create(FirstInst->getOperand(0)->getType(),
405 NewPN->reserveOperandSpace(PN.getNumOperands()/2);
407 Value *InVal = FirstInst->getOperand(0);
408 NewPN->addIncoming(InVal, PN.getIncomingBlock(0));
410 // Add all operands to the new PHI.
411 for (unsigned i = 1, e = PN.getNumIncomingValues(); i != e; ++i) {
412 Value *NewInVal = cast<Instruction>(PN.getIncomingValue(i))->getOperand(0);
413 if (NewInVal != InVal)
415 NewPN->addIncoming(NewInVal, PN.getIncomingBlock(i));
420 // The new PHI unions all of the same values together. This is really
421 // common, so we handle it intelligently here for compile-time speed.
425 InsertNewInstBefore(NewPN, PN);
429 // Insert and return the new operation.
430 if (CastInst *FirstCI = dyn_cast<CastInst>(FirstInst))
431 return CastInst::Create(FirstCI->getOpcode(), PhiVal, PN.getType());
433 if (BinaryOperator *BinOp = dyn_cast<BinaryOperator>(FirstInst))
434 return BinaryOperator::Create(BinOp->getOpcode(), PhiVal, ConstantOp);
436 CmpInst *CIOp = cast<CmpInst>(FirstInst);
437 return CmpInst::Create(CIOp->getOpcode(), CIOp->getPredicate(),
441 /// DeadPHICycle - Return true if this PHI node is only used by a PHI node cycle
443 static bool DeadPHICycle(PHINode *PN,
444 SmallPtrSet<PHINode*, 16> &PotentiallyDeadPHIs) {
445 if (PN->use_empty()) return true;
446 if (!PN->hasOneUse()) return false;
448 // Remember this node, and if we find the cycle, return.
449 if (!PotentiallyDeadPHIs.insert(PN))
452 // Don't scan crazily complex things.
453 if (PotentiallyDeadPHIs.size() == 16)
456 if (PHINode *PU = dyn_cast<PHINode>(PN->use_back()))
457 return DeadPHICycle(PU, PotentiallyDeadPHIs);
462 /// PHIsEqualValue - Return true if this phi node is always equal to
463 /// NonPhiInVal. This happens with mutually cyclic phi nodes like:
464 /// z = some value; x = phi (y, z); y = phi (x, z)
465 static bool PHIsEqualValue(PHINode *PN, Value *NonPhiInVal,
466 SmallPtrSet<PHINode*, 16> &ValueEqualPHIs) {
467 // See if we already saw this PHI node.
468 if (!ValueEqualPHIs.insert(PN))
471 // Don't scan crazily complex things.
472 if (ValueEqualPHIs.size() == 16)
475 // Scan the operands to see if they are either phi nodes or are equal to
477 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) {
478 Value *Op = PN->getIncomingValue(i);
479 if (PHINode *OpPN = dyn_cast<PHINode>(Op)) {
480 if (!PHIsEqualValue(OpPN, NonPhiInVal, ValueEqualPHIs))
482 } else if (Op != NonPhiInVal)
491 struct PHIUsageRecord {
492 unsigned PHIId; // The ID # of the PHI (something determinstic to sort on)
493 unsigned Shift; // The amount shifted.
494 Instruction *Inst; // The trunc instruction.
496 PHIUsageRecord(unsigned pn, unsigned Sh, Instruction *User)
497 : PHIId(pn), Shift(Sh), Inst(User) {}
499 bool operator<(const PHIUsageRecord &RHS) const {
500 if (PHIId < RHS.PHIId) return true;
501 if (PHIId > RHS.PHIId) return false;
502 if (Shift < RHS.Shift) return true;
503 if (Shift > RHS.Shift) return false;
504 return Inst->getType()->getPrimitiveSizeInBits() <
505 RHS.Inst->getType()->getPrimitiveSizeInBits();
509 struct LoweredPHIRecord {
510 PHINode *PN; // The PHI that was lowered.
511 unsigned Shift; // The amount shifted.
512 unsigned Width; // The width extracted.
514 LoweredPHIRecord(PHINode *pn, unsigned Sh, const Type *Ty)
515 : PN(pn), Shift(Sh), Width(Ty->getPrimitiveSizeInBits()) {}
517 // Ctor form used by DenseMap.
518 LoweredPHIRecord(PHINode *pn, unsigned Sh)
519 : PN(pn), Shift(Sh), Width(0) {}
525 struct DenseMapInfo<LoweredPHIRecord> {
526 static inline LoweredPHIRecord getEmptyKey() {
527 return LoweredPHIRecord(0, 0);
529 static inline LoweredPHIRecord getTombstoneKey() {
530 return LoweredPHIRecord(0, 1);
532 static unsigned getHashValue(const LoweredPHIRecord &Val) {
533 return DenseMapInfo<PHINode*>::getHashValue(Val.PN) ^ (Val.Shift>>3) ^
536 static bool isEqual(const LoweredPHIRecord &LHS,
537 const LoweredPHIRecord &RHS) {
538 return LHS.PN == RHS.PN && LHS.Shift == RHS.Shift &&
539 LHS.Width == RHS.Width;
543 struct isPodLike<LoweredPHIRecord> { static const bool value = true; };
547 /// SliceUpIllegalIntegerPHI - This is an integer PHI and we know that it has an
548 /// illegal type: see if it is only used by trunc or trunc(lshr) operations. If
549 /// so, we split the PHI into the various pieces being extracted. This sort of
550 /// thing is introduced when SROA promotes an aggregate to large integer values.
552 /// TODO: The user of the trunc may be an bitcast to float/double/vector or an
553 /// inttoptr. We should produce new PHIs in the right type.
555 Instruction *InstCombiner::SliceUpIllegalIntegerPHI(PHINode &FirstPhi) {
556 // PHIUsers - Keep track of all of the truncated values extracted from a set
557 // of PHIs, along with their offset. These are the things we want to rewrite.
558 SmallVector<PHIUsageRecord, 16> PHIUsers;
560 // PHIs are often mutually cyclic, so we keep track of a whole set of PHI
561 // nodes which are extracted from. PHIsToSlice is a set we use to avoid
562 // revisiting PHIs, PHIsInspected is a ordered list of PHIs that we need to
563 // check the uses of (to ensure they are all extracts).
564 SmallVector<PHINode*, 8> PHIsToSlice;
565 SmallPtrSet<PHINode*, 8> PHIsInspected;
567 PHIsToSlice.push_back(&FirstPhi);
568 PHIsInspected.insert(&FirstPhi);
570 for (unsigned PHIId = 0; PHIId != PHIsToSlice.size(); ++PHIId) {
571 PHINode *PN = PHIsToSlice[PHIId];
573 // Scan the input list of the PHI. If any input is an invoke, and if the
574 // input is defined in the predecessor, then we won't be split the critical
575 // edge which is required to insert a truncate. Because of this, we have to
577 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) {
578 InvokeInst *II = dyn_cast<InvokeInst>(PN->getIncomingValue(i));
579 if (II == 0) continue;
580 if (II->getParent() != PN->getIncomingBlock(i))
583 // If we have a phi, and if it's directly in the predecessor, then we have
584 // a critical edge where we need to put the truncate. Since we can't
585 // split the edge in instcombine, we have to bail out.
590 for (Value::use_iterator UI = PN->use_begin(), E = PN->use_end();
592 Instruction *User = cast<Instruction>(*UI);
594 // If the user is a PHI, inspect its uses recursively.
595 if (PHINode *UserPN = dyn_cast<PHINode>(User)) {
596 if (PHIsInspected.insert(UserPN))
597 PHIsToSlice.push_back(UserPN);
601 // Truncates are always ok.
602 if (isa<TruncInst>(User)) {
603 PHIUsers.push_back(PHIUsageRecord(PHIId, 0, User));
607 // Otherwise it must be a lshr which can only be used by one trunc.
608 if (User->getOpcode() != Instruction::LShr ||
609 !User->hasOneUse() || !isa<TruncInst>(User->use_back()) ||
610 !isa<ConstantInt>(User->getOperand(1)))
613 unsigned Shift = cast<ConstantInt>(User->getOperand(1))->getZExtValue();
614 PHIUsers.push_back(PHIUsageRecord(PHIId, Shift, User->use_back()));
618 // If we have no users, they must be all self uses, just nuke the PHI.
619 if (PHIUsers.empty())
620 return ReplaceInstUsesWith(FirstPhi, UndefValue::get(FirstPhi.getType()));
622 // If this phi node is transformable, create new PHIs for all the pieces
623 // extracted out of it. First, sort the users by their offset and size.
624 array_pod_sort(PHIUsers.begin(), PHIUsers.end());
626 DEBUG(errs() << "SLICING UP PHI: " << FirstPhi << '\n';
627 for (unsigned i = 1, e = PHIsToSlice.size(); i != e; ++i)
628 errs() << "AND USER PHI #" << i << ": " << *PHIsToSlice[i] <<'\n';
631 // PredValues - This is a temporary used when rewriting PHI nodes. It is
632 // hoisted out here to avoid construction/destruction thrashing.
633 DenseMap<BasicBlock*, Value*> PredValues;
635 // ExtractedVals - Each new PHI we introduce is saved here so we don't
636 // introduce redundant PHIs.
637 DenseMap<LoweredPHIRecord, PHINode*> ExtractedVals;
639 for (unsigned UserI = 0, UserE = PHIUsers.size(); UserI != UserE; ++UserI) {
640 unsigned PHIId = PHIUsers[UserI].PHIId;
641 PHINode *PN = PHIsToSlice[PHIId];
642 unsigned Offset = PHIUsers[UserI].Shift;
643 const Type *Ty = PHIUsers[UserI].Inst->getType();
647 // If we've already lowered a user like this, reuse the previously lowered
649 if ((EltPHI = ExtractedVals[LoweredPHIRecord(PN, Offset, Ty)]) == 0) {
651 // Otherwise, Create the new PHI node for this user.
652 EltPHI = PHINode::Create(Ty, PN->getName()+".off"+Twine(Offset), PN);
653 assert(EltPHI->getType() != PN->getType() &&
654 "Truncate didn't shrink phi?");
656 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) {
657 BasicBlock *Pred = PN->getIncomingBlock(i);
658 Value *&PredVal = PredValues[Pred];
660 // If we already have a value for this predecessor, reuse it.
662 EltPHI->addIncoming(PredVal, Pred);
666 // Handle the PHI self-reuse case.
667 Value *InVal = PN->getIncomingValue(i);
670 EltPHI->addIncoming(PredVal, Pred);
674 if (PHINode *InPHI = dyn_cast<PHINode>(PN)) {
675 // If the incoming value was a PHI, and if it was one of the PHIs we
676 // already rewrote it, just use the lowered value.
677 if (Value *Res = ExtractedVals[LoweredPHIRecord(InPHI, Offset, Ty)]) {
679 EltPHI->addIncoming(PredVal, Pred);
684 // Otherwise, do an extract in the predecessor.
685 Builder->SetInsertPoint(Pred, Pred->getTerminator());
688 Res = Builder->CreateLShr(Res, ConstantInt::get(InVal->getType(),
690 Res = Builder->CreateTrunc(Res, Ty, "extract.t");
692 EltPHI->addIncoming(Res, Pred);
694 // If the incoming value was a PHI, and if it was one of the PHIs we are
695 // rewriting, we will ultimately delete the code we inserted. This
696 // means we need to revisit that PHI to make sure we extract out the
698 if (PHINode *OldInVal = dyn_cast<PHINode>(PN->getIncomingValue(i)))
699 if (PHIsInspected.count(OldInVal)) {
700 unsigned RefPHIId = std::find(PHIsToSlice.begin(),PHIsToSlice.end(),
701 OldInVal)-PHIsToSlice.begin();
702 PHIUsers.push_back(PHIUsageRecord(RefPHIId, Offset,
703 cast<Instruction>(Res)));
709 DEBUG(errs() << " Made element PHI for offset " << Offset << ": "
711 ExtractedVals[LoweredPHIRecord(PN, Offset, Ty)] = EltPHI;
714 // Replace the use of this piece with the PHI node.
715 ReplaceInstUsesWith(*PHIUsers[UserI].Inst, EltPHI);
718 // Replace all the remaining uses of the PHI nodes (self uses and the lshrs)
720 Value *Undef = UndefValue::get(FirstPhi.getType());
721 for (unsigned i = 1, e = PHIsToSlice.size(); i != e; ++i)
722 ReplaceInstUsesWith(*PHIsToSlice[i], Undef);
723 return ReplaceInstUsesWith(FirstPhi, Undef);
726 // PHINode simplification
728 Instruction *InstCombiner::visitPHINode(PHINode &PN) {
729 // If LCSSA is around, don't mess with Phi nodes
730 if (MustPreserveLCSSA) return 0;
732 if (Value *V = PN.hasConstantValue())
733 return ReplaceInstUsesWith(PN, V);
735 // If all PHI operands are the same operation, pull them through the PHI,
736 // reducing code size.
737 if (isa<Instruction>(PN.getIncomingValue(0)) &&
738 isa<Instruction>(PN.getIncomingValue(1)) &&
739 cast<Instruction>(PN.getIncomingValue(0))->getOpcode() ==
740 cast<Instruction>(PN.getIncomingValue(1))->getOpcode() &&
741 // FIXME: The hasOneUse check will fail for PHIs that use the value more
742 // than themselves more than once.
743 PN.getIncomingValue(0)->hasOneUse())
744 if (Instruction *Result = FoldPHIArgOpIntoPHI(PN))
747 // If this is a trivial cycle in the PHI node graph, remove it. Basically, if
748 // this PHI only has a single use (a PHI), and if that PHI only has one use (a
749 // PHI)... break the cycle.
750 if (PN.hasOneUse()) {
751 Instruction *PHIUser = cast<Instruction>(PN.use_back());
752 if (PHINode *PU = dyn_cast<PHINode>(PHIUser)) {
753 SmallPtrSet<PHINode*, 16> PotentiallyDeadPHIs;
754 PotentiallyDeadPHIs.insert(&PN);
755 if (DeadPHICycle(PU, PotentiallyDeadPHIs))
756 return ReplaceInstUsesWith(PN, UndefValue::get(PN.getType()));
759 // If this phi has a single use, and if that use just computes a value for
760 // the next iteration of a loop, delete the phi. This occurs with unused
761 // induction variables, e.g. "for (int j = 0; ; ++j);". Detecting this
762 // common case here is good because the only other things that catch this
763 // are induction variable analysis (sometimes) and ADCE, which is only run
765 if (PHIUser->hasOneUse() &&
766 (isa<BinaryOperator>(PHIUser) || isa<GetElementPtrInst>(PHIUser)) &&
767 PHIUser->use_back() == &PN) {
768 return ReplaceInstUsesWith(PN, UndefValue::get(PN.getType()));
772 // We sometimes end up with phi cycles that non-obviously end up being the
773 // same value, for example:
774 // z = some value; x = phi (y, z); y = phi (x, z)
775 // where the phi nodes don't necessarily need to be in the same block. Do a
776 // quick check to see if the PHI node only contains a single non-phi value, if
777 // so, scan to see if the phi cycle is actually equal to that value.
779 unsigned InValNo = 0, NumOperandVals = PN.getNumIncomingValues();
780 // Scan for the first non-phi operand.
781 while (InValNo != NumOperandVals &&
782 isa<PHINode>(PN.getIncomingValue(InValNo)))
785 if (InValNo != NumOperandVals) {
786 Value *NonPhiInVal = PN.getOperand(InValNo);
788 // Scan the rest of the operands to see if there are any conflicts, if so
789 // there is no need to recursively scan other phis.
790 for (++InValNo; InValNo != NumOperandVals; ++InValNo) {
791 Value *OpVal = PN.getIncomingValue(InValNo);
792 if (OpVal != NonPhiInVal && !isa<PHINode>(OpVal))
796 // If we scanned over all operands, then we have one unique value plus
797 // phi values. Scan PHI nodes to see if they all merge in each other or
799 if (InValNo == NumOperandVals) {
800 SmallPtrSet<PHINode*, 16> ValueEqualPHIs;
801 if (PHIsEqualValue(&PN, NonPhiInVal, ValueEqualPHIs))
802 return ReplaceInstUsesWith(PN, NonPhiInVal);
807 // If there are multiple PHIs, sort their operands so that they all list
808 // the blocks in the same order. This will help identical PHIs be eliminated
809 // by other passes. Other passes shouldn't depend on this for correctness
811 PHINode *FirstPN = cast<PHINode>(PN.getParent()->begin());
813 for (unsigned i = 0, e = FirstPN->getNumIncomingValues(); i != e; ++i) {
814 BasicBlock *BBA = PN.getIncomingBlock(i);
815 BasicBlock *BBB = FirstPN->getIncomingBlock(i);
817 Value *VA = PN.getIncomingValue(i);
818 unsigned j = PN.getBasicBlockIndex(BBB);
819 Value *VB = PN.getIncomingValue(j);
820 PN.setIncomingBlock(i, BBB);
821 PN.setIncomingValue(i, VB);
822 PN.setIncomingBlock(j, BBA);
823 PN.setIncomingValue(j, VA);
824 // NOTE: Instcombine normally would want us to "return &PN" if we
825 // modified any of the operands of an instruction. However, since we
826 // aren't adding or removing uses (just rearranging them) we don't do
827 // this in this case.
831 // If this is an integer PHI and we know that it has an illegal type, see if
832 // it is only used by trunc or trunc(lshr) operations. If so, we split the
833 // PHI into the various pieces being extracted. This sort of thing is
834 // introduced when SROA promotes an aggregate to a single large integer type.
835 if (isa<IntegerType>(PN.getType()) && TD &&
836 !TD->isLegalInteger(PN.getType()->getPrimitiveSizeInBits()))
837 if (Instruction *Res = SliceUpIllegalIntegerPHI(PN))