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 "InstCombineInternal.h"
15 #include "llvm/ADT/STLExtras.h"
16 #include "llvm/ADT/SmallPtrSet.h"
17 #include "llvm/Analysis/InstructionSimplify.h"
20 #define DEBUG_TYPE "instcombine"
22 /// FoldPHIArgBinOpIntoPHI - If we have something like phi [add (a,b), add(a,c)]
23 /// and if a/b/c and the add's all have a single use, turn this into a phi
24 /// and a single binop.
25 Instruction *InstCombiner::FoldPHIArgBinOpIntoPHI(PHINode &PN) {
26 Instruction *FirstInst = cast<Instruction>(PN.getIncomingValue(0));
27 assert(isa<BinaryOperator>(FirstInst) || isa<CmpInst>(FirstInst));
28 unsigned Opc = FirstInst->getOpcode();
29 Value *LHSVal = FirstInst->getOperand(0);
30 Value *RHSVal = FirstInst->getOperand(1);
32 Type *LHSType = LHSVal->getType();
33 Type *RHSType = RHSVal->getType();
35 bool isNUW = false, isNSW = false, isExact = false;
36 if (OverflowingBinaryOperator *BO =
37 dyn_cast<OverflowingBinaryOperator>(FirstInst)) {
38 isNUW = BO->hasNoUnsignedWrap();
39 isNSW = BO->hasNoSignedWrap();
40 } else if (PossiblyExactOperator *PEO =
41 dyn_cast<PossiblyExactOperator>(FirstInst))
42 isExact = PEO->isExact();
44 // Scan to see if all operands are the same opcode, and all have one use.
45 for (unsigned i = 1; i != PN.getNumIncomingValues(); ++i) {
46 Instruction *I = dyn_cast<Instruction>(PN.getIncomingValue(i));
47 if (!I || I->getOpcode() != Opc || !I->hasOneUse() ||
48 // Verify type of the LHS matches so we don't fold cmp's of different
50 I->getOperand(0)->getType() != LHSType ||
51 I->getOperand(1)->getType() != RHSType)
54 // If they are CmpInst instructions, check their predicates
55 if (CmpInst *CI = dyn_cast<CmpInst>(I))
56 if (CI->getPredicate() != cast<CmpInst>(FirstInst)->getPredicate())
60 isNUW = cast<OverflowingBinaryOperator>(I)->hasNoUnsignedWrap();
62 isNSW = cast<OverflowingBinaryOperator>(I)->hasNoSignedWrap();
64 isExact = cast<PossiblyExactOperator>(I)->isExact();
66 // Keep track of which operand needs a phi node.
67 if (I->getOperand(0) != LHSVal) LHSVal = nullptr;
68 if (I->getOperand(1) != RHSVal) RHSVal = nullptr;
71 // If both LHS and RHS would need a PHI, don't do this transformation,
72 // because it would increase the number of PHIs entering the block,
73 // which leads to higher register pressure. This is especially
74 // bad when the PHIs are in the header of a loop.
75 if (!LHSVal && !RHSVal)
78 // Otherwise, this is safe to transform!
80 Value *InLHS = FirstInst->getOperand(0);
81 Value *InRHS = FirstInst->getOperand(1);
82 PHINode *NewLHS = nullptr, *NewRHS = nullptr;
84 NewLHS = PHINode::Create(LHSType, PN.getNumIncomingValues(),
85 FirstInst->getOperand(0)->getName() + ".pn");
86 NewLHS->addIncoming(InLHS, PN.getIncomingBlock(0));
87 InsertNewInstBefore(NewLHS, PN);
92 NewRHS = PHINode::Create(RHSType, PN.getNumIncomingValues(),
93 FirstInst->getOperand(1)->getName() + ".pn");
94 NewRHS->addIncoming(InRHS, PN.getIncomingBlock(0));
95 InsertNewInstBefore(NewRHS, PN);
99 // Add all operands to the new PHIs.
100 if (NewLHS || NewRHS) {
101 for (unsigned i = 1, e = PN.getNumIncomingValues(); i != e; ++i) {
102 Instruction *InInst = cast<Instruction>(PN.getIncomingValue(i));
104 Value *NewInLHS = InInst->getOperand(0);
105 NewLHS->addIncoming(NewInLHS, PN.getIncomingBlock(i));
108 Value *NewInRHS = InInst->getOperand(1);
109 NewRHS->addIncoming(NewInRHS, PN.getIncomingBlock(i));
114 if (CmpInst *CIOp = dyn_cast<CmpInst>(FirstInst)) {
115 CmpInst *NewCI = CmpInst::Create(CIOp->getOpcode(), CIOp->getPredicate(),
117 NewCI->setDebugLoc(FirstInst->getDebugLoc());
121 BinaryOperator *BinOp = cast<BinaryOperator>(FirstInst);
122 BinaryOperator *NewBinOp =
123 BinaryOperator::Create(BinOp->getOpcode(), LHSVal, RHSVal);
124 if (isNUW) NewBinOp->setHasNoUnsignedWrap();
125 if (isNSW) NewBinOp->setHasNoSignedWrap();
126 if (isExact) NewBinOp->setIsExact();
127 NewBinOp->setDebugLoc(FirstInst->getDebugLoc());
131 Instruction *InstCombiner::FoldPHIArgGEPIntoPHI(PHINode &PN) {
132 GetElementPtrInst *FirstInst =cast<GetElementPtrInst>(PN.getIncomingValue(0));
134 SmallVector<Value*, 16> FixedOperands(FirstInst->op_begin(),
135 FirstInst->op_end());
136 // This is true if all GEP bases are allocas and if all indices into them are
138 bool AllBasePointersAreAllocas = true;
140 // We don't want to replace this phi if the replacement would require
141 // more than one phi, which leads to higher register pressure. This is
142 // especially bad when the PHIs are in the header of a loop.
143 bool NeededPhi = false;
145 bool AllInBounds = true;
147 // Scan to see if all operands are the same opcode, and all have one use.
148 for (unsigned i = 1; i != PN.getNumIncomingValues(); ++i) {
149 GetElementPtrInst *GEP= dyn_cast<GetElementPtrInst>(PN.getIncomingValue(i));
150 if (!GEP || !GEP->hasOneUse() || GEP->getType() != FirstInst->getType() ||
151 GEP->getNumOperands() != FirstInst->getNumOperands())
154 AllInBounds &= GEP->isInBounds();
156 // Keep track of whether or not all GEPs are of alloca pointers.
157 if (AllBasePointersAreAllocas &&
158 (!isa<AllocaInst>(GEP->getOperand(0)) ||
159 !GEP->hasAllConstantIndices()))
160 AllBasePointersAreAllocas = false;
162 // Compare the operand lists.
163 for (unsigned op = 0, e = FirstInst->getNumOperands(); op != e; ++op) {
164 if (FirstInst->getOperand(op) == GEP->getOperand(op))
167 // Don't merge two GEPs when two operands differ (introducing phi nodes)
168 // if one of the PHIs has a constant for the index. The index may be
169 // substantially cheaper to compute for the constants, so making it a
170 // variable index could pessimize the path. This also handles the case
171 // for struct indices, which must always be constant.
172 if (isa<ConstantInt>(FirstInst->getOperand(op)) ||
173 isa<ConstantInt>(GEP->getOperand(op)))
176 if (FirstInst->getOperand(op)->getType() !=GEP->getOperand(op)->getType())
179 // If we already needed a PHI for an earlier operand, and another operand
180 // also requires a PHI, we'd be introducing more PHIs than we're
181 // eliminating, which increases register pressure on entry to the PHI's
186 FixedOperands[op] = nullptr; // Needs a PHI.
191 // If all of the base pointers of the PHI'd GEPs are from allocas, don't
192 // bother doing this transformation. At best, this will just save a bit of
193 // offset calculation, but all the predecessors will have to materialize the
194 // stack address into a register anyway. We'd actually rather *clone* the
195 // load up into the predecessors so that we have a load of a gep of an alloca,
196 // which can usually all be folded into the load.
197 if (AllBasePointersAreAllocas)
200 // Otherwise, this is safe to transform. Insert PHI nodes for each operand
202 SmallVector<PHINode*, 16> OperandPhis(FixedOperands.size());
204 bool HasAnyPHIs = false;
205 for (unsigned i = 0, e = FixedOperands.size(); i != e; ++i) {
206 if (FixedOperands[i]) continue; // operand doesn't need a phi.
207 Value *FirstOp = FirstInst->getOperand(i);
208 PHINode *NewPN = PHINode::Create(FirstOp->getType(), e,
209 FirstOp->getName()+".pn");
210 InsertNewInstBefore(NewPN, PN);
212 NewPN->addIncoming(FirstOp, PN.getIncomingBlock(0));
213 OperandPhis[i] = NewPN;
214 FixedOperands[i] = NewPN;
219 // Add all operands to the new PHIs.
221 for (unsigned i = 1, e = PN.getNumIncomingValues(); i != e; ++i) {
222 GetElementPtrInst *InGEP =cast<GetElementPtrInst>(PN.getIncomingValue(i));
223 BasicBlock *InBB = PN.getIncomingBlock(i);
225 for (unsigned op = 0, e = OperandPhis.size(); op != e; ++op)
226 if (PHINode *OpPhi = OperandPhis[op])
227 OpPhi->addIncoming(InGEP->getOperand(op), InBB);
231 Value *Base = FixedOperands[0];
232 GetElementPtrInst *NewGEP =
233 GetElementPtrInst::Create(FirstInst->getSourceElementType(), Base,
234 makeArrayRef(FixedOperands).slice(1));
235 if (AllInBounds) NewGEP->setIsInBounds();
236 NewGEP->setDebugLoc(FirstInst->getDebugLoc());
241 /// isSafeAndProfitableToSinkLoad - Return true if we know that it is safe to
242 /// sink the load out of the block that defines it. This means that it must be
243 /// obvious the value of the load is not changed from the point of the load to
244 /// the end of the block it is in.
246 /// Finally, it is safe, but not profitable, to sink a load targeting a
247 /// non-address-taken alloca. Doing so will cause us to not promote the alloca
249 static bool isSafeAndProfitableToSinkLoad(LoadInst *L) {
250 BasicBlock::iterator BBI = L, E = L->getParent()->end();
252 for (++BBI; BBI != E; ++BBI)
253 if (BBI->mayWriteToMemory())
256 // Check for non-address taken alloca. If not address-taken already, it isn't
257 // profitable to do this xform.
258 if (AllocaInst *AI = dyn_cast<AllocaInst>(L->getOperand(0))) {
259 bool isAddressTaken = false;
260 for (User *U : AI->users()) {
261 if (isa<LoadInst>(U)) continue;
262 if (StoreInst *SI = dyn_cast<StoreInst>(U)) {
263 // If storing TO the alloca, then the address isn't taken.
264 if (SI->getOperand(1) == AI) continue;
266 isAddressTaken = true;
270 if (!isAddressTaken && AI->isStaticAlloca())
274 // If this load is a load from a GEP with a constant offset from an alloca,
275 // then we don't want to sink it. In its present form, it will be
276 // load [constant stack offset]. Sinking it will cause us to have to
277 // materialize the stack addresses in each predecessor in a register only to
278 // do a shared load from register in the successor.
279 if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(L->getOperand(0)))
280 if (AllocaInst *AI = dyn_cast<AllocaInst>(GEP->getOperand(0)))
281 if (AI->isStaticAlloca() && GEP->hasAllConstantIndices())
287 Instruction *InstCombiner::FoldPHIArgLoadIntoPHI(PHINode &PN) {
288 LoadInst *FirstLI = cast<LoadInst>(PN.getIncomingValue(0));
290 // FIXME: This is overconservative; this transform is allowed in some cases
291 // for atomic operations.
292 if (FirstLI->isAtomic())
295 // When processing loads, we need to propagate two bits of information to the
296 // sunk load: whether it is volatile, and what its alignment is. We currently
297 // don't sink loads when some have their alignment specified and some don't.
298 // visitLoadInst will propagate an alignment onto the load when TD is around,
299 // and if TD isn't around, we can't handle the mixed case.
300 bool isVolatile = FirstLI->isVolatile();
301 unsigned LoadAlignment = FirstLI->getAlignment();
302 unsigned LoadAddrSpace = FirstLI->getPointerAddressSpace();
304 // We can't sink the load if the loaded value could be modified between the
306 if (FirstLI->getParent() != PN.getIncomingBlock(0) ||
307 !isSafeAndProfitableToSinkLoad(FirstLI))
310 // If the PHI is of volatile loads and the load block has multiple
311 // successors, sinking it would remove a load of the volatile value from
312 // the path through the other successor.
314 FirstLI->getParent()->getTerminator()->getNumSuccessors() != 1)
317 // Check to see if all arguments are the same operation.
318 for (unsigned i = 1, e = PN.getNumIncomingValues(); i != e; ++i) {
319 LoadInst *LI = dyn_cast<LoadInst>(PN.getIncomingValue(i));
320 if (!LI || !LI->hasOneUse())
323 // We can't sink the load if the loaded value could be modified between
324 // the load and the PHI.
325 if (LI->isVolatile() != isVolatile ||
326 LI->getParent() != PN.getIncomingBlock(i) ||
327 LI->getPointerAddressSpace() != LoadAddrSpace ||
328 !isSafeAndProfitableToSinkLoad(LI))
331 // If some of the loads have an alignment specified but not all of them,
332 // we can't do the transformation.
333 if ((LoadAlignment != 0) != (LI->getAlignment() != 0))
336 LoadAlignment = std::min(LoadAlignment, LI->getAlignment());
338 // If the PHI is of volatile loads and the load block has multiple
339 // successors, sinking it would remove a load of the volatile value from
340 // the path through the other successor.
342 LI->getParent()->getTerminator()->getNumSuccessors() != 1)
346 // Okay, they are all the same operation. Create a new PHI node of the
347 // correct type, and PHI together all of the LHS's of the instructions.
348 PHINode *NewPN = PHINode::Create(FirstLI->getOperand(0)->getType(),
349 PN.getNumIncomingValues(),
352 Value *InVal = FirstLI->getOperand(0);
353 NewPN->addIncoming(InVal, PN.getIncomingBlock(0));
355 // Add all operands to the new PHI.
356 for (unsigned i = 1, e = PN.getNumIncomingValues(); i != e; ++i) {
357 Value *NewInVal = cast<LoadInst>(PN.getIncomingValue(i))->getOperand(0);
358 if (NewInVal != InVal)
360 NewPN->addIncoming(NewInVal, PN.getIncomingBlock(i));
365 // The new PHI unions all of the same values together. This is really
366 // common, so we handle it intelligently here for compile-time speed.
370 InsertNewInstBefore(NewPN, PN);
374 // If this was a volatile load that we are merging, make sure to loop through
375 // and mark all the input loads as non-volatile. If we don't do this, we will
376 // insert a new volatile load and the old ones will not be deletable.
378 for (Value *IncValue : PN.incoming_values())
379 cast<LoadInst>(IncValue)->setVolatile(false);
381 LoadInst *NewLI = new LoadInst(PhiVal, "", isVolatile, LoadAlignment);
382 NewLI->setDebugLoc(FirstLI->getDebugLoc());
388 /// FoldPHIArgOpIntoPHI - If all operands to a PHI node are the same "unary"
389 /// operator and they all are only used by the PHI, PHI together their
390 /// inputs, and do the operation once, to the result of the PHI.
391 Instruction *InstCombiner::FoldPHIArgOpIntoPHI(PHINode &PN) {
392 Instruction *FirstInst = cast<Instruction>(PN.getIncomingValue(0));
394 if (isa<GetElementPtrInst>(FirstInst))
395 return FoldPHIArgGEPIntoPHI(PN);
396 if (isa<LoadInst>(FirstInst))
397 return FoldPHIArgLoadIntoPHI(PN);
399 // Scan the instruction, looking for input operations that can be folded away.
400 // If all input operands to the phi are the same instruction (e.g. a cast from
401 // the same type or "+42") we can pull the operation through the PHI, reducing
402 // code size and simplifying code.
403 Constant *ConstantOp = nullptr;
404 Type *CastSrcTy = nullptr;
405 bool isNUW = false, isNSW = false, isExact = false;
407 if (isa<CastInst>(FirstInst)) {
408 CastSrcTy = FirstInst->getOperand(0)->getType();
410 // Be careful about transforming integer PHIs. We don't want to pessimize
411 // the code by turning an i32 into an i1293.
412 if (PN.getType()->isIntegerTy() && CastSrcTy->isIntegerTy()) {
413 if (!ShouldChangeType(PN.getType(), CastSrcTy))
416 } else if (isa<BinaryOperator>(FirstInst) || isa<CmpInst>(FirstInst)) {
417 // Can fold binop, compare or shift here if the RHS is a constant,
418 // otherwise call FoldPHIArgBinOpIntoPHI.
419 ConstantOp = dyn_cast<Constant>(FirstInst->getOperand(1));
421 return FoldPHIArgBinOpIntoPHI(PN);
423 if (OverflowingBinaryOperator *BO =
424 dyn_cast<OverflowingBinaryOperator>(FirstInst)) {
425 isNUW = BO->hasNoUnsignedWrap();
426 isNSW = BO->hasNoSignedWrap();
427 } else if (PossiblyExactOperator *PEO =
428 dyn_cast<PossiblyExactOperator>(FirstInst))
429 isExact = PEO->isExact();
431 return nullptr; // Cannot fold this operation.
434 // Check to see if all arguments are the same operation.
435 for (unsigned i = 1, e = PN.getNumIncomingValues(); i != e; ++i) {
436 Instruction *I = dyn_cast<Instruction>(PN.getIncomingValue(i));
437 if (!I || !I->hasOneUse() || !I->isSameOperationAs(FirstInst))
440 if (I->getOperand(0)->getType() != CastSrcTy)
441 return nullptr; // Cast operation must match.
442 } else if (I->getOperand(1) != ConstantOp) {
447 isNUW = cast<OverflowingBinaryOperator>(I)->hasNoUnsignedWrap();
449 isNSW = cast<OverflowingBinaryOperator>(I)->hasNoSignedWrap();
451 isExact = cast<PossiblyExactOperator>(I)->isExact();
454 // Okay, they are all the same operation. Create a new PHI node of the
455 // correct type, and PHI together all of the LHS's of the instructions.
456 PHINode *NewPN = PHINode::Create(FirstInst->getOperand(0)->getType(),
457 PN.getNumIncomingValues(),
460 Value *InVal = FirstInst->getOperand(0);
461 NewPN->addIncoming(InVal, PN.getIncomingBlock(0));
463 // Add all operands to the new PHI.
464 for (unsigned i = 1, e = PN.getNumIncomingValues(); i != e; ++i) {
465 Value *NewInVal = cast<Instruction>(PN.getIncomingValue(i))->getOperand(0);
466 if (NewInVal != InVal)
468 NewPN->addIncoming(NewInVal, PN.getIncomingBlock(i));
473 // The new PHI unions all of the same values together. This is really
474 // common, so we handle it intelligently here for compile-time speed.
478 InsertNewInstBefore(NewPN, PN);
482 // Insert and return the new operation.
483 if (CastInst *FirstCI = dyn_cast<CastInst>(FirstInst)) {
484 CastInst *NewCI = CastInst::Create(FirstCI->getOpcode(), PhiVal,
486 NewCI->setDebugLoc(FirstInst->getDebugLoc());
490 if (BinaryOperator *BinOp = dyn_cast<BinaryOperator>(FirstInst)) {
491 BinOp = BinaryOperator::Create(BinOp->getOpcode(), PhiVal, ConstantOp);
492 if (isNUW) BinOp->setHasNoUnsignedWrap();
493 if (isNSW) BinOp->setHasNoSignedWrap();
494 if (isExact) BinOp->setIsExact();
495 BinOp->setDebugLoc(FirstInst->getDebugLoc());
499 CmpInst *CIOp = cast<CmpInst>(FirstInst);
500 CmpInst *NewCI = CmpInst::Create(CIOp->getOpcode(), CIOp->getPredicate(),
502 NewCI->setDebugLoc(FirstInst->getDebugLoc());
506 /// DeadPHICycle - Return true if this PHI node is only used by a PHI node cycle
508 static bool DeadPHICycle(PHINode *PN,
509 SmallPtrSetImpl<PHINode*> &PotentiallyDeadPHIs) {
510 if (PN->use_empty()) return true;
511 if (!PN->hasOneUse()) return false;
513 // Remember this node, and if we find the cycle, return.
514 if (!PotentiallyDeadPHIs.insert(PN).second)
517 // Don't scan crazily complex things.
518 if (PotentiallyDeadPHIs.size() == 16)
521 if (PHINode *PU = dyn_cast<PHINode>(PN->user_back()))
522 return DeadPHICycle(PU, PotentiallyDeadPHIs);
527 /// PHIsEqualValue - Return true if this phi node is always equal to
528 /// NonPhiInVal. This happens with mutually cyclic phi nodes like:
529 /// z = some value; x = phi (y, z); y = phi (x, z)
530 static bool PHIsEqualValue(PHINode *PN, Value *NonPhiInVal,
531 SmallPtrSetImpl<PHINode*> &ValueEqualPHIs) {
532 // See if we already saw this PHI node.
533 if (!ValueEqualPHIs.insert(PN).second)
536 // Don't scan crazily complex things.
537 if (ValueEqualPHIs.size() == 16)
540 // Scan the operands to see if they are either phi nodes or are equal to
542 for (Value *Op : PN->incoming_values()) {
543 if (PHINode *OpPN = dyn_cast<PHINode>(Op)) {
544 if (!PHIsEqualValue(OpPN, NonPhiInVal, ValueEqualPHIs))
546 } else if (Op != NonPhiInVal)
555 struct PHIUsageRecord {
556 unsigned PHIId; // The ID # of the PHI (something determinstic to sort on)
557 unsigned Shift; // The amount shifted.
558 Instruction *Inst; // The trunc instruction.
560 PHIUsageRecord(unsigned pn, unsigned Sh, Instruction *User)
561 : PHIId(pn), Shift(Sh), Inst(User) {}
563 bool operator<(const PHIUsageRecord &RHS) const {
564 if (PHIId < RHS.PHIId) return true;
565 if (PHIId > RHS.PHIId) return false;
566 if (Shift < RHS.Shift) return true;
567 if (Shift > RHS.Shift) return false;
568 return Inst->getType()->getPrimitiveSizeInBits() <
569 RHS.Inst->getType()->getPrimitiveSizeInBits();
573 struct LoweredPHIRecord {
574 PHINode *PN; // The PHI that was lowered.
575 unsigned Shift; // The amount shifted.
576 unsigned Width; // The width extracted.
578 LoweredPHIRecord(PHINode *pn, unsigned Sh, Type *Ty)
579 : PN(pn), Shift(Sh), Width(Ty->getPrimitiveSizeInBits()) {}
581 // Ctor form used by DenseMap.
582 LoweredPHIRecord(PHINode *pn, unsigned Sh)
583 : PN(pn), Shift(Sh), Width(0) {}
589 struct DenseMapInfo<LoweredPHIRecord> {
590 static inline LoweredPHIRecord getEmptyKey() {
591 return LoweredPHIRecord(nullptr, 0);
593 static inline LoweredPHIRecord getTombstoneKey() {
594 return LoweredPHIRecord(nullptr, 1);
596 static unsigned getHashValue(const LoweredPHIRecord &Val) {
597 return DenseMapInfo<PHINode*>::getHashValue(Val.PN) ^ (Val.Shift>>3) ^
600 static bool isEqual(const LoweredPHIRecord &LHS,
601 const LoweredPHIRecord &RHS) {
602 return LHS.PN == RHS.PN && LHS.Shift == RHS.Shift &&
603 LHS.Width == RHS.Width;
609 /// SliceUpIllegalIntegerPHI - This is an integer PHI and we know that it has an
610 /// illegal type: see if it is only used by trunc or trunc(lshr) operations. If
611 /// so, we split the PHI into the various pieces being extracted. This sort of
612 /// thing is introduced when SROA promotes an aggregate to large integer values.
614 /// TODO: The user of the trunc may be an bitcast to float/double/vector or an
615 /// inttoptr. We should produce new PHIs in the right type.
617 Instruction *InstCombiner::SliceUpIllegalIntegerPHI(PHINode &FirstPhi) {
618 // PHIUsers - Keep track of all of the truncated values extracted from a set
619 // of PHIs, along with their offset. These are the things we want to rewrite.
620 SmallVector<PHIUsageRecord, 16> PHIUsers;
622 // PHIs are often mutually cyclic, so we keep track of a whole set of PHI
623 // nodes which are extracted from. PHIsToSlice is a set we use to avoid
624 // revisiting PHIs, PHIsInspected is a ordered list of PHIs that we need to
625 // check the uses of (to ensure they are all extracts).
626 SmallVector<PHINode*, 8> PHIsToSlice;
627 SmallPtrSet<PHINode*, 8> PHIsInspected;
629 PHIsToSlice.push_back(&FirstPhi);
630 PHIsInspected.insert(&FirstPhi);
632 for (unsigned PHIId = 0; PHIId != PHIsToSlice.size(); ++PHIId) {
633 PHINode *PN = PHIsToSlice[PHIId];
635 // Scan the input list of the PHI. If any input is an invoke, and if the
636 // input is defined in the predecessor, then we won't be split the critical
637 // edge which is required to insert a truncate. Because of this, we have to
639 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) {
640 InvokeInst *II = dyn_cast<InvokeInst>(PN->getIncomingValue(i));
642 if (II->getParent() != PN->getIncomingBlock(i))
645 // If we have a phi, and if it's directly in the predecessor, then we have
646 // a critical edge where we need to put the truncate. Since we can't
647 // split the edge in instcombine, we have to bail out.
651 for (User *U : PN->users()) {
652 Instruction *UserI = cast<Instruction>(U);
654 // If the user is a PHI, inspect its uses recursively.
655 if (PHINode *UserPN = dyn_cast<PHINode>(UserI)) {
656 if (PHIsInspected.insert(UserPN).second)
657 PHIsToSlice.push_back(UserPN);
661 // Truncates are always ok.
662 if (isa<TruncInst>(UserI)) {
663 PHIUsers.push_back(PHIUsageRecord(PHIId, 0, UserI));
667 // Otherwise it must be a lshr which can only be used by one trunc.
668 if (UserI->getOpcode() != Instruction::LShr ||
669 !UserI->hasOneUse() || !isa<TruncInst>(UserI->user_back()) ||
670 !isa<ConstantInt>(UserI->getOperand(1)))
673 unsigned Shift = cast<ConstantInt>(UserI->getOperand(1))->getZExtValue();
674 PHIUsers.push_back(PHIUsageRecord(PHIId, Shift, UserI->user_back()));
678 // If we have no users, they must be all self uses, just nuke the PHI.
679 if (PHIUsers.empty())
680 return ReplaceInstUsesWith(FirstPhi, UndefValue::get(FirstPhi.getType()));
682 // If this phi node is transformable, create new PHIs for all the pieces
683 // extracted out of it. First, sort the users by their offset and size.
684 array_pod_sort(PHIUsers.begin(), PHIUsers.end());
686 DEBUG(dbgs() << "SLICING UP PHI: " << FirstPhi << '\n';
687 for (unsigned i = 1, e = PHIsToSlice.size(); i != e; ++i)
688 dbgs() << "AND USER PHI #" << i << ": " << *PHIsToSlice[i] << '\n';
691 // PredValues - This is a temporary used when rewriting PHI nodes. It is
692 // hoisted out here to avoid construction/destruction thrashing.
693 DenseMap<BasicBlock*, Value*> PredValues;
695 // ExtractedVals - Each new PHI we introduce is saved here so we don't
696 // introduce redundant PHIs.
697 DenseMap<LoweredPHIRecord, PHINode*> ExtractedVals;
699 for (unsigned UserI = 0, UserE = PHIUsers.size(); UserI != UserE; ++UserI) {
700 unsigned PHIId = PHIUsers[UserI].PHIId;
701 PHINode *PN = PHIsToSlice[PHIId];
702 unsigned Offset = PHIUsers[UserI].Shift;
703 Type *Ty = PHIUsers[UserI].Inst->getType();
707 // If we've already lowered a user like this, reuse the previously lowered
709 if ((EltPHI = ExtractedVals[LoweredPHIRecord(PN, Offset, Ty)]) == nullptr) {
711 // Otherwise, Create the new PHI node for this user.
712 EltPHI = PHINode::Create(Ty, PN->getNumIncomingValues(),
713 PN->getName()+".off"+Twine(Offset), PN);
714 assert(EltPHI->getType() != PN->getType() &&
715 "Truncate didn't shrink phi?");
717 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) {
718 BasicBlock *Pred = PN->getIncomingBlock(i);
719 Value *&PredVal = PredValues[Pred];
721 // If we already have a value for this predecessor, reuse it.
723 EltPHI->addIncoming(PredVal, Pred);
727 // Handle the PHI self-reuse case.
728 Value *InVal = PN->getIncomingValue(i);
731 EltPHI->addIncoming(PredVal, Pred);
735 if (PHINode *InPHI = dyn_cast<PHINode>(PN)) {
736 // If the incoming value was a PHI, and if it was one of the PHIs we
737 // already rewrote it, just use the lowered value.
738 if (Value *Res = ExtractedVals[LoweredPHIRecord(InPHI, Offset, Ty)]) {
740 EltPHI->addIncoming(PredVal, Pred);
745 // Otherwise, do an extract in the predecessor.
746 Builder->SetInsertPoint(Pred, Pred->getTerminator());
749 Res = Builder->CreateLShr(Res, ConstantInt::get(InVal->getType(),
751 Res = Builder->CreateTrunc(Res, Ty, "extract.t");
753 EltPHI->addIncoming(Res, Pred);
755 // If the incoming value was a PHI, and if it was one of the PHIs we are
756 // rewriting, we will ultimately delete the code we inserted. This
757 // means we need to revisit that PHI to make sure we extract out the
759 if (PHINode *OldInVal = dyn_cast<PHINode>(PN->getIncomingValue(i)))
760 if (PHIsInspected.count(OldInVal)) {
761 unsigned RefPHIId = std::find(PHIsToSlice.begin(),PHIsToSlice.end(),
762 OldInVal)-PHIsToSlice.begin();
763 PHIUsers.push_back(PHIUsageRecord(RefPHIId, Offset,
764 cast<Instruction>(Res)));
770 DEBUG(dbgs() << " Made element PHI for offset " << Offset << ": "
772 ExtractedVals[LoweredPHIRecord(PN, Offset, Ty)] = EltPHI;
775 // Replace the use of this piece with the PHI node.
776 ReplaceInstUsesWith(*PHIUsers[UserI].Inst, EltPHI);
779 // Replace all the remaining uses of the PHI nodes (self uses and the lshrs)
781 Value *Undef = UndefValue::get(FirstPhi.getType());
782 for (unsigned i = 1, e = PHIsToSlice.size(); i != e; ++i)
783 ReplaceInstUsesWith(*PHIsToSlice[i], Undef);
784 return ReplaceInstUsesWith(FirstPhi, Undef);
787 // PHINode simplification
789 Instruction *InstCombiner::visitPHINode(PHINode &PN) {
790 if (Value *V = SimplifyInstruction(&PN, DL, TLI, DT, AC))
791 return ReplaceInstUsesWith(PN, V);
793 // If all PHI operands are the same operation, pull them through the PHI,
794 // reducing code size.
795 if (isa<Instruction>(PN.getIncomingValue(0)) &&
796 isa<Instruction>(PN.getIncomingValue(1)) &&
797 cast<Instruction>(PN.getIncomingValue(0))->getOpcode() ==
798 cast<Instruction>(PN.getIncomingValue(1))->getOpcode() &&
799 // FIXME: The hasOneUse check will fail for PHIs that use the value more
800 // than themselves more than once.
801 PN.getIncomingValue(0)->hasOneUse())
802 if (Instruction *Result = FoldPHIArgOpIntoPHI(PN))
805 // If this is a trivial cycle in the PHI node graph, remove it. Basically, if
806 // this PHI only has a single use (a PHI), and if that PHI only has one use (a
807 // PHI)... break the cycle.
808 if (PN.hasOneUse()) {
809 Instruction *PHIUser = cast<Instruction>(PN.user_back());
810 if (PHINode *PU = dyn_cast<PHINode>(PHIUser)) {
811 SmallPtrSet<PHINode*, 16> PotentiallyDeadPHIs;
812 PotentiallyDeadPHIs.insert(&PN);
813 if (DeadPHICycle(PU, PotentiallyDeadPHIs))
814 return ReplaceInstUsesWith(PN, UndefValue::get(PN.getType()));
817 // If this phi has a single use, and if that use just computes a value for
818 // the next iteration of a loop, delete the phi. This occurs with unused
819 // induction variables, e.g. "for (int j = 0; ; ++j);". Detecting this
820 // common case here is good because the only other things that catch this
821 // are induction variable analysis (sometimes) and ADCE, which is only run
823 if (PHIUser->hasOneUse() &&
824 (isa<BinaryOperator>(PHIUser) || isa<GetElementPtrInst>(PHIUser)) &&
825 PHIUser->user_back() == &PN) {
826 return ReplaceInstUsesWith(PN, UndefValue::get(PN.getType()));
830 // We sometimes end up with phi cycles that non-obviously end up being the
831 // same value, for example:
832 // z = some value; x = phi (y, z); y = phi (x, z)
833 // where the phi nodes don't necessarily need to be in the same block. Do a
834 // quick check to see if the PHI node only contains a single non-phi value, if
835 // so, scan to see if the phi cycle is actually equal to that value.
837 unsigned InValNo = 0, NumIncomingVals = PN.getNumIncomingValues();
838 // Scan for the first non-phi operand.
839 while (InValNo != NumIncomingVals &&
840 isa<PHINode>(PN.getIncomingValue(InValNo)))
843 if (InValNo != NumIncomingVals) {
844 Value *NonPhiInVal = PN.getIncomingValue(InValNo);
846 // Scan the rest of the operands to see if there are any conflicts, if so
847 // there is no need to recursively scan other phis.
848 for (++InValNo; InValNo != NumIncomingVals; ++InValNo) {
849 Value *OpVal = PN.getIncomingValue(InValNo);
850 if (OpVal != NonPhiInVal && !isa<PHINode>(OpVal))
854 // If we scanned over all operands, then we have one unique value plus
855 // phi values. Scan PHI nodes to see if they all merge in each other or
857 if (InValNo == NumIncomingVals) {
858 SmallPtrSet<PHINode*, 16> ValueEqualPHIs;
859 if (PHIsEqualValue(&PN, NonPhiInVal, ValueEqualPHIs))
860 return ReplaceInstUsesWith(PN, NonPhiInVal);
865 // If there are multiple PHIs, sort their operands so that they all list
866 // the blocks in the same order. This will help identical PHIs be eliminated
867 // by other passes. Other passes shouldn't depend on this for correctness
869 PHINode *FirstPN = cast<PHINode>(PN.getParent()->begin());
871 for (unsigned i = 0, e = FirstPN->getNumIncomingValues(); i != e; ++i) {
872 BasicBlock *BBA = PN.getIncomingBlock(i);
873 BasicBlock *BBB = FirstPN->getIncomingBlock(i);
875 Value *VA = PN.getIncomingValue(i);
876 unsigned j = PN.getBasicBlockIndex(BBB);
877 Value *VB = PN.getIncomingValue(j);
878 PN.setIncomingBlock(i, BBB);
879 PN.setIncomingValue(i, VB);
880 PN.setIncomingBlock(j, BBA);
881 PN.setIncomingValue(j, VA);
882 // NOTE: Instcombine normally would want us to "return &PN" if we
883 // modified any of the operands of an instruction. However, since we
884 // aren't adding or removing uses (just rearranging them) we don't do
885 // this in this case.
889 // If this is an integer PHI and we know that it has an illegal type, see if
890 // it is only used by trunc or trunc(lshr) operations. If so, we split the
891 // PHI into the various pieces being extracted. This sort of thing is
892 // introduced when SROA promotes an aggregate to a single large integer type.
893 if (PN.getType()->isIntegerTy() &&
894 !DL.isLegalInteger(PN.getType()->getPrimitiveSizeInBits()))
895 if (Instruction *Res = SliceUpIllegalIntegerPHI(PN))