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