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.
11 //
12 //===----------------------------------------------------------------------===//
13 
14 #include "InstCombineInternal.h"
15 #include "llvm/ADT/STLExtras.h"
16 #include "llvm/ADT/SmallPtrSet.h"
17 #include "llvm/Analysis/InstructionSimplify.h"
18 #include "llvm/Analysis/ValueTracking.h"
19 #include "llvm/IR/PatternMatch.h"
20 #include "llvm/Transforms/Utils/Local.h"
21 using namespace llvm;
22 using namespace llvm::PatternMatch;
23 
24 #define DEBUG_TYPE "instcombine"
25 
26 /// If we have something like phi [add (a,b), add(a,c)] and if a/b/c and the
27 /// adds all have a single use, turn this into a phi and a single binop.
28 Instruction *InstCombiner::FoldPHIArgBinOpIntoPHI(PHINode &PN) {
29   Instruction *FirstInst = cast<Instruction>(PN.getIncomingValue(0));
30   assert(isa<BinaryOperator>(FirstInst) || isa<CmpInst>(FirstInst));
31   unsigned Opc = FirstInst->getOpcode();
32   Value *LHSVal = FirstInst->getOperand(0);
33   Value *RHSVal = FirstInst->getOperand(1);
34 
35   Type *LHSType = LHSVal->getType();
36   Type *RHSType = RHSVal->getType();
37 
38   bool isNUW = false, isNSW = false, isExact = false;
39   if (OverflowingBinaryOperator *BO =
40         dyn_cast<OverflowingBinaryOperator>(FirstInst)) {
41     isNUW = BO->hasNoUnsignedWrap();
42     isNSW = BO->hasNoSignedWrap();
43   } else if (PossiblyExactOperator *PEO =
44                dyn_cast<PossiblyExactOperator>(FirstInst))
45     isExact = PEO->isExact();
46 
47   // Scan to see if all operands are the same opcode, and all have one use.
48   for (unsigned i = 1; i != PN.getNumIncomingValues(); ++i) {
49     Instruction *I = dyn_cast<Instruction>(PN.getIncomingValue(i));
50     if (!I || I->getOpcode() != Opc || !I->hasOneUse() ||
51         // Verify type of the LHS matches so we don't fold cmp's of different
52         // types.
53         I->getOperand(0)->getType() != LHSType ||
54         I->getOperand(1)->getType() != RHSType)
55       return nullptr;
56 
57     // If they are CmpInst instructions, check their predicates
58     if (CmpInst *CI = dyn_cast<CmpInst>(I))
59       if (CI->getPredicate() != cast<CmpInst>(FirstInst)->getPredicate())
60         return nullptr;
61 
62     if (isNUW)
63       isNUW = cast<OverflowingBinaryOperator>(I)->hasNoUnsignedWrap();
64     if (isNSW)
65       isNSW = cast<OverflowingBinaryOperator>(I)->hasNoSignedWrap();
66     if (isExact)
67       isExact = cast<PossiblyExactOperator>(I)->isExact();
68 
69     // Keep track of which operand needs a phi node.
70     if (I->getOperand(0) != LHSVal) LHSVal = nullptr;
71     if (I->getOperand(1) != RHSVal) RHSVal = nullptr;
72   }
73 
74   // If both LHS and RHS would need a PHI, don't do this transformation,
75   // because it would increase the number of PHIs entering the block,
76   // which leads to higher register pressure. This is especially
77   // bad when the PHIs are in the header of a loop.
78   if (!LHSVal && !RHSVal)
79     return nullptr;
80 
81   // Otherwise, this is safe to transform!
82 
83   Value *InLHS = FirstInst->getOperand(0);
84   Value *InRHS = FirstInst->getOperand(1);
85   PHINode *NewLHS = nullptr, *NewRHS = nullptr;
86   if (!LHSVal) {
87     NewLHS = PHINode::Create(LHSType, PN.getNumIncomingValues(),
88                              FirstInst->getOperand(0)->getName() + ".pn");
89     NewLHS->addIncoming(InLHS, PN.getIncomingBlock(0));
90     InsertNewInstBefore(NewLHS, PN);
91     LHSVal = NewLHS;
92   }
93 
94   if (!RHSVal) {
95     NewRHS = PHINode::Create(RHSType, PN.getNumIncomingValues(),
96                              FirstInst->getOperand(1)->getName() + ".pn");
97     NewRHS->addIncoming(InRHS, PN.getIncomingBlock(0));
98     InsertNewInstBefore(NewRHS, PN);
99     RHSVal = NewRHS;
100   }
101 
102   // Add all operands to the new PHIs.
103   if (NewLHS || NewRHS) {
104     for (unsigned i = 1, e = PN.getNumIncomingValues(); i != e; ++i) {
105       Instruction *InInst = cast<Instruction>(PN.getIncomingValue(i));
106       if (NewLHS) {
107         Value *NewInLHS = InInst->getOperand(0);
108         NewLHS->addIncoming(NewInLHS, PN.getIncomingBlock(i));
109       }
110       if (NewRHS) {
111         Value *NewInRHS = InInst->getOperand(1);
112         NewRHS->addIncoming(NewInRHS, PN.getIncomingBlock(i));
113       }
114     }
115   }
116 
117   if (CmpInst *CIOp = dyn_cast<CmpInst>(FirstInst)) {
118     CmpInst *NewCI = CmpInst::Create(CIOp->getOpcode(), CIOp->getPredicate(),
119                                      LHSVal, RHSVal);
120     NewCI->setDebugLoc(FirstInst->getDebugLoc());
121     return NewCI;
122   }
123 
124   BinaryOperator *BinOp = cast<BinaryOperator>(FirstInst);
125   BinaryOperator *NewBinOp =
126     BinaryOperator::Create(BinOp->getOpcode(), LHSVal, RHSVal);
127   if (isNUW) NewBinOp->setHasNoUnsignedWrap();
128   if (isNSW) NewBinOp->setHasNoSignedWrap();
129   if (isExact) NewBinOp->setIsExact();
130   NewBinOp->setDebugLoc(FirstInst->getDebugLoc());
131   return NewBinOp;
132 }
133 
134 Instruction *InstCombiner::FoldPHIArgGEPIntoPHI(PHINode &PN) {
135   GetElementPtrInst *FirstInst =cast<GetElementPtrInst>(PN.getIncomingValue(0));
136 
137   SmallVector<Value*, 16> FixedOperands(FirstInst->op_begin(),
138                                         FirstInst->op_end());
139   // This is true if all GEP bases are allocas and if all indices into them are
140   // constants.
141   bool AllBasePointersAreAllocas = true;
142 
143   // We don't want to replace this phi if the replacement would require
144   // more than one phi, which leads to higher register pressure. This is
145   // especially bad when the PHIs are in the header of a loop.
146   bool NeededPhi = false;
147 
148   bool AllInBounds = true;
149 
150   // Scan to see if all operands are the same opcode, and all have one use.
151   for (unsigned i = 1; i != PN.getNumIncomingValues(); ++i) {
152     GetElementPtrInst *GEP= dyn_cast<GetElementPtrInst>(PN.getIncomingValue(i));
153     if (!GEP || !GEP->hasOneUse() || GEP->getType() != FirstInst->getType() ||
154       GEP->getNumOperands() != FirstInst->getNumOperands())
155       return nullptr;
156 
157     AllInBounds &= GEP->isInBounds();
158 
159     // Keep track of whether or not all GEPs are of alloca pointers.
160     if (AllBasePointersAreAllocas &&
161         (!isa<AllocaInst>(GEP->getOperand(0)) ||
162          !GEP->hasAllConstantIndices()))
163       AllBasePointersAreAllocas = false;
164 
165     // Compare the operand lists.
166     for (unsigned op = 0, e = FirstInst->getNumOperands(); op != e; ++op) {
167       if (FirstInst->getOperand(op) == GEP->getOperand(op))
168         continue;
169 
170       // Don't merge two GEPs when two operands differ (introducing phi nodes)
171       // if one of the PHIs has a constant for the index.  The index may be
172       // substantially cheaper to compute for the constants, so making it a
173       // variable index could pessimize the path.  This also handles the case
174       // for struct indices, which must always be constant.
175       if (isa<ConstantInt>(FirstInst->getOperand(op)) ||
176           isa<ConstantInt>(GEP->getOperand(op)))
177         return nullptr;
178 
179       if (FirstInst->getOperand(op)->getType() !=GEP->getOperand(op)->getType())
180         return nullptr;
181 
182       // If we already needed a PHI for an earlier operand, and another operand
183       // also requires a PHI, we'd be introducing more PHIs than we're
184       // eliminating, which increases register pressure on entry to the PHI's
185       // block.
186       if (NeededPhi)
187         return nullptr;
188 
189       FixedOperands[op] = nullptr;  // Needs a PHI.
190       NeededPhi = true;
191     }
192   }
193 
194   // If all of the base pointers of the PHI'd GEPs are from allocas, don't
195   // bother doing this transformation.  At best, this will just save a bit of
196   // offset calculation, but all the predecessors will have to materialize the
197   // stack address into a register anyway.  We'd actually rather *clone* the
198   // load up into the predecessors so that we have a load of a gep of an alloca,
199   // which can usually all be folded into the load.
200   if (AllBasePointersAreAllocas)
201     return nullptr;
202 
203   // Otherwise, this is safe to transform.  Insert PHI nodes for each operand
204   // that is variable.
205   SmallVector<PHINode*, 16> OperandPhis(FixedOperands.size());
206 
207   bool HasAnyPHIs = false;
208   for (unsigned i = 0, e = FixedOperands.size(); i != e; ++i) {
209     if (FixedOperands[i]) continue;  // operand doesn't need a phi.
210     Value *FirstOp = FirstInst->getOperand(i);
211     PHINode *NewPN = PHINode::Create(FirstOp->getType(), e,
212                                      FirstOp->getName()+".pn");
213     InsertNewInstBefore(NewPN, PN);
214 
215     NewPN->addIncoming(FirstOp, PN.getIncomingBlock(0));
216     OperandPhis[i] = NewPN;
217     FixedOperands[i] = NewPN;
218     HasAnyPHIs = true;
219   }
220 
221 
222   // Add all operands to the new PHIs.
223   if (HasAnyPHIs) {
224     for (unsigned i = 1, e = PN.getNumIncomingValues(); i != e; ++i) {
225       GetElementPtrInst *InGEP =cast<GetElementPtrInst>(PN.getIncomingValue(i));
226       BasicBlock *InBB = PN.getIncomingBlock(i);
227 
228       for (unsigned op = 0, e = OperandPhis.size(); op != e; ++op)
229         if (PHINode *OpPhi = OperandPhis[op])
230           OpPhi->addIncoming(InGEP->getOperand(op), InBB);
231     }
232   }
233 
234   Value *Base = FixedOperands[0];
235   GetElementPtrInst *NewGEP =
236       GetElementPtrInst::Create(FirstInst->getSourceElementType(), Base,
237                                 makeArrayRef(FixedOperands).slice(1));
238   if (AllInBounds) NewGEP->setIsInBounds();
239   NewGEP->setDebugLoc(FirstInst->getDebugLoc());
240   return NewGEP;
241 }
242 
243 
244 /// Return true if we know that it is safe to sink the load out of the block
245 /// that defines it. This means that it must be obvious the value of the load is
246 /// not changed from the point of the load to the end of the block it is in.
247 ///
248 /// Finally, it is safe, but not profitable, to sink a load targeting a
249 /// non-address-taken alloca.  Doing so will cause us to not promote the alloca
250 /// to a register.
251 static bool isSafeAndProfitableToSinkLoad(LoadInst *L) {
252   BasicBlock::iterator BBI = L->getIterator(), E = L->getParent()->end();
253 
254   for (++BBI; BBI != E; ++BBI)
255     if (BBI->mayWriteToMemory())
256       return false;
257 
258   // Check for non-address taken alloca.  If not address-taken already, it isn't
259   // profitable to do this xform.
260   if (AllocaInst *AI = dyn_cast<AllocaInst>(L->getOperand(0))) {
261     bool isAddressTaken = false;
262     for (User *U : AI->users()) {
263       if (isa<LoadInst>(U)) continue;
264       if (StoreInst *SI = dyn_cast<StoreInst>(U)) {
265         // If storing TO the alloca, then the address isn't taken.
266         if (SI->getOperand(1) == AI) continue;
267       }
268       isAddressTaken = true;
269       break;
270     }
271 
272     if (!isAddressTaken && AI->isStaticAlloca())
273       return false;
274   }
275 
276   // If this load is a load from a GEP with a constant offset from an alloca,
277   // then we don't want to sink it.  In its present form, it will be
278   // load [constant stack offset].  Sinking it will cause us to have to
279   // materialize the stack addresses in each predecessor in a register only to
280   // do a shared load from register in the successor.
281   if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(L->getOperand(0)))
282     if (AllocaInst *AI = dyn_cast<AllocaInst>(GEP->getOperand(0)))
283       if (AI->isStaticAlloca() && GEP->hasAllConstantIndices())
284         return false;
285 
286   return true;
287 }
288 
289 Instruction *InstCombiner::FoldPHIArgLoadIntoPHI(PHINode &PN) {
290   LoadInst *FirstLI = cast<LoadInst>(PN.getIncomingValue(0));
291 
292   // FIXME: This is overconservative; this transform is allowed in some cases
293   // for atomic operations.
294   if (FirstLI->isAtomic())
295     return nullptr;
296 
297   // When processing loads, we need to propagate two bits of information to the
298   // sunk load: whether it is volatile, and what its alignment is.  We currently
299   // don't sink loads when some have their alignment specified and some don't.
300   // visitLoadInst will propagate an alignment onto the load when TD is around,
301   // and if TD isn't around, we can't handle the mixed case.
302   bool isVolatile = FirstLI->isVolatile();
303   unsigned LoadAlignment = FirstLI->getAlignment();
304   unsigned LoadAddrSpace = FirstLI->getPointerAddressSpace();
305 
306   // We can't sink the load if the loaded value could be modified between the
307   // load and the PHI.
308   if (FirstLI->getParent() != PN.getIncomingBlock(0) ||
309       !isSafeAndProfitableToSinkLoad(FirstLI))
310     return nullptr;
311 
312   // If the PHI is of volatile loads and the load block has multiple
313   // successors, sinking it would remove a load of the volatile value from
314   // the path through the other successor.
315   if (isVolatile &&
316       FirstLI->getParent()->getTerminator()->getNumSuccessors() != 1)
317     return nullptr;
318 
319   // Check to see if all arguments are the same operation.
320   for (unsigned i = 1, e = PN.getNumIncomingValues(); i != e; ++i) {
321     LoadInst *LI = dyn_cast<LoadInst>(PN.getIncomingValue(i));
322     if (!LI || !LI->hasOneUse())
323       return nullptr;
324 
325     // We can't sink the load if the loaded value could be modified between
326     // the load and the PHI.
327     if (LI->isVolatile() != isVolatile ||
328         LI->getParent() != PN.getIncomingBlock(i) ||
329         LI->getPointerAddressSpace() != LoadAddrSpace ||
330         !isSafeAndProfitableToSinkLoad(LI))
331       return nullptr;
332 
333     // If some of the loads have an alignment specified but not all of them,
334     // we can't do the transformation.
335     if ((LoadAlignment != 0) != (LI->getAlignment() != 0))
336       return nullptr;
337 
338     LoadAlignment = std::min(LoadAlignment, LI->getAlignment());
339 
340     // If the PHI is of volatile loads and the load block has multiple
341     // successors, sinking it would remove a load of the volatile value from
342     // the path through the other successor.
343     if (isVolatile &&
344         LI->getParent()->getTerminator()->getNumSuccessors() != 1)
345       return nullptr;
346   }
347 
348   // Okay, they are all the same operation.  Create a new PHI node of the
349   // correct type, and PHI together all of the LHS's of the instructions.
350   PHINode *NewPN = PHINode::Create(FirstLI->getOperand(0)->getType(),
351                                    PN.getNumIncomingValues(),
352                                    PN.getName()+".in");
353 
354   Value *InVal = FirstLI->getOperand(0);
355   NewPN->addIncoming(InVal, PN.getIncomingBlock(0));
356   LoadInst *NewLI = new LoadInst(NewPN, "", isVolatile, LoadAlignment);
357 
358   unsigned KnownIDs[] = {
359     LLVMContext::MD_tbaa,
360     LLVMContext::MD_range,
361     LLVMContext::MD_invariant_load,
362     LLVMContext::MD_alias_scope,
363     LLVMContext::MD_noalias,
364     LLVMContext::MD_nonnull,
365     LLVMContext::MD_align,
366     LLVMContext::MD_dereferenceable,
367     LLVMContext::MD_dereferenceable_or_null,
368   };
369 
370   for (unsigned ID : KnownIDs)
371     NewLI->setMetadata(ID, FirstLI->getMetadata(ID));
372 
373   // Add all operands to the new PHI and combine TBAA metadata.
374   for (unsigned i = 1, e = PN.getNumIncomingValues(); i != e; ++i) {
375     LoadInst *LI = cast<LoadInst>(PN.getIncomingValue(i));
376     combineMetadata(NewLI, LI, KnownIDs);
377     Value *NewInVal = LI->getOperand(0);
378     if (NewInVal != InVal)
379       InVal = nullptr;
380     NewPN->addIncoming(NewInVal, PN.getIncomingBlock(i));
381   }
382 
383   if (InVal) {
384     // The new PHI unions all of the same values together.  This is really
385     // common, so we handle it intelligently here for compile-time speed.
386     NewLI->setOperand(0, InVal);
387     delete NewPN;
388   } else {
389     InsertNewInstBefore(NewPN, PN);
390   }
391 
392   // If this was a volatile load that we are merging, make sure to loop through
393   // and mark all the input loads as non-volatile.  If we don't do this, we will
394   // insert a new volatile load and the old ones will not be deletable.
395   if (isVolatile)
396     for (Value *IncValue : PN.incoming_values())
397       cast<LoadInst>(IncValue)->setVolatile(false);
398 
399   NewLI->setDebugLoc(FirstLI->getDebugLoc());
400   return NewLI;
401 }
402 
403 /// TODO: This function could handle other cast types, but then it might
404 /// require special-casing a cast from the 'i1' type. See the comment in
405 /// FoldPHIArgOpIntoPHI() about pessimizing illegal integer types.
406 Instruction *InstCombiner::FoldPHIArgZextsIntoPHI(PHINode &Phi) {
407   // We cannot create a new instruction after the PHI if the terminator is an
408   // EHPad because there is no valid insertion point.
409   if (TerminatorInst *TI = Phi.getParent()->getTerminator())
410     if (TI->isEHPad())
411       return nullptr;
412 
413   // Early exit for the common case of a phi with two operands. These are
414   // handled elsewhere. See the comment below where we check the count of zexts
415   // and constants for more details.
416   unsigned NumIncomingValues = Phi.getNumIncomingValues();
417   if (NumIncomingValues < 3)
418     return nullptr;
419 
420   // Find the narrower type specified by the first zext.
421   Type *NarrowType = nullptr;
422   for (Value *V : Phi.incoming_values()) {
423     if (auto *Zext = dyn_cast<ZExtInst>(V)) {
424       NarrowType = Zext->getSrcTy();
425       break;
426     }
427   }
428   if (!NarrowType)
429     return nullptr;
430 
431   // Walk the phi operands checking that we only have zexts or constants that
432   // we can shrink for free. Store the new operands for the new phi.
433   SmallVector<Value *, 4> NewIncoming;
434   unsigned NumZexts = 0;
435   unsigned NumConsts = 0;
436   for (Value *V : Phi.incoming_values()) {
437     if (auto *Zext = dyn_cast<ZExtInst>(V)) {
438       // All zexts must be identical and have one use.
439       if (Zext->getSrcTy() != NarrowType || !Zext->hasOneUse())
440         return nullptr;
441       NewIncoming.push_back(Zext->getOperand(0));
442       NumZexts++;
443     } else if (auto *C = dyn_cast<Constant>(V)) {
444       // Make sure that constants can fit in the new type.
445       Constant *Trunc = ConstantExpr::getTrunc(C, NarrowType);
446       if (ConstantExpr::getZExt(Trunc, C->getType()) != C)
447         return nullptr;
448       NewIncoming.push_back(Trunc);
449       NumConsts++;
450     } else {
451       // If it's not a cast or a constant, bail out.
452       return nullptr;
453     }
454   }
455 
456   // The more common cases of a phi with no constant operands or just one
457   // variable operand are handled by FoldPHIArgOpIntoPHI() and FoldOpIntoPhi()
458   // respectively. FoldOpIntoPhi() wants to do the opposite transform that is
459   // performed here. It tries to replicate a cast in the phi operand's basic
460   // block to expose other folding opportunities. Thus, InstCombine will
461   // infinite loop without this check.
462   if (NumConsts == 0 || NumZexts < 2)
463     return nullptr;
464 
465   // All incoming values are zexts or constants that are safe to truncate.
466   // Create a new phi node of the narrow type, phi together all of the new
467   // operands, and zext the result back to the original type.
468   PHINode *NewPhi = PHINode::Create(NarrowType, NumIncomingValues,
469                                     Phi.getName() + ".shrunk");
470   for (unsigned i = 0; i != NumIncomingValues; ++i)
471     NewPhi->addIncoming(NewIncoming[i], Phi.getIncomingBlock(i));
472 
473   InsertNewInstBefore(NewPhi, Phi);
474   return CastInst::CreateZExtOrBitCast(NewPhi, Phi.getType());
475 }
476 
477 /// If all operands to a PHI node are the same "unary" operator and they all are
478 /// only used by the PHI, PHI together their inputs, and do the operation once,
479 /// to the result of the PHI.
480 Instruction *InstCombiner::FoldPHIArgOpIntoPHI(PHINode &PN) {
481   // We cannot create a new instruction after the PHI if the terminator is an
482   // EHPad because there is no valid insertion point.
483   if (TerminatorInst *TI = PN.getParent()->getTerminator())
484     if (TI->isEHPad())
485       return nullptr;
486 
487   Instruction *FirstInst = cast<Instruction>(PN.getIncomingValue(0));
488 
489   if (isa<GetElementPtrInst>(FirstInst))
490     return FoldPHIArgGEPIntoPHI(PN);
491   if (isa<LoadInst>(FirstInst))
492     return FoldPHIArgLoadIntoPHI(PN);
493 
494   // Scan the instruction, looking for input operations that can be folded away.
495   // If all input operands to the phi are the same instruction (e.g. a cast from
496   // the same type or "+42") we can pull the operation through the PHI, reducing
497   // code size and simplifying code.
498   Constant *ConstantOp = nullptr;
499   Type *CastSrcTy = nullptr;
500   bool isNUW = false, isNSW = false, isExact = false;
501 
502   if (isa<CastInst>(FirstInst)) {
503     CastSrcTy = FirstInst->getOperand(0)->getType();
504 
505     // Be careful about transforming integer PHIs.  We don't want to pessimize
506     // the code by turning an i32 into an i1293.
507     if (PN.getType()->isIntegerTy() && CastSrcTy->isIntegerTy()) {
508       if (!ShouldChangeType(PN.getType(), CastSrcTy))
509         return nullptr;
510     }
511   } else if (isa<BinaryOperator>(FirstInst) || isa<CmpInst>(FirstInst)) {
512     // Can fold binop, compare or shift here if the RHS is a constant,
513     // otherwise call FoldPHIArgBinOpIntoPHI.
514     ConstantOp = dyn_cast<Constant>(FirstInst->getOperand(1));
515     if (!ConstantOp)
516       return FoldPHIArgBinOpIntoPHI(PN);
517 
518     if (OverflowingBinaryOperator *BO =
519         dyn_cast<OverflowingBinaryOperator>(FirstInst)) {
520       isNUW = BO->hasNoUnsignedWrap();
521       isNSW = BO->hasNoSignedWrap();
522     } else if (PossiblyExactOperator *PEO =
523                dyn_cast<PossiblyExactOperator>(FirstInst))
524       isExact = PEO->isExact();
525   } else {
526     return nullptr;  // Cannot fold this operation.
527   }
528 
529   // Check to see if all arguments are the same operation.
530   for (unsigned i = 1, e = PN.getNumIncomingValues(); i != e; ++i) {
531     Instruction *I = dyn_cast<Instruction>(PN.getIncomingValue(i));
532     if (!I || !I->hasOneUse() || !I->isSameOperationAs(FirstInst))
533       return nullptr;
534     if (CastSrcTy) {
535       if (I->getOperand(0)->getType() != CastSrcTy)
536         return nullptr;  // Cast operation must match.
537     } else if (I->getOperand(1) != ConstantOp) {
538       return nullptr;
539     }
540 
541     if (isNUW)
542       isNUW = cast<OverflowingBinaryOperator>(I)->hasNoUnsignedWrap();
543     if (isNSW)
544       isNSW = cast<OverflowingBinaryOperator>(I)->hasNoSignedWrap();
545     if (isExact)
546       isExact = cast<PossiblyExactOperator>(I)->isExact();
547   }
548 
549   // Okay, they are all the same operation.  Create a new PHI node of the
550   // correct type, and PHI together all of the LHS's of the instructions.
551   PHINode *NewPN = PHINode::Create(FirstInst->getOperand(0)->getType(),
552                                    PN.getNumIncomingValues(),
553                                    PN.getName()+".in");
554 
555   Value *InVal = FirstInst->getOperand(0);
556   NewPN->addIncoming(InVal, PN.getIncomingBlock(0));
557 
558   // Add all operands to the new PHI.
559   for (unsigned i = 1, e = PN.getNumIncomingValues(); i != e; ++i) {
560     Value *NewInVal = cast<Instruction>(PN.getIncomingValue(i))->getOperand(0);
561     if (NewInVal != InVal)
562       InVal = nullptr;
563     NewPN->addIncoming(NewInVal, PN.getIncomingBlock(i));
564   }
565 
566   Value *PhiVal;
567   if (InVal) {
568     // The new PHI unions all of the same values together.  This is really
569     // common, so we handle it intelligently here for compile-time speed.
570     PhiVal = InVal;
571     delete NewPN;
572   } else {
573     InsertNewInstBefore(NewPN, PN);
574     PhiVal = NewPN;
575   }
576 
577   // Insert and return the new operation.
578   if (CastInst *FirstCI = dyn_cast<CastInst>(FirstInst)) {
579     CastInst *NewCI = CastInst::Create(FirstCI->getOpcode(), PhiVal,
580                                        PN.getType());
581     NewCI->setDebugLoc(FirstInst->getDebugLoc());
582     return NewCI;
583   }
584 
585   if (BinaryOperator *BinOp = dyn_cast<BinaryOperator>(FirstInst)) {
586     BinOp = BinaryOperator::Create(BinOp->getOpcode(), PhiVal, ConstantOp);
587     if (isNUW) BinOp->setHasNoUnsignedWrap();
588     if (isNSW) BinOp->setHasNoSignedWrap();
589     if (isExact) BinOp->setIsExact();
590     BinOp->setDebugLoc(FirstInst->getDebugLoc());
591     return BinOp;
592   }
593 
594   CmpInst *CIOp = cast<CmpInst>(FirstInst);
595   CmpInst *NewCI = CmpInst::Create(CIOp->getOpcode(), CIOp->getPredicate(),
596                                    PhiVal, ConstantOp);
597   NewCI->setDebugLoc(FirstInst->getDebugLoc());
598   return NewCI;
599 }
600 
601 /// Return true if this PHI node is only used by a PHI node cycle that is dead.
602 static bool DeadPHICycle(PHINode *PN,
603                          SmallPtrSetImpl<PHINode*> &PotentiallyDeadPHIs) {
604   if (PN->use_empty()) return true;
605   if (!PN->hasOneUse()) return false;
606 
607   // Remember this node, and if we find the cycle, return.
608   if (!PotentiallyDeadPHIs.insert(PN).second)
609     return true;
610 
611   // Don't scan crazily complex things.
612   if (PotentiallyDeadPHIs.size() == 16)
613     return false;
614 
615   if (PHINode *PU = dyn_cast<PHINode>(PN->user_back()))
616     return DeadPHICycle(PU, PotentiallyDeadPHIs);
617 
618   return false;
619 }
620 
621 /// Return true if this phi node is always equal to NonPhiInVal.
622 /// This happens with mutually cyclic phi nodes like:
623 ///   z = some value; x = phi (y, z); y = phi (x, z)
624 static bool PHIsEqualValue(PHINode *PN, Value *NonPhiInVal,
625                            SmallPtrSetImpl<PHINode*> &ValueEqualPHIs) {
626   // See if we already saw this PHI node.
627   if (!ValueEqualPHIs.insert(PN).second)
628     return true;
629 
630   // Don't scan crazily complex things.
631   if (ValueEqualPHIs.size() == 16)
632     return false;
633 
634   // Scan the operands to see if they are either phi nodes or are equal to
635   // the value.
636   for (Value *Op : PN->incoming_values()) {
637     if (PHINode *OpPN = dyn_cast<PHINode>(Op)) {
638       if (!PHIsEqualValue(OpPN, NonPhiInVal, ValueEqualPHIs))
639         return false;
640     } else if (Op != NonPhiInVal)
641       return false;
642   }
643 
644   return true;
645 }
646 
647 /// Return an existing non-zero constant if this phi node has one, otherwise
648 /// return constant 1.
649 static ConstantInt *GetAnyNonZeroConstInt(PHINode &PN) {
650   assert(isa<IntegerType>(PN.getType()) && "Expect only intger type phi");
651   for (Value *V : PN.operands())
652     if (auto *ConstVA = dyn_cast<ConstantInt>(V))
653       if (!ConstVA->isZeroValue())
654         return ConstVA;
655   return ConstantInt::get(cast<IntegerType>(PN.getType()), 1);
656 }
657 
658 namespace {
659 struct PHIUsageRecord {
660   unsigned PHIId;     // The ID # of the PHI (something determinstic to sort on)
661   unsigned Shift;     // The amount shifted.
662   Instruction *Inst;  // The trunc instruction.
663 
664   PHIUsageRecord(unsigned pn, unsigned Sh, Instruction *User)
665     : PHIId(pn), Shift(Sh), Inst(User) {}
666 
667   bool operator<(const PHIUsageRecord &RHS) const {
668     if (PHIId < RHS.PHIId) return true;
669     if (PHIId > RHS.PHIId) return false;
670     if (Shift < RHS.Shift) return true;
671     if (Shift > RHS.Shift) return false;
672     return Inst->getType()->getPrimitiveSizeInBits() <
673            RHS.Inst->getType()->getPrimitiveSizeInBits();
674   }
675 };
676 
677 struct LoweredPHIRecord {
678   PHINode *PN;        // The PHI that was lowered.
679   unsigned Shift;     // The amount shifted.
680   unsigned Width;     // The width extracted.
681 
682   LoweredPHIRecord(PHINode *pn, unsigned Sh, Type *Ty)
683     : PN(pn), Shift(Sh), Width(Ty->getPrimitiveSizeInBits()) {}
684 
685   // Ctor form used by DenseMap.
686   LoweredPHIRecord(PHINode *pn, unsigned Sh)
687     : PN(pn), Shift(Sh), Width(0) {}
688 };
689 }
690 
691 namespace llvm {
692   template<>
693   struct DenseMapInfo<LoweredPHIRecord> {
694     static inline LoweredPHIRecord getEmptyKey() {
695       return LoweredPHIRecord(nullptr, 0);
696     }
697     static inline LoweredPHIRecord getTombstoneKey() {
698       return LoweredPHIRecord(nullptr, 1);
699     }
700     static unsigned getHashValue(const LoweredPHIRecord &Val) {
701       return DenseMapInfo<PHINode*>::getHashValue(Val.PN) ^ (Val.Shift>>3) ^
702              (Val.Width>>3);
703     }
704     static bool isEqual(const LoweredPHIRecord &LHS,
705                         const LoweredPHIRecord &RHS) {
706       return LHS.PN == RHS.PN && LHS.Shift == RHS.Shift &&
707              LHS.Width == RHS.Width;
708     }
709   };
710 }
711 
712 
713 /// This is an integer PHI and we know that it has an illegal type: see if it is
714 /// only used by trunc or trunc(lshr) operations. If so, we split the PHI into
715 /// the various pieces being extracted. This sort of thing is introduced when
716 /// SROA promotes an aggregate to large integer values.
717 ///
718 /// TODO: The user of the trunc may be an bitcast to float/double/vector or an
719 /// inttoptr.  We should produce new PHIs in the right type.
720 ///
721 Instruction *InstCombiner::SliceUpIllegalIntegerPHI(PHINode &FirstPhi) {
722   // PHIUsers - Keep track of all of the truncated values extracted from a set
723   // of PHIs, along with their offset.  These are the things we want to rewrite.
724   SmallVector<PHIUsageRecord, 16> PHIUsers;
725 
726   // PHIs are often mutually cyclic, so we keep track of a whole set of PHI
727   // nodes which are extracted from. PHIsToSlice is a set we use to avoid
728   // revisiting PHIs, PHIsInspected is a ordered list of PHIs that we need to
729   // check the uses of (to ensure they are all extracts).
730   SmallVector<PHINode*, 8> PHIsToSlice;
731   SmallPtrSet<PHINode*, 8> PHIsInspected;
732 
733   PHIsToSlice.push_back(&FirstPhi);
734   PHIsInspected.insert(&FirstPhi);
735 
736   for (unsigned PHIId = 0; PHIId != PHIsToSlice.size(); ++PHIId) {
737     PHINode *PN = PHIsToSlice[PHIId];
738 
739     // Scan the input list of the PHI.  If any input is an invoke, and if the
740     // input is defined in the predecessor, then we won't be split the critical
741     // edge which is required to insert a truncate.  Because of this, we have to
742     // bail out.
743     for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) {
744       InvokeInst *II = dyn_cast<InvokeInst>(PN->getIncomingValue(i));
745       if (!II) continue;
746       if (II->getParent() != PN->getIncomingBlock(i))
747         continue;
748 
749       // If we have a phi, and if it's directly in the predecessor, then we have
750       // a critical edge where we need to put the truncate.  Since we can't
751       // split the edge in instcombine, we have to bail out.
752       return nullptr;
753     }
754 
755     for (User *U : PN->users()) {
756       Instruction *UserI = cast<Instruction>(U);
757 
758       // If the user is a PHI, inspect its uses recursively.
759       if (PHINode *UserPN = dyn_cast<PHINode>(UserI)) {
760         if (PHIsInspected.insert(UserPN).second)
761           PHIsToSlice.push_back(UserPN);
762         continue;
763       }
764 
765       // Truncates are always ok.
766       if (isa<TruncInst>(UserI)) {
767         PHIUsers.push_back(PHIUsageRecord(PHIId, 0, UserI));
768         continue;
769       }
770 
771       // Otherwise it must be a lshr which can only be used by one trunc.
772       if (UserI->getOpcode() != Instruction::LShr ||
773           !UserI->hasOneUse() || !isa<TruncInst>(UserI->user_back()) ||
774           !isa<ConstantInt>(UserI->getOperand(1)))
775         return nullptr;
776 
777       unsigned Shift = cast<ConstantInt>(UserI->getOperand(1))->getZExtValue();
778       PHIUsers.push_back(PHIUsageRecord(PHIId, Shift, UserI->user_back()));
779     }
780   }
781 
782   // If we have no users, they must be all self uses, just nuke the PHI.
783   if (PHIUsers.empty())
784     return replaceInstUsesWith(FirstPhi, UndefValue::get(FirstPhi.getType()));
785 
786   // If this phi node is transformable, create new PHIs for all the pieces
787   // extracted out of it.  First, sort the users by their offset and size.
788   array_pod_sort(PHIUsers.begin(), PHIUsers.end());
789 
790   DEBUG(dbgs() << "SLICING UP PHI: " << FirstPhi << '\n';
791         for (unsigned i = 1, e = PHIsToSlice.size(); i != e; ++i)
792           dbgs() << "AND USER PHI #" << i << ": " << *PHIsToSlice[i] << '\n';
793     );
794 
795   // PredValues - This is a temporary used when rewriting PHI nodes.  It is
796   // hoisted out here to avoid construction/destruction thrashing.
797   DenseMap<BasicBlock*, Value*> PredValues;
798 
799   // ExtractedVals - Each new PHI we introduce is saved here so we don't
800   // introduce redundant PHIs.
801   DenseMap<LoweredPHIRecord, PHINode*> ExtractedVals;
802 
803   for (unsigned UserI = 0, UserE = PHIUsers.size(); UserI != UserE; ++UserI) {
804     unsigned PHIId = PHIUsers[UserI].PHIId;
805     PHINode *PN = PHIsToSlice[PHIId];
806     unsigned Offset = PHIUsers[UserI].Shift;
807     Type *Ty = PHIUsers[UserI].Inst->getType();
808 
809     PHINode *EltPHI;
810 
811     // If we've already lowered a user like this, reuse the previously lowered
812     // value.
813     if ((EltPHI = ExtractedVals[LoweredPHIRecord(PN, Offset, Ty)]) == nullptr) {
814 
815       // Otherwise, Create the new PHI node for this user.
816       EltPHI = PHINode::Create(Ty, PN->getNumIncomingValues(),
817                                PN->getName()+".off"+Twine(Offset), PN);
818       assert(EltPHI->getType() != PN->getType() &&
819              "Truncate didn't shrink phi?");
820 
821       for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) {
822         BasicBlock *Pred = PN->getIncomingBlock(i);
823         Value *&PredVal = PredValues[Pred];
824 
825         // If we already have a value for this predecessor, reuse it.
826         if (PredVal) {
827           EltPHI->addIncoming(PredVal, Pred);
828           continue;
829         }
830 
831         // Handle the PHI self-reuse case.
832         Value *InVal = PN->getIncomingValue(i);
833         if (InVal == PN) {
834           PredVal = EltPHI;
835           EltPHI->addIncoming(PredVal, Pred);
836           continue;
837         }
838 
839         if (PHINode *InPHI = dyn_cast<PHINode>(PN)) {
840           // If the incoming value was a PHI, and if it was one of the PHIs we
841           // already rewrote it, just use the lowered value.
842           if (Value *Res = ExtractedVals[LoweredPHIRecord(InPHI, Offset, Ty)]) {
843             PredVal = Res;
844             EltPHI->addIncoming(PredVal, Pred);
845             continue;
846           }
847         }
848 
849         // Otherwise, do an extract in the predecessor.
850         Builder->SetInsertPoint(Pred->getTerminator());
851         Value *Res = InVal;
852         if (Offset)
853           Res = Builder->CreateLShr(Res, ConstantInt::get(InVal->getType(),
854                                                           Offset), "extract");
855         Res = Builder->CreateTrunc(Res, Ty, "extract.t");
856         PredVal = Res;
857         EltPHI->addIncoming(Res, Pred);
858 
859         // If the incoming value was a PHI, and if it was one of the PHIs we are
860         // rewriting, we will ultimately delete the code we inserted.  This
861         // means we need to revisit that PHI to make sure we extract out the
862         // needed piece.
863         if (PHINode *OldInVal = dyn_cast<PHINode>(PN->getIncomingValue(i)))
864           if (PHIsInspected.count(OldInVal)) {
865             unsigned RefPHIId = std::find(PHIsToSlice.begin(),PHIsToSlice.end(),
866                                           OldInVal)-PHIsToSlice.begin();
867             PHIUsers.push_back(PHIUsageRecord(RefPHIId, Offset,
868                                               cast<Instruction>(Res)));
869             ++UserE;
870           }
871       }
872       PredValues.clear();
873 
874       DEBUG(dbgs() << "  Made element PHI for offset " << Offset << ": "
875                    << *EltPHI << '\n');
876       ExtractedVals[LoweredPHIRecord(PN, Offset, Ty)] = EltPHI;
877     }
878 
879     // Replace the use of this piece with the PHI node.
880     replaceInstUsesWith(*PHIUsers[UserI].Inst, EltPHI);
881   }
882 
883   // Replace all the remaining uses of the PHI nodes (self uses and the lshrs)
884   // with undefs.
885   Value *Undef = UndefValue::get(FirstPhi.getType());
886   for (unsigned i = 1, e = PHIsToSlice.size(); i != e; ++i)
887     replaceInstUsesWith(*PHIsToSlice[i], Undef);
888   return replaceInstUsesWith(FirstPhi, Undef);
889 }
890 
891 // PHINode simplification
892 //
893 Instruction *InstCombiner::visitPHINode(PHINode &PN) {
894   if (Value *V = SimplifyInstruction(&PN, DL, TLI, DT, AC))
895     return replaceInstUsesWith(PN, V);
896 
897   if (Instruction *Result = FoldPHIArgZextsIntoPHI(PN))
898     return Result;
899 
900   // If all PHI operands are the same operation, pull them through the PHI,
901   // reducing code size.
902   if (isa<Instruction>(PN.getIncomingValue(0)) &&
903       isa<Instruction>(PN.getIncomingValue(1)) &&
904       cast<Instruction>(PN.getIncomingValue(0))->getOpcode() ==
905       cast<Instruction>(PN.getIncomingValue(1))->getOpcode() &&
906       // FIXME: The hasOneUse check will fail for PHIs that use the value more
907       // than themselves more than once.
908       PN.getIncomingValue(0)->hasOneUse())
909     if (Instruction *Result = FoldPHIArgOpIntoPHI(PN))
910       return Result;
911 
912   // If this is a trivial cycle in the PHI node graph, remove it.  Basically, if
913   // this PHI only has a single use (a PHI), and if that PHI only has one use (a
914   // PHI)... break the cycle.
915   if (PN.hasOneUse()) {
916     Instruction *PHIUser = cast<Instruction>(PN.user_back());
917     if (PHINode *PU = dyn_cast<PHINode>(PHIUser)) {
918       SmallPtrSet<PHINode*, 16> PotentiallyDeadPHIs;
919       PotentiallyDeadPHIs.insert(&PN);
920       if (DeadPHICycle(PU, PotentiallyDeadPHIs))
921         return replaceInstUsesWith(PN, UndefValue::get(PN.getType()));
922     }
923 
924     // If this phi has a single use, and if that use just computes a value for
925     // the next iteration of a loop, delete the phi.  This occurs with unused
926     // induction variables, e.g. "for (int j = 0; ; ++j);".  Detecting this
927     // common case here is good because the only other things that catch this
928     // are induction variable analysis (sometimes) and ADCE, which is only run
929     // late.
930     if (PHIUser->hasOneUse() &&
931         (isa<BinaryOperator>(PHIUser) || isa<GetElementPtrInst>(PHIUser)) &&
932         PHIUser->user_back() == &PN) {
933       return replaceInstUsesWith(PN, UndefValue::get(PN.getType()));
934     }
935     // When a PHI is used only to be compared with zero, it is safe to replace
936     // an incoming value proved as known nonzero with any non-zero constant.
937     // For example, in the code below, the incoming value %v can be replaced
938     // with any non-zero constant based on the fact that the PHI is only used to
939     // be compared with zero and %v is a known non-zero value:
940     // %v = select %cond, 1, 2
941     // %p = phi [%v, BB] ...
942     //      icmp eq, %p, 0
943     auto *CmpInst = dyn_cast<ICmpInst>(PHIUser);
944     // FIXME: To be simple, handle only integer type for now.
945     if (CmpInst && isa<IntegerType>(PN.getType()) && CmpInst->isEquality() &&
946         match(CmpInst->getOperand(1), m_Zero())) {
947       ConstantInt *NonZeroConst = nullptr;
948       for (unsigned i = 0, e = PN.getNumIncomingValues(); i != e; ++i) {
949         Instruction *CtxI = PN.getIncomingBlock(i)->getTerminator();
950         Value *VA = PN.getIncomingValue(i);
951         if (isKnownNonZero(VA, DL, 0, AC, CtxI, DT)) {
952           if (!NonZeroConst)
953             NonZeroConst = GetAnyNonZeroConstInt(PN);
954           PN.setIncomingValue(i, NonZeroConst);
955         }
956       }
957     }
958   }
959 
960   // We sometimes end up with phi cycles that non-obviously end up being the
961   // same value, for example:
962   //   z = some value; x = phi (y, z); y = phi (x, z)
963   // where the phi nodes don't necessarily need to be in the same block.  Do a
964   // quick check to see if the PHI node only contains a single non-phi value, if
965   // so, scan to see if the phi cycle is actually equal to that value.
966   {
967     unsigned InValNo = 0, NumIncomingVals = PN.getNumIncomingValues();
968     // Scan for the first non-phi operand.
969     while (InValNo != NumIncomingVals &&
970            isa<PHINode>(PN.getIncomingValue(InValNo)))
971       ++InValNo;
972 
973     if (InValNo != NumIncomingVals) {
974       Value *NonPhiInVal = PN.getIncomingValue(InValNo);
975 
976       // Scan the rest of the operands to see if there are any conflicts, if so
977       // there is no need to recursively scan other phis.
978       for (++InValNo; InValNo != NumIncomingVals; ++InValNo) {
979         Value *OpVal = PN.getIncomingValue(InValNo);
980         if (OpVal != NonPhiInVal && !isa<PHINode>(OpVal))
981           break;
982       }
983 
984       // If we scanned over all operands, then we have one unique value plus
985       // phi values.  Scan PHI nodes to see if they all merge in each other or
986       // the value.
987       if (InValNo == NumIncomingVals) {
988         SmallPtrSet<PHINode*, 16> ValueEqualPHIs;
989         if (PHIsEqualValue(&PN, NonPhiInVal, ValueEqualPHIs))
990           return replaceInstUsesWith(PN, NonPhiInVal);
991       }
992     }
993   }
994 
995   // If there are multiple PHIs, sort their operands so that they all list
996   // the blocks in the same order. This will help identical PHIs be eliminated
997   // by other passes. Other passes shouldn't depend on this for correctness
998   // however.
999   PHINode *FirstPN = cast<PHINode>(PN.getParent()->begin());
1000   if (&PN != FirstPN)
1001     for (unsigned i = 0, e = FirstPN->getNumIncomingValues(); i != e; ++i) {
1002       BasicBlock *BBA = PN.getIncomingBlock(i);
1003       BasicBlock *BBB = FirstPN->getIncomingBlock(i);
1004       if (BBA != BBB) {
1005         Value *VA = PN.getIncomingValue(i);
1006         unsigned j = PN.getBasicBlockIndex(BBB);
1007         Value *VB = PN.getIncomingValue(j);
1008         PN.setIncomingBlock(i, BBB);
1009         PN.setIncomingValue(i, VB);
1010         PN.setIncomingBlock(j, BBA);
1011         PN.setIncomingValue(j, VA);
1012         // NOTE: Instcombine normally would want us to "return &PN" if we
1013         // modified any of the operands of an instruction.  However, since we
1014         // aren't adding or removing uses (just rearranging them) we don't do
1015         // this in this case.
1016       }
1017     }
1018 
1019   // If this is an integer PHI and we know that it has an illegal type, see if
1020   // it is only used by trunc or trunc(lshr) operations.  If so, we split the
1021   // PHI into the various pieces being extracted.  This sort of thing is
1022   // introduced when SROA promotes an aggregate to a single large integer type.
1023   if (PN.getType()->isIntegerTy() &&
1024       !DL.isLegalInteger(PN.getType()->getPrimitiveSizeInBits()))
1025     if (Instruction *Res = SliceUpIllegalIntegerPHI(PN))
1026       return Res;
1027 
1028   return nullptr;
1029 }
1030