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