There is only one register coalescer. Merge it into the base class and
[llvm/stm8.git] / lib / Transforms / InstCombine / InstCombinePHI.cpp
blob37773403490c39e2e5f468a45dfe7da4b93e4daa
1 //===- InstCombinePHI.cpp -------------------------------------------------===//
2 //
3 // The LLVM Compiler Infrastructure
4 //
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
7 //
8 //===----------------------------------------------------------------------===//
9 //
10 // This file implements the visitPHINode function.
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"
19 using namespace llvm;
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
48 // types.
49 I->getOperand(0)->getType() != LHSType ||
50 I->getOperand(1)->getType() != RHSType)
51 return 0;
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())
56 return 0;
58 if (isNUW)
59 isNUW = cast<OverflowingBinaryOperator>(I)->hasNoUnsignedWrap();
60 if (isNSW)
61 isNSW = cast<OverflowingBinaryOperator>(I)->hasNoSignedWrap();
62 if (isExact)
63 isExact = cast<PossiblyExactOperator>(I)->isExact();
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)
75 return 0;
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;
82 if (LHSVal == 0) {
83 NewLHS = PHINode::Create(LHSType, PN.getNumIncomingValues(),
84 FirstInst->getOperand(0)->getName() + ".pn");
85 NewLHS->addIncoming(InLHS, PN.getIncomingBlock(0));
86 InsertNewInstBefore(NewLHS, PN);
87 LHSVal = NewLHS;
90 if (RHSVal == 0) {
91 NewRHS = PHINode::Create(RHSType, PN.getNumIncomingValues(),
92 FirstInst->getOperand(1)->getName() + ".pn");
93 NewRHS->addIncoming(InRHS, PN.getIncomingBlock(0));
94 InsertNewInstBefore(NewRHS, PN);
95 RHSVal = NewRHS;
98 // Add all operands to the new PHIs.
99 if (NewLHS || NewRHS) {
100 for (unsigned i = 1, e = PN.getNumIncomingValues(); i != e; ++i) {
101 Instruction *InInst = cast<Instruction>(PN.getIncomingValue(i));
102 if (NewLHS) {
103 Value *NewInLHS = InInst->getOperand(0);
104 NewLHS->addIncoming(NewInLHS, PN.getIncomingBlock(i));
106 if (NewRHS) {
107 Value *NewInRHS = InInst->getOperand(1);
108 NewRHS->addIncoming(NewInRHS, PN.getIncomingBlock(i));
113 if (CmpInst *CIOp = dyn_cast<CmpInst>(FirstInst)) {
114 CmpInst *NewCI = CmpInst::Create(CIOp->getOpcode(), CIOp->getPredicate(),
115 LHSVal, RHSVal);
116 NewCI->setDebugLoc(FirstInst->getDebugLoc());
117 return NewCI;
120 BinaryOperator *BinOp = cast<BinaryOperator>(FirstInst);
121 BinaryOperator *NewBinOp =
122 BinaryOperator::Create(BinOp->getOpcode(), LHSVal, RHSVal);
123 if (isNUW) NewBinOp->setHasNoUnsignedWrap();
124 if (isNSW) NewBinOp->setHasNoSignedWrap();
125 if (isExact) NewBinOp->setIsExact();
126 NewBinOp->setDebugLoc(FirstInst->getDebugLoc());
127 return NewBinOp;
130 Instruction *InstCombiner::FoldPHIArgGEPIntoPHI(PHINode &PN) {
131 GetElementPtrInst *FirstInst =cast<GetElementPtrInst>(PN.getIncomingValue(0));
133 SmallVector<Value*, 16> FixedOperands(FirstInst->op_begin(),
134 FirstInst->op_end());
135 // This is true if all GEP bases are allocas and if all indices into them are
136 // constants.
137 bool AllBasePointersAreAllocas = true;
139 // We don't want to replace this phi if the replacement would require
140 // more than one phi, which leads to higher register pressure. This is
141 // especially bad when the PHIs are in the header of a loop.
142 bool NeededPhi = false;
144 bool AllInBounds = true;
146 // Scan to see if all operands are the same opcode, and all have one use.
147 for (unsigned i = 1; i != PN.getNumIncomingValues(); ++i) {
148 GetElementPtrInst *GEP= dyn_cast<GetElementPtrInst>(PN.getIncomingValue(i));
149 if (!GEP || !GEP->hasOneUse() || GEP->getType() != FirstInst->getType() ||
150 GEP->getNumOperands() != FirstInst->getNumOperands())
151 return 0;
153 AllInBounds &= GEP->isInBounds();
155 // Keep track of whether or not all GEPs are of alloca pointers.
156 if (AllBasePointersAreAllocas &&
157 (!isa<AllocaInst>(GEP->getOperand(0)) ||
158 !GEP->hasAllConstantIndices()))
159 AllBasePointersAreAllocas = false;
161 // Compare the operand lists.
162 for (unsigned op = 0, e = FirstInst->getNumOperands(); op != e; ++op) {
163 if (FirstInst->getOperand(op) == GEP->getOperand(op))
164 continue;
166 // Don't merge two GEPs when two operands differ (introducing phi nodes)
167 // if one of the PHIs has a constant for the index. The index may be
168 // substantially cheaper to compute for the constants, so making it a
169 // variable index could pessimize the path. This also handles the case
170 // for struct indices, which must always be constant.
171 if (isa<ConstantInt>(FirstInst->getOperand(op)) ||
172 isa<ConstantInt>(GEP->getOperand(op)))
173 return 0;
175 if (FirstInst->getOperand(op)->getType() !=GEP->getOperand(op)->getType())
176 return 0;
178 // If we already needed a PHI for an earlier operand, and another operand
179 // also requires a PHI, we'd be introducing more PHIs than we're
180 // eliminating, which increases register pressure on entry to the PHI's
181 // block.
182 if (NeededPhi)
183 return 0;
185 FixedOperands[op] = 0; // Needs a PHI.
186 NeededPhi = true;
190 // If all of the base pointers of the PHI'd GEPs are from allocas, don't
191 // bother doing this transformation. At best, this will just save a bit of
192 // offset calculation, but all the predecessors will have to materialize the
193 // stack address into a register anyway. We'd actually rather *clone* the
194 // load up into the predecessors so that we have a load of a gep of an alloca,
195 // which can usually all be folded into the load.
196 if (AllBasePointersAreAllocas)
197 return 0;
199 // Otherwise, this is safe to transform. Insert PHI nodes for each operand
200 // that is variable.
201 SmallVector<PHINode*, 16> OperandPhis(FixedOperands.size());
203 bool HasAnyPHIs = false;
204 for (unsigned i = 0, e = FixedOperands.size(); i != e; ++i) {
205 if (FixedOperands[i]) continue; // operand doesn't need a phi.
206 Value *FirstOp = FirstInst->getOperand(i);
207 PHINode *NewPN = PHINode::Create(FirstOp->getType(), e,
208 FirstOp->getName()+".pn");
209 InsertNewInstBefore(NewPN, PN);
211 NewPN->addIncoming(FirstOp, PN.getIncomingBlock(0));
212 OperandPhis[i] = NewPN;
213 FixedOperands[i] = NewPN;
214 HasAnyPHIs = true;
218 // Add all operands to the new PHIs.
219 if (HasAnyPHIs) {
220 for (unsigned i = 1, e = PN.getNumIncomingValues(); i != e; ++i) {
221 GetElementPtrInst *InGEP =cast<GetElementPtrInst>(PN.getIncomingValue(i));
222 BasicBlock *InBB = PN.getIncomingBlock(i);
224 for (unsigned op = 0, e = OperandPhis.size(); op != e; ++op)
225 if (PHINode *OpPhi = OperandPhis[op])
226 OpPhi->addIncoming(InGEP->getOperand(op), InBB);
230 Value *Base = FixedOperands[0];
231 GetElementPtrInst *NewGEP =
232 GetElementPtrInst::Create(Base, FixedOperands.begin()+1,
233 FixedOperands.end());
234 if (AllInBounds) NewGEP->setIsInBounds();
235 NewGEP->setDebugLoc(FirstInst->getDebugLoc());
236 return NewGEP;
240 /// isSafeAndProfitableToSinkLoad - Return true if we know that it is safe to
241 /// sink the load out of the block that defines it. This means that it must be
242 /// obvious the value of the load is not changed from the point of the load to
243 /// the end of the block it is in.
245 /// Finally, it is safe, but not profitable, to sink a load targeting a
246 /// non-address-taken alloca. Doing so will cause us to not promote the alloca
247 /// to a register.
248 static bool isSafeAndProfitableToSinkLoad(LoadInst *L) {
249 BasicBlock::iterator BBI = L, E = L->getParent()->end();
251 for (++BBI; BBI != E; ++BBI)
252 if (BBI->mayWriteToMemory())
253 return false;
255 // Check for non-address taken alloca. If not address-taken already, it isn't
256 // profitable to do this xform.
257 if (AllocaInst *AI = dyn_cast<AllocaInst>(L->getOperand(0))) {
258 bool isAddressTaken = false;
259 for (Value::use_iterator UI = AI->use_begin(), E = AI->use_end();
260 UI != E; ++UI) {
261 User *U = *UI;
262 if (isa<LoadInst>(U)) continue;
263 if (StoreInst *SI = dyn_cast<StoreInst>(U)) {
264 // If storing TO the alloca, then the address isn't taken.
265 if (SI->getOperand(1) == AI) continue;
267 isAddressTaken = true;
268 break;
271 if (!isAddressTaken && AI->isStaticAlloca())
272 return false;
275 // If this load is a load from a GEP with a constant offset from an alloca,
276 // then we don't want to sink it. In its present form, it will be
277 // load [constant stack offset]. Sinking it will cause us to have to
278 // materialize the stack addresses in each predecessor in a register only to
279 // do a shared load from register in the successor.
280 if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(L->getOperand(0)))
281 if (AllocaInst *AI = dyn_cast<AllocaInst>(GEP->getOperand(0)))
282 if (AI->isStaticAlloca() && GEP->hasAllConstantIndices())
283 return false;
285 return true;
288 Instruction *InstCombiner::FoldPHIArgLoadIntoPHI(PHINode &PN) {
289 LoadInst *FirstLI = cast<LoadInst>(PN.getIncomingValue(0));
291 // When processing loads, we need to propagate two bits of information to the
292 // sunk load: whether it is volatile, and what its alignment is. We currently
293 // don't sink loads when some have their alignment specified and some don't.
294 // visitLoadInst will propagate an alignment onto the load when TD is around,
295 // and if TD isn't around, we can't handle the mixed case.
296 bool isVolatile = FirstLI->isVolatile();
297 unsigned LoadAlignment = FirstLI->getAlignment();
298 unsigned LoadAddrSpace = FirstLI->getPointerAddressSpace();
300 // We can't sink the load if the loaded value could be modified between the
301 // load and the PHI.
302 if (FirstLI->getParent() != PN.getIncomingBlock(0) ||
303 !isSafeAndProfitableToSinkLoad(FirstLI))
304 return 0;
306 // If the PHI is of volatile loads and the load block has multiple
307 // successors, sinking it would remove a load of the volatile value from
308 // the path through the other successor.
309 if (isVolatile &&
310 FirstLI->getParent()->getTerminator()->getNumSuccessors() != 1)
311 return 0;
313 // Check to see if all arguments are the same operation.
314 for (unsigned i = 1, e = PN.getNumIncomingValues(); i != e; ++i) {
315 LoadInst *LI = dyn_cast<LoadInst>(PN.getIncomingValue(i));
316 if (!LI || !LI->hasOneUse())
317 return 0;
319 // We can't sink the load if the loaded value could be modified between
320 // the load and the PHI.
321 if (LI->isVolatile() != isVolatile ||
322 LI->getParent() != PN.getIncomingBlock(i) ||
323 LI->getPointerAddressSpace() != LoadAddrSpace ||
324 !isSafeAndProfitableToSinkLoad(LI))
325 return 0;
327 // If some of the loads have an alignment specified but not all of them,
328 // we can't do the transformation.
329 if ((LoadAlignment != 0) != (LI->getAlignment() != 0))
330 return 0;
332 LoadAlignment = std::min(LoadAlignment, LI->getAlignment());
334 // If the PHI is of volatile loads and the load block has multiple
335 // successors, sinking it would remove a load of the volatile value from
336 // the path through the other successor.
337 if (isVolatile &&
338 LI->getParent()->getTerminator()->getNumSuccessors() != 1)
339 return 0;
342 // Okay, they are all the same operation. Create a new PHI node of the
343 // correct type, and PHI together all of the LHS's of the instructions.
344 PHINode *NewPN = PHINode::Create(FirstLI->getOperand(0)->getType(),
345 PN.getNumIncomingValues(),
346 PN.getName()+".in");
348 Value *InVal = FirstLI->getOperand(0);
349 NewPN->addIncoming(InVal, PN.getIncomingBlock(0));
351 // Add all operands to the new PHI.
352 for (unsigned i = 1, e = PN.getNumIncomingValues(); i != e; ++i) {
353 Value *NewInVal = cast<LoadInst>(PN.getIncomingValue(i))->getOperand(0);
354 if (NewInVal != InVal)
355 InVal = 0;
356 NewPN->addIncoming(NewInVal, PN.getIncomingBlock(i));
359 Value *PhiVal;
360 if (InVal) {
361 // The new PHI unions all of the same values together. This is really
362 // common, so we handle it intelligently here for compile-time speed.
363 PhiVal = InVal;
364 delete NewPN;
365 } else {
366 InsertNewInstBefore(NewPN, PN);
367 PhiVal = NewPN;
370 // If this was a volatile load that we are merging, make sure to loop through
371 // and mark all the input loads as non-volatile. If we don't do this, we will
372 // insert a new volatile load and the old ones will not be deletable.
373 if (isVolatile)
374 for (unsigned i = 0, e = PN.getNumIncomingValues(); i != e; ++i)
375 cast<LoadInst>(PN.getIncomingValue(i))->setVolatile(false);
377 LoadInst *NewLI = new LoadInst(PhiVal, "", isVolatile, LoadAlignment);
378 NewLI->setDebugLoc(FirstLI->getDebugLoc());
379 return NewLI;
384 /// FoldPHIArgOpIntoPHI - If all operands to a PHI node are the same "unary"
385 /// operator and they all are only used by the PHI, PHI together their
386 /// inputs, and do the operation once, to the result of the PHI.
387 Instruction *InstCombiner::FoldPHIArgOpIntoPHI(PHINode &PN) {
388 Instruction *FirstInst = cast<Instruction>(PN.getIncomingValue(0));
390 if (isa<GetElementPtrInst>(FirstInst))
391 return FoldPHIArgGEPIntoPHI(PN);
392 if (isa<LoadInst>(FirstInst))
393 return FoldPHIArgLoadIntoPHI(PN);
395 // Scan the instruction, looking for input operations that can be folded away.
396 // If all input operands to the phi are the same instruction (e.g. a cast from
397 // the same type or "+42") we can pull the operation through the PHI, reducing
398 // code size and simplifying code.
399 Constant *ConstantOp = 0;
400 const Type *CastSrcTy = 0;
401 bool isNUW = false, isNSW = false, isExact = false;
403 if (isa<CastInst>(FirstInst)) {
404 CastSrcTy = FirstInst->getOperand(0)->getType();
406 // Be careful about transforming integer PHIs. We don't want to pessimize
407 // the code by turning an i32 into an i1293.
408 if (PN.getType()->isIntegerTy() && CastSrcTy->isIntegerTy()) {
409 if (!ShouldChangeType(PN.getType(), CastSrcTy))
410 return 0;
412 } else if (isa<BinaryOperator>(FirstInst) || isa<CmpInst>(FirstInst)) {
413 // Can fold binop, compare or shift here if the RHS is a constant,
414 // otherwise call FoldPHIArgBinOpIntoPHI.
415 ConstantOp = dyn_cast<Constant>(FirstInst->getOperand(1));
416 if (ConstantOp == 0)
417 return FoldPHIArgBinOpIntoPHI(PN);
419 if (OverflowingBinaryOperator *BO =
420 dyn_cast<OverflowingBinaryOperator>(FirstInst)) {
421 isNUW = BO->hasNoUnsignedWrap();
422 isNSW = BO->hasNoSignedWrap();
423 } else if (PossiblyExactOperator *PEO =
424 dyn_cast<PossiblyExactOperator>(FirstInst))
425 isExact = PEO->isExact();
426 } else {
427 return 0; // Cannot fold this operation.
430 // Check to see if all arguments are the same operation.
431 for (unsigned i = 1, e = PN.getNumIncomingValues(); i != e; ++i) {
432 Instruction *I = dyn_cast<Instruction>(PN.getIncomingValue(i));
433 if (I == 0 || !I->hasOneUse() || !I->isSameOperationAs(FirstInst))
434 return 0;
435 if (CastSrcTy) {
436 if (I->getOperand(0)->getType() != CastSrcTy)
437 return 0; // Cast operation must match.
438 } else if (I->getOperand(1) != ConstantOp) {
439 return 0;
442 if (isNUW)
443 isNUW = cast<OverflowingBinaryOperator>(I)->hasNoUnsignedWrap();
444 if (isNSW)
445 isNSW = cast<OverflowingBinaryOperator>(I)->hasNoSignedWrap();
446 if (isExact)
447 isExact = cast<PossiblyExactOperator>(I)->isExact();
450 // Okay, they are all the same operation. Create a new PHI node of the
451 // correct type, and PHI together all of the LHS's of the instructions.
452 PHINode *NewPN = PHINode::Create(FirstInst->getOperand(0)->getType(),
453 PN.getNumIncomingValues(),
454 PN.getName()+".in");
456 Value *InVal = FirstInst->getOperand(0);
457 NewPN->addIncoming(InVal, PN.getIncomingBlock(0));
459 // Add all operands to the new PHI.
460 for (unsigned i = 1, e = PN.getNumIncomingValues(); i != e; ++i) {
461 Value *NewInVal = cast<Instruction>(PN.getIncomingValue(i))->getOperand(0);
462 if (NewInVal != InVal)
463 InVal = 0;
464 NewPN->addIncoming(NewInVal, PN.getIncomingBlock(i));
467 Value *PhiVal;
468 if (InVal) {
469 // The new PHI unions all of the same values together. This is really
470 // common, so we handle it intelligently here for compile-time speed.
471 PhiVal = InVal;
472 delete NewPN;
473 } else {
474 InsertNewInstBefore(NewPN, PN);
475 PhiVal = NewPN;
478 // Insert and return the new operation.
479 if (CastInst *FirstCI = dyn_cast<CastInst>(FirstInst)) {
480 CastInst *NewCI = CastInst::Create(FirstCI->getOpcode(), PhiVal,
481 PN.getType());
482 NewCI->setDebugLoc(FirstInst->getDebugLoc());
483 return NewCI;
486 if (BinaryOperator *BinOp = dyn_cast<BinaryOperator>(FirstInst)) {
487 BinOp = BinaryOperator::Create(BinOp->getOpcode(), PhiVal, ConstantOp);
488 if (isNUW) BinOp->setHasNoUnsignedWrap();
489 if (isNSW) BinOp->setHasNoSignedWrap();
490 if (isExact) BinOp->setIsExact();
491 BinOp->setDebugLoc(FirstInst->getDebugLoc());
492 return BinOp;
495 CmpInst *CIOp = cast<CmpInst>(FirstInst);
496 CmpInst *NewCI = CmpInst::Create(CIOp->getOpcode(), CIOp->getPredicate(),
497 PhiVal, ConstantOp);
498 NewCI->setDebugLoc(FirstInst->getDebugLoc());
499 return NewCI;
502 /// DeadPHICycle - Return true if this PHI node is only used by a PHI node cycle
503 /// that is dead.
504 static bool DeadPHICycle(PHINode *PN,
505 SmallPtrSet<PHINode*, 16> &PotentiallyDeadPHIs) {
506 if (PN->use_empty()) return true;
507 if (!PN->hasOneUse()) return false;
509 // Remember this node, and if we find the cycle, return.
510 if (!PotentiallyDeadPHIs.insert(PN))
511 return true;
513 // Don't scan crazily complex things.
514 if (PotentiallyDeadPHIs.size() == 16)
515 return false;
517 if (PHINode *PU = dyn_cast<PHINode>(PN->use_back()))
518 return DeadPHICycle(PU, PotentiallyDeadPHIs);
520 return false;
523 /// PHIsEqualValue - Return true if this phi node is always equal to
524 /// NonPhiInVal. This happens with mutually cyclic phi nodes like:
525 /// z = some value; x = phi (y, z); y = phi (x, z)
526 static bool PHIsEqualValue(PHINode *PN, Value *NonPhiInVal,
527 SmallPtrSet<PHINode*, 16> &ValueEqualPHIs) {
528 // See if we already saw this PHI node.
529 if (!ValueEqualPHIs.insert(PN))
530 return true;
532 // Don't scan crazily complex things.
533 if (ValueEqualPHIs.size() == 16)
534 return false;
536 // Scan the operands to see if they are either phi nodes or are equal to
537 // the value.
538 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) {
539 Value *Op = PN->getIncomingValue(i);
540 if (PHINode *OpPN = dyn_cast<PHINode>(Op)) {
541 if (!PHIsEqualValue(OpPN, NonPhiInVal, ValueEqualPHIs))
542 return false;
543 } else if (Op != NonPhiInVal)
544 return false;
547 return true;
551 namespace {
552 struct PHIUsageRecord {
553 unsigned PHIId; // The ID # of the PHI (something determinstic to sort on)
554 unsigned Shift; // The amount shifted.
555 Instruction *Inst; // The trunc instruction.
557 PHIUsageRecord(unsigned pn, unsigned Sh, Instruction *User)
558 : PHIId(pn), Shift(Sh), Inst(User) {}
560 bool operator<(const PHIUsageRecord &RHS) const {
561 if (PHIId < RHS.PHIId) return true;
562 if (PHIId > RHS.PHIId) return false;
563 if (Shift < RHS.Shift) return true;
564 if (Shift > RHS.Shift) return false;
565 return Inst->getType()->getPrimitiveSizeInBits() <
566 RHS.Inst->getType()->getPrimitiveSizeInBits();
570 struct LoweredPHIRecord {
571 PHINode *PN; // The PHI that was lowered.
572 unsigned Shift; // The amount shifted.
573 unsigned Width; // The width extracted.
575 LoweredPHIRecord(PHINode *pn, unsigned Sh, const Type *Ty)
576 : PN(pn), Shift(Sh), Width(Ty->getPrimitiveSizeInBits()) {}
578 // Ctor form used by DenseMap.
579 LoweredPHIRecord(PHINode *pn, unsigned Sh)
580 : PN(pn), Shift(Sh), Width(0) {}
584 namespace llvm {
585 template<>
586 struct DenseMapInfo<LoweredPHIRecord> {
587 static inline LoweredPHIRecord getEmptyKey() {
588 return LoweredPHIRecord(0, 0);
590 static inline LoweredPHIRecord getTombstoneKey() {
591 return LoweredPHIRecord(0, 1);
593 static unsigned getHashValue(const LoweredPHIRecord &Val) {
594 return DenseMapInfo<PHINode*>::getHashValue(Val.PN) ^ (Val.Shift>>3) ^
595 (Val.Width>>3);
597 static bool isEqual(const LoweredPHIRecord &LHS,
598 const LoweredPHIRecord &RHS) {
599 return LHS.PN == RHS.PN && LHS.Shift == RHS.Shift &&
600 LHS.Width == RHS.Width;
603 template <>
604 struct isPodLike<LoweredPHIRecord> { static const bool value = true; };
608 /// SliceUpIllegalIntegerPHI - This is an integer PHI and we know that it has an
609 /// illegal type: see if it is only used by trunc or trunc(lshr) operations. If
610 /// so, we split the PHI into the various pieces being extracted. This sort of
611 /// thing is introduced when SROA promotes an aggregate to large integer values.
613 /// TODO: The user of the trunc may be an bitcast to float/double/vector or an
614 /// inttoptr. We should produce new PHIs in the right type.
616 Instruction *InstCombiner::SliceUpIllegalIntegerPHI(PHINode &FirstPhi) {
617 // PHIUsers - Keep track of all of the truncated values extracted from a set
618 // of PHIs, along with their offset. These are the things we want to rewrite.
619 SmallVector<PHIUsageRecord, 16> PHIUsers;
621 // PHIs are often mutually cyclic, so we keep track of a whole set of PHI
622 // nodes which are extracted from. PHIsToSlice is a set we use to avoid
623 // revisiting PHIs, PHIsInspected is a ordered list of PHIs that we need to
624 // check the uses of (to ensure they are all extracts).
625 SmallVector<PHINode*, 8> PHIsToSlice;
626 SmallPtrSet<PHINode*, 8> PHIsInspected;
628 PHIsToSlice.push_back(&FirstPhi);
629 PHIsInspected.insert(&FirstPhi);
631 for (unsigned PHIId = 0; PHIId != PHIsToSlice.size(); ++PHIId) {
632 PHINode *PN = PHIsToSlice[PHIId];
634 // Scan the input list of the PHI. If any input is an invoke, and if the
635 // input is defined in the predecessor, then we won't be split the critical
636 // edge which is required to insert a truncate. Because of this, we have to
637 // bail out.
638 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) {
639 InvokeInst *II = dyn_cast<InvokeInst>(PN->getIncomingValue(i));
640 if (II == 0) continue;
641 if (II->getParent() != PN->getIncomingBlock(i))
642 continue;
644 // If we have a phi, and if it's directly in the predecessor, then we have
645 // a critical edge where we need to put the truncate. Since we can't
646 // split the edge in instcombine, we have to bail out.
647 return 0;
651 for (Value::use_iterator UI = PN->use_begin(), E = PN->use_end();
652 UI != E; ++UI) {
653 Instruction *User = cast<Instruction>(*UI);
655 // If the user is a PHI, inspect its uses recursively.
656 if (PHINode *UserPN = dyn_cast<PHINode>(User)) {
657 if (PHIsInspected.insert(UserPN))
658 PHIsToSlice.push_back(UserPN);
659 continue;
662 // Truncates are always ok.
663 if (isa<TruncInst>(User)) {
664 PHIUsers.push_back(PHIUsageRecord(PHIId, 0, User));
665 continue;
668 // Otherwise it must be a lshr which can only be used by one trunc.
669 if (User->getOpcode() != Instruction::LShr ||
670 !User->hasOneUse() || !isa<TruncInst>(User->use_back()) ||
671 !isa<ConstantInt>(User->getOperand(1)))
672 return 0;
674 unsigned Shift = cast<ConstantInt>(User->getOperand(1))->getZExtValue();
675 PHIUsers.push_back(PHIUsageRecord(PHIId, Shift, User->use_back()));
679 // If we have no users, they must be all self uses, just nuke the PHI.
680 if (PHIUsers.empty())
681 return ReplaceInstUsesWith(FirstPhi, UndefValue::get(FirstPhi.getType()));
683 // If this phi node is transformable, create new PHIs for all the pieces
684 // extracted out of it. First, sort the users by their offset and size.
685 array_pod_sort(PHIUsers.begin(), PHIUsers.end());
687 DEBUG(errs() << "SLICING UP PHI: " << FirstPhi << '\n';
688 for (unsigned i = 1, e = PHIsToSlice.size(); i != e; ++i)
689 errs() << "AND USER PHI #" << i << ": " << *PHIsToSlice[i] <<'\n';
692 // PredValues - This is a temporary used when rewriting PHI nodes. It is
693 // hoisted out here to avoid construction/destruction thrashing.
694 DenseMap<BasicBlock*, Value*> PredValues;
696 // ExtractedVals - Each new PHI we introduce is saved here so we don't
697 // introduce redundant PHIs.
698 DenseMap<LoweredPHIRecord, PHINode*> ExtractedVals;
700 for (unsigned UserI = 0, UserE = PHIUsers.size(); UserI != UserE; ++UserI) {
701 unsigned PHIId = PHIUsers[UserI].PHIId;
702 PHINode *PN = PHIsToSlice[PHIId];
703 unsigned Offset = PHIUsers[UserI].Shift;
704 const Type *Ty = PHIUsers[UserI].Inst->getType();
706 PHINode *EltPHI;
708 // If we've already lowered a user like this, reuse the previously lowered
709 // value.
710 if ((EltPHI = ExtractedVals[LoweredPHIRecord(PN, Offset, Ty)]) == 0) {
712 // Otherwise, Create the new PHI node for this user.
713 EltPHI = PHINode::Create(Ty, PN->getNumIncomingValues(),
714 PN->getName()+".off"+Twine(Offset), PN);
715 assert(EltPHI->getType() != PN->getType() &&
716 "Truncate didn't shrink phi?");
718 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) {
719 BasicBlock *Pred = PN->getIncomingBlock(i);
720 Value *&PredVal = PredValues[Pred];
722 // If we already have a value for this predecessor, reuse it.
723 if (PredVal) {
724 EltPHI->addIncoming(PredVal, Pred);
725 continue;
728 // Handle the PHI self-reuse case.
729 Value *InVal = PN->getIncomingValue(i);
730 if (InVal == PN) {
731 PredVal = EltPHI;
732 EltPHI->addIncoming(PredVal, Pred);
733 continue;
736 if (PHINode *InPHI = dyn_cast<PHINode>(PN)) {
737 // If the incoming value was a PHI, and if it was one of the PHIs we
738 // already rewrote it, just use the lowered value.
739 if (Value *Res = ExtractedVals[LoweredPHIRecord(InPHI, Offset, Ty)]) {
740 PredVal = Res;
741 EltPHI->addIncoming(PredVal, Pred);
742 continue;
746 // Otherwise, do an extract in the predecessor.
747 Builder->SetInsertPoint(Pred, Pred->getTerminator());
748 Value *Res = InVal;
749 if (Offset)
750 Res = Builder->CreateLShr(Res, ConstantInt::get(InVal->getType(),
751 Offset), "extract");
752 Res = Builder->CreateTrunc(Res, Ty, "extract.t");
753 PredVal = Res;
754 EltPHI->addIncoming(Res, Pred);
756 // If the incoming value was a PHI, and if it was one of the PHIs we are
757 // rewriting, we will ultimately delete the code we inserted. This
758 // means we need to revisit that PHI to make sure we extract out the
759 // needed piece.
760 if (PHINode *OldInVal = dyn_cast<PHINode>(PN->getIncomingValue(i)))
761 if (PHIsInspected.count(OldInVal)) {
762 unsigned RefPHIId = std::find(PHIsToSlice.begin(),PHIsToSlice.end(),
763 OldInVal)-PHIsToSlice.begin();
764 PHIUsers.push_back(PHIUsageRecord(RefPHIId, Offset,
765 cast<Instruction>(Res)));
766 ++UserE;
769 PredValues.clear();
771 DEBUG(errs() << " Made element PHI for offset " << Offset << ": "
772 << *EltPHI << '\n');
773 ExtractedVals[LoweredPHIRecord(PN, Offset, Ty)] = EltPHI;
776 // Replace the use of this piece with the PHI node.
777 ReplaceInstUsesWith(*PHIUsers[UserI].Inst, EltPHI);
780 // Replace all the remaining uses of the PHI nodes (self uses and the lshrs)
781 // with undefs.
782 Value *Undef = UndefValue::get(FirstPhi.getType());
783 for (unsigned i = 1, e = PHIsToSlice.size(); i != e; ++i)
784 ReplaceInstUsesWith(*PHIsToSlice[i], Undef);
785 return ReplaceInstUsesWith(FirstPhi, Undef);
788 // PHINode simplification
790 Instruction *InstCombiner::visitPHINode(PHINode &PN) {
791 if (Value *V = SimplifyInstruction(&PN, TD))
792 return ReplaceInstUsesWith(PN, V);
794 // If all PHI operands are the same operation, pull them through the PHI,
795 // reducing code size.
796 if (isa<Instruction>(PN.getIncomingValue(0)) &&
797 isa<Instruction>(PN.getIncomingValue(1)) &&
798 cast<Instruction>(PN.getIncomingValue(0))->getOpcode() ==
799 cast<Instruction>(PN.getIncomingValue(1))->getOpcode() &&
800 // FIXME: The hasOneUse check will fail for PHIs that use the value more
801 // than themselves more than once.
802 PN.getIncomingValue(0)->hasOneUse())
803 if (Instruction *Result = FoldPHIArgOpIntoPHI(PN))
804 return Result;
806 // If this is a trivial cycle in the PHI node graph, remove it. Basically, if
807 // this PHI only has a single use (a PHI), and if that PHI only has one use (a
808 // PHI)... break the cycle.
809 if (PN.hasOneUse()) {
810 Instruction *PHIUser = cast<Instruction>(PN.use_back());
811 if (PHINode *PU = dyn_cast<PHINode>(PHIUser)) {
812 SmallPtrSet<PHINode*, 16> PotentiallyDeadPHIs;
813 PotentiallyDeadPHIs.insert(&PN);
814 if (DeadPHICycle(PU, PotentiallyDeadPHIs))
815 return ReplaceInstUsesWith(PN, UndefValue::get(PN.getType()));
818 // If this phi has a single use, and if that use just computes a value for
819 // the next iteration of a loop, delete the phi. This occurs with unused
820 // induction variables, e.g. "for (int j = 0; ; ++j);". Detecting this
821 // common case here is good because the only other things that catch this
822 // are induction variable analysis (sometimes) and ADCE, which is only run
823 // late.
824 if (PHIUser->hasOneUse() &&
825 (isa<BinaryOperator>(PHIUser) || isa<GetElementPtrInst>(PHIUser)) &&
826 PHIUser->use_back() == &PN) {
827 return ReplaceInstUsesWith(PN, UndefValue::get(PN.getType()));
831 // We sometimes end up with phi cycles that non-obviously end up being the
832 // same value, for example:
833 // z = some value; x = phi (y, z); y = phi (x, z)
834 // where the phi nodes don't necessarily need to be in the same block. Do a
835 // quick check to see if the PHI node only contains a single non-phi value, if
836 // so, scan to see if the phi cycle is actually equal to that value.
838 unsigned InValNo = 0, NumIncomingVals = PN.getNumIncomingValues();
839 // Scan for the first non-phi operand.
840 while (InValNo != NumIncomingVals &&
841 isa<PHINode>(PN.getIncomingValue(InValNo)))
842 ++InValNo;
844 if (InValNo != NumIncomingVals) {
845 Value *NonPhiInVal = PN.getIncomingValue(InValNo);
847 // Scan the rest of the operands to see if there are any conflicts, if so
848 // there is no need to recursively scan other phis.
849 for (++InValNo; InValNo != NumIncomingVals; ++InValNo) {
850 Value *OpVal = PN.getIncomingValue(InValNo);
851 if (OpVal != NonPhiInVal && !isa<PHINode>(OpVal))
852 break;
855 // If we scanned over all operands, then we have one unique value plus
856 // phi values. Scan PHI nodes to see if they all merge in each other or
857 // the value.
858 if (InValNo == NumIncomingVals) {
859 SmallPtrSet<PHINode*, 16> ValueEqualPHIs;
860 if (PHIsEqualValue(&PN, NonPhiInVal, ValueEqualPHIs))
861 return ReplaceInstUsesWith(PN, NonPhiInVal);
866 // If there are multiple PHIs, sort their operands so that they all list
867 // the blocks in the same order. This will help identical PHIs be eliminated
868 // by other passes. Other passes shouldn't depend on this for correctness
869 // however.
870 PHINode *FirstPN = cast<PHINode>(PN.getParent()->begin());
871 if (&PN != FirstPN)
872 for (unsigned i = 0, e = FirstPN->getNumIncomingValues(); i != e; ++i) {
873 BasicBlock *BBA = PN.getIncomingBlock(i);
874 BasicBlock *BBB = FirstPN->getIncomingBlock(i);
875 if (BBA != BBB) {
876 Value *VA = PN.getIncomingValue(i);
877 unsigned j = PN.getBasicBlockIndex(BBB);
878 Value *VB = PN.getIncomingValue(j);
879 PN.setIncomingBlock(i, BBB);
880 PN.setIncomingValue(i, VB);
881 PN.setIncomingBlock(j, BBA);
882 PN.setIncomingValue(j, VA);
883 // NOTE: Instcombine normally would want us to "return &PN" if we
884 // modified any of the operands of an instruction. However, since we
885 // aren't adding or removing uses (just rearranging them) we don't do
886 // this in this case.
890 // If this is an integer PHI and we know that it has an illegal type, see if
891 // it is only used by trunc or trunc(lshr) operations. If so, we split the
892 // PHI into the various pieces being extracted. This sort of thing is
893 // introduced when SROA promotes an aggregate to a single large integer type.
894 if (PN.getType()->isIntegerTy() && TD &&
895 !TD->isLegalInteger(PN.getType()->getPrimitiveSizeInBits()))
896 if (Instruction *Res = SliceUpIllegalIntegerPHI(PN))
897 return Res;
899 return 0;