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   MaybeAlign LoadAlignment(FirstLI->getAlignment());
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     // If some of the loads have an alignment specified but not all of them,
588     // we can't do the transformation.
589     if ((LoadAlignment.hasValue()) != (LI->getAlignment() != 0))
590       return nullptr;
591 
592     LoadAlignment = std::min(LoadAlignment, MaybeAlign(LI->getAlignment()));
593 
594     // If the PHI is of volatile loads and the load block has multiple
595     // successors, sinking it would remove a load of the volatile value from
596     // the path through the other successor.
597     if (isVolatile &&
598         LI->getParent()->getTerminator()->getNumSuccessors() != 1)
599       return nullptr;
600   }
601 
602   // Okay, they are all the same operation.  Create a new PHI node of the
603   // correct type, and PHI together all of the LHS's of the instructions.
604   PHINode *NewPN = PHINode::Create(FirstLI->getOperand(0)->getType(),
605                                    PN.getNumIncomingValues(),
606                                    PN.getName()+".in");
607 
608   Value *InVal = FirstLI->getOperand(0);
609   NewPN->addIncoming(InVal, PN.getIncomingBlock(0));
610   LoadInst *NewLI =
611       new LoadInst(FirstLI->getType(), NewPN, "", isVolatile, LoadAlignment);
612 
613   unsigned KnownIDs[] = {
614     LLVMContext::MD_tbaa,
615     LLVMContext::MD_range,
616     LLVMContext::MD_invariant_load,
617     LLVMContext::MD_alias_scope,
618     LLVMContext::MD_noalias,
619     LLVMContext::MD_nonnull,
620     LLVMContext::MD_align,
621     LLVMContext::MD_dereferenceable,
622     LLVMContext::MD_dereferenceable_or_null,
623     LLVMContext::MD_access_group,
624   };
625 
626   for (unsigned ID : KnownIDs)
627     NewLI->setMetadata(ID, FirstLI->getMetadata(ID));
628 
629   // Add all operands to the new PHI and combine TBAA metadata.
630   for (unsigned i = 1, e = PN.getNumIncomingValues(); i != e; ++i) {
631     LoadInst *LI = cast<LoadInst>(PN.getIncomingValue(i));
632     combineMetadata(NewLI, LI, KnownIDs, true);
633     Value *NewInVal = LI->getOperand(0);
634     if (NewInVal != InVal)
635       InVal = nullptr;
636     NewPN->addIncoming(NewInVal, PN.getIncomingBlock(i));
637   }
638 
639   if (InVal) {
640     // The new PHI unions all of the same values together.  This is really
641     // common, so we handle it intelligently here for compile-time speed.
642     NewLI->setOperand(0, InVal);
643     delete NewPN;
644   } else {
645     InsertNewInstBefore(NewPN, PN);
646   }
647 
648   // If this was a volatile load that we are merging, make sure to loop through
649   // and mark all the input loads as non-volatile.  If we don't do this, we will
650   // insert a new volatile load and the old ones will not be deletable.
651   if (isVolatile)
652     for (Value *IncValue : PN.incoming_values())
653       cast<LoadInst>(IncValue)->setVolatile(false);
654 
655   PHIArgMergedDebugLoc(NewLI, PN);
656   return NewLI;
657 }
658 
659 /// TODO: This function could handle other cast types, but then it might
660 /// require special-casing a cast from the 'i1' type. See the comment in
661 /// FoldPHIArgOpIntoPHI() about pessimizing illegal integer types.
662 Instruction *InstCombiner::FoldPHIArgZextsIntoPHI(PHINode &Phi) {
663   // We cannot create a new instruction after the PHI if the terminator is an
664   // EHPad because there is no valid insertion point.
665   if (Instruction *TI = Phi.getParent()->getTerminator())
666     if (TI->isEHPad())
667       return nullptr;
668 
669   // Early exit for the common case of a phi with two operands. These are
670   // handled elsewhere. See the comment below where we check the count of zexts
671   // and constants for more details.
672   unsigned NumIncomingValues = Phi.getNumIncomingValues();
673   if (NumIncomingValues < 3)
674     return nullptr;
675 
676   // Find the narrower type specified by the first zext.
677   Type *NarrowType = nullptr;
678   for (Value *V : Phi.incoming_values()) {
679     if (auto *Zext = dyn_cast<ZExtInst>(V)) {
680       NarrowType = Zext->getSrcTy();
681       break;
682     }
683   }
684   if (!NarrowType)
685     return nullptr;
686 
687   // Walk the phi operands checking that we only have zexts or constants that
688   // we can shrink for free. Store the new operands for the new phi.
689   SmallVector<Value *, 4> NewIncoming;
690   unsigned NumZexts = 0;
691   unsigned NumConsts = 0;
692   for (Value *V : Phi.incoming_values()) {
693     if (auto *Zext = dyn_cast<ZExtInst>(V)) {
694       // All zexts must be identical and have one use.
695       if (Zext->getSrcTy() != NarrowType || !Zext->hasOneUse())
696         return nullptr;
697       NewIncoming.push_back(Zext->getOperand(0));
698       NumZexts++;
699     } else if (auto *C = dyn_cast<Constant>(V)) {
700       // Make sure that constants can fit in the new type.
701       Constant *Trunc = ConstantExpr::getTrunc(C, NarrowType);
702       if (ConstantExpr::getZExt(Trunc, C->getType()) != C)
703         return nullptr;
704       NewIncoming.push_back(Trunc);
705       NumConsts++;
706     } else {
707       // If it's not a cast or a constant, bail out.
708       return nullptr;
709     }
710   }
711 
712   // The more common cases of a phi with no constant operands or just one
713   // variable operand are handled by FoldPHIArgOpIntoPHI() and foldOpIntoPhi()
714   // respectively. foldOpIntoPhi() wants to do the opposite transform that is
715   // performed here. It tries to replicate a cast in the phi operand's basic
716   // block to expose other folding opportunities. Thus, InstCombine will
717   // infinite loop without this check.
718   if (NumConsts == 0 || NumZexts < 2)
719     return nullptr;
720 
721   // All incoming values are zexts or constants that are safe to truncate.
722   // Create a new phi node of the narrow type, phi together all of the new
723   // operands, and zext the result back to the original type.
724   PHINode *NewPhi = PHINode::Create(NarrowType, NumIncomingValues,
725                                     Phi.getName() + ".shrunk");
726   for (unsigned i = 0; i != NumIncomingValues; ++i)
727     NewPhi->addIncoming(NewIncoming[i], Phi.getIncomingBlock(i));
728 
729   InsertNewInstBefore(NewPhi, Phi);
730   return CastInst::CreateZExtOrBitCast(NewPhi, Phi.getType());
731 }
732 
733 /// If all operands to a PHI node are the same "unary" operator and they all are
734 /// only used by the PHI, PHI together their inputs, and do the operation once,
735 /// to the result of the PHI.
736 Instruction *InstCombiner::FoldPHIArgOpIntoPHI(PHINode &PN) {
737   // We cannot create a new instruction after the PHI if the terminator is an
738   // EHPad because there is no valid insertion point.
739   if (Instruction *TI = PN.getParent()->getTerminator())
740     if (TI->isEHPad())
741       return nullptr;
742 
743   Instruction *FirstInst = cast<Instruction>(PN.getIncomingValue(0));
744 
745   if (isa<GetElementPtrInst>(FirstInst))
746     return FoldPHIArgGEPIntoPHI(PN);
747   if (isa<LoadInst>(FirstInst))
748     return FoldPHIArgLoadIntoPHI(PN);
749 
750   // Scan the instruction, looking for input operations that can be folded away.
751   // If all input operands to the phi are the same instruction (e.g. a cast from
752   // the same type or "+42") we can pull the operation through the PHI, reducing
753   // code size and simplifying code.
754   Constant *ConstantOp = nullptr;
755   Type *CastSrcTy = nullptr;
756 
757   if (isa<CastInst>(FirstInst)) {
758     CastSrcTy = FirstInst->getOperand(0)->getType();
759 
760     // Be careful about transforming integer PHIs.  We don't want to pessimize
761     // the code by turning an i32 into an i1293.
762     if (PN.getType()->isIntegerTy() && CastSrcTy->isIntegerTy()) {
763       if (!shouldChangeType(PN.getType(), CastSrcTy))
764         return nullptr;
765     }
766   } else if (isa<BinaryOperator>(FirstInst) || isa<CmpInst>(FirstInst)) {
767     // Can fold binop, compare or shift here if the RHS is a constant,
768     // otherwise call FoldPHIArgBinOpIntoPHI.
769     ConstantOp = dyn_cast<Constant>(FirstInst->getOperand(1));
770     if (!ConstantOp)
771       return FoldPHIArgBinOpIntoPHI(PN);
772   } else {
773     return nullptr;  // Cannot fold this operation.
774   }
775 
776   // Check to see if all arguments are the same operation.
777   for (unsigned i = 1, e = PN.getNumIncomingValues(); i != e; ++i) {
778     Instruction *I = dyn_cast<Instruction>(PN.getIncomingValue(i));
779     if (!I || !I->hasOneUse() || !I->isSameOperationAs(FirstInst))
780       return nullptr;
781     if (CastSrcTy) {
782       if (I->getOperand(0)->getType() != CastSrcTy)
783         return nullptr;  // Cast operation must match.
784     } else if (I->getOperand(1) != ConstantOp) {
785       return nullptr;
786     }
787   }
788 
789   // Okay, they are all the same operation.  Create a new PHI node of the
790   // correct type, and PHI together all of the LHS's of the instructions.
791   PHINode *NewPN = PHINode::Create(FirstInst->getOperand(0)->getType(),
792                                    PN.getNumIncomingValues(),
793                                    PN.getName()+".in");
794 
795   Value *InVal = FirstInst->getOperand(0);
796   NewPN->addIncoming(InVal, PN.getIncomingBlock(0));
797 
798   // Add all operands to the new PHI.
799   for (unsigned i = 1, e = PN.getNumIncomingValues(); i != e; ++i) {
800     Value *NewInVal = cast<Instruction>(PN.getIncomingValue(i))->getOperand(0);
801     if (NewInVal != InVal)
802       InVal = nullptr;
803     NewPN->addIncoming(NewInVal, PN.getIncomingBlock(i));
804   }
805 
806   Value *PhiVal;
807   if (InVal) {
808     // The new PHI unions all of the same values together.  This is really
809     // common, so we handle it intelligently here for compile-time speed.
810     PhiVal = InVal;
811     delete NewPN;
812   } else {
813     InsertNewInstBefore(NewPN, PN);
814     PhiVal = NewPN;
815   }
816 
817   // Insert and return the new operation.
818   if (CastInst *FirstCI = dyn_cast<CastInst>(FirstInst)) {
819     CastInst *NewCI = CastInst::Create(FirstCI->getOpcode(), PhiVal,
820                                        PN.getType());
821     PHIArgMergedDebugLoc(NewCI, PN);
822     return NewCI;
823   }
824 
825   if (BinaryOperator *BinOp = dyn_cast<BinaryOperator>(FirstInst)) {
826     BinOp = BinaryOperator::Create(BinOp->getOpcode(), PhiVal, ConstantOp);
827     BinOp->copyIRFlags(PN.getIncomingValue(0));
828 
829     for (unsigned i = 1, e = PN.getNumIncomingValues(); i != e; ++i)
830       BinOp->andIRFlags(PN.getIncomingValue(i));
831 
832     PHIArgMergedDebugLoc(BinOp, PN);
833     return BinOp;
834   }
835 
836   CmpInst *CIOp = cast<CmpInst>(FirstInst);
837   CmpInst *NewCI = CmpInst::Create(CIOp->getOpcode(), CIOp->getPredicate(),
838                                    PhiVal, ConstantOp);
839   PHIArgMergedDebugLoc(NewCI, PN);
840   return NewCI;
841 }
842 
843 /// Return true if this PHI node is only used by a PHI node cycle that is dead.
844 static bool DeadPHICycle(PHINode *PN,
845                          SmallPtrSetImpl<PHINode*> &PotentiallyDeadPHIs) {
846   if (PN->use_empty()) return true;
847   if (!PN->hasOneUse()) return false;
848 
849   // Remember this node, and if we find the cycle, return.
850   if (!PotentiallyDeadPHIs.insert(PN).second)
851     return true;
852 
853   // Don't scan crazily complex things.
854   if (PotentiallyDeadPHIs.size() == 16)
855     return false;
856 
857   if (PHINode *PU = dyn_cast<PHINode>(PN->user_back()))
858     return DeadPHICycle(PU, PotentiallyDeadPHIs);
859 
860   return false;
861 }
862 
863 /// Return true if this phi node is always equal to NonPhiInVal.
864 /// This happens with mutually cyclic phi nodes like:
865 ///   z = some value; x = phi (y, z); y = phi (x, z)
866 static bool PHIsEqualValue(PHINode *PN, Value *NonPhiInVal,
867                            SmallPtrSetImpl<PHINode*> &ValueEqualPHIs) {
868   // See if we already saw this PHI node.
869   if (!ValueEqualPHIs.insert(PN).second)
870     return true;
871 
872   // Don't scan crazily complex things.
873   if (ValueEqualPHIs.size() == 16)
874     return false;
875 
876   // Scan the operands to see if they are either phi nodes or are equal to
877   // the value.
878   for (Value *Op : PN->incoming_values()) {
879     if (PHINode *OpPN = dyn_cast<PHINode>(Op)) {
880       if (!PHIsEqualValue(OpPN, NonPhiInVal, ValueEqualPHIs))
881         return false;
882     } else if (Op != NonPhiInVal)
883       return false;
884   }
885 
886   return true;
887 }
888 
889 /// Return an existing non-zero constant if this phi node has one, otherwise
890 /// return constant 1.
891 static ConstantInt *GetAnyNonZeroConstInt(PHINode &PN) {
892   assert(isa<IntegerType>(PN.getType()) && "Expect only integer type phi");
893   for (Value *V : PN.operands())
894     if (auto *ConstVA = dyn_cast<ConstantInt>(V))
895       if (!ConstVA->isZero())
896         return ConstVA;
897   return ConstantInt::get(cast<IntegerType>(PN.getType()), 1);
898 }
899 
900 namespace {
901 struct PHIUsageRecord {
902   unsigned PHIId;     // The ID # of the PHI (something determinstic to sort on)
903   unsigned Shift;     // The amount shifted.
904   Instruction *Inst;  // The trunc instruction.
905 
906   PHIUsageRecord(unsigned pn, unsigned Sh, Instruction *User)
907     : PHIId(pn), Shift(Sh), Inst(User) {}
908 
909   bool operator<(const PHIUsageRecord &RHS) const {
910     if (PHIId < RHS.PHIId) return true;
911     if (PHIId > RHS.PHIId) return false;
912     if (Shift < RHS.Shift) return true;
913     if (Shift > RHS.Shift) return false;
914     return Inst->getType()->getPrimitiveSizeInBits() <
915            RHS.Inst->getType()->getPrimitiveSizeInBits();
916   }
917 };
918 
919 struct LoweredPHIRecord {
920   PHINode *PN;        // The PHI that was lowered.
921   unsigned Shift;     // The amount shifted.
922   unsigned Width;     // The width extracted.
923 
924   LoweredPHIRecord(PHINode *pn, unsigned Sh, Type *Ty)
925     : PN(pn), Shift(Sh), Width(Ty->getPrimitiveSizeInBits()) {}
926 
927   // Ctor form used by DenseMap.
928   LoweredPHIRecord(PHINode *pn, unsigned Sh)
929     : PN(pn), Shift(Sh), Width(0) {}
930 };
931 }
932 
933 namespace llvm {
934   template<>
935   struct DenseMapInfo<LoweredPHIRecord> {
936     static inline LoweredPHIRecord getEmptyKey() {
937       return LoweredPHIRecord(nullptr, 0);
938     }
939     static inline LoweredPHIRecord getTombstoneKey() {
940       return LoweredPHIRecord(nullptr, 1);
941     }
942     static unsigned getHashValue(const LoweredPHIRecord &Val) {
943       return DenseMapInfo<PHINode*>::getHashValue(Val.PN) ^ (Val.Shift>>3) ^
944              (Val.Width>>3);
945     }
946     static bool isEqual(const LoweredPHIRecord &LHS,
947                         const LoweredPHIRecord &RHS) {
948       return LHS.PN == RHS.PN && LHS.Shift == RHS.Shift &&
949              LHS.Width == RHS.Width;
950     }
951   };
952 }
953 
954 
955 /// This is an integer PHI and we know that it has an illegal type: see if it is
956 /// only used by trunc or trunc(lshr) operations. If so, we split the PHI into
957 /// the various pieces being extracted. This sort of thing is introduced when
958 /// SROA promotes an aggregate to large integer values.
959 ///
960 /// TODO: The user of the trunc may be an bitcast to float/double/vector or an
961 /// inttoptr.  We should produce new PHIs in the right type.
962 ///
963 Instruction *InstCombiner::SliceUpIllegalIntegerPHI(PHINode &FirstPhi) {
964   // PHIUsers - Keep track of all of the truncated values extracted from a set
965   // of PHIs, along with their offset.  These are the things we want to rewrite.
966   SmallVector<PHIUsageRecord, 16> PHIUsers;
967 
968   // PHIs are often mutually cyclic, so we keep track of a whole set of PHI
969   // nodes which are extracted from. PHIsToSlice is a set we use to avoid
970   // revisiting PHIs, PHIsInspected is a ordered list of PHIs that we need to
971   // check the uses of (to ensure they are all extracts).
972   SmallVector<PHINode*, 8> PHIsToSlice;
973   SmallPtrSet<PHINode*, 8> PHIsInspected;
974 
975   PHIsToSlice.push_back(&FirstPhi);
976   PHIsInspected.insert(&FirstPhi);
977 
978   for (unsigned PHIId = 0; PHIId != PHIsToSlice.size(); ++PHIId) {
979     PHINode *PN = PHIsToSlice[PHIId];
980 
981     // Scan the input list of the PHI.  If any input is an invoke, and if the
982     // input is defined in the predecessor, then we won't be split the critical
983     // edge which is required to insert a truncate.  Because of this, we have to
984     // bail out.
985     for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) {
986       InvokeInst *II = dyn_cast<InvokeInst>(PN->getIncomingValue(i));
987       if (!II) continue;
988       if (II->getParent() != PN->getIncomingBlock(i))
989         continue;
990 
991       // If we have a phi, and if it's directly in the predecessor, then we have
992       // a critical edge where we need to put the truncate.  Since we can't
993       // split the edge in instcombine, we have to bail out.
994       return nullptr;
995     }
996 
997     for (User *U : PN->users()) {
998       Instruction *UserI = cast<Instruction>(U);
999 
1000       // If the user is a PHI, inspect its uses recursively.
1001       if (PHINode *UserPN = dyn_cast<PHINode>(UserI)) {
1002         if (PHIsInspected.insert(UserPN).second)
1003           PHIsToSlice.push_back(UserPN);
1004         continue;
1005       }
1006 
1007       // Truncates are always ok.
1008       if (isa<TruncInst>(UserI)) {
1009         PHIUsers.push_back(PHIUsageRecord(PHIId, 0, UserI));
1010         continue;
1011       }
1012 
1013       // Otherwise it must be a lshr which can only be used by one trunc.
1014       if (UserI->getOpcode() != Instruction::LShr ||
1015           !UserI->hasOneUse() || !isa<TruncInst>(UserI->user_back()) ||
1016           !isa<ConstantInt>(UserI->getOperand(1)))
1017         return nullptr;
1018 
1019       // Bail on out of range shifts.
1020       unsigned SizeInBits = UserI->getType()->getScalarSizeInBits();
1021       if (cast<ConstantInt>(UserI->getOperand(1))->getValue().uge(SizeInBits))
1022         return nullptr;
1023 
1024       unsigned Shift = cast<ConstantInt>(UserI->getOperand(1))->getZExtValue();
1025       PHIUsers.push_back(PHIUsageRecord(PHIId, Shift, UserI->user_back()));
1026     }
1027   }
1028 
1029   // If we have no users, they must be all self uses, just nuke the PHI.
1030   if (PHIUsers.empty())
1031     return replaceInstUsesWith(FirstPhi, UndefValue::get(FirstPhi.getType()));
1032 
1033   // If this phi node is transformable, create new PHIs for all the pieces
1034   // extracted out of it.  First, sort the users by their offset and size.
1035   array_pod_sort(PHIUsers.begin(), PHIUsers.end());
1036 
1037   LLVM_DEBUG(dbgs() << "SLICING UP PHI: " << FirstPhi << '\n';
1038              for (unsigned i = 1, e = PHIsToSlice.size(); i != e; ++i) dbgs()
1039              << "AND USER PHI #" << i << ": " << *PHIsToSlice[i] << '\n';);
1040 
1041   // PredValues - This is a temporary used when rewriting PHI nodes.  It is
1042   // hoisted out here to avoid construction/destruction thrashing.
1043   DenseMap<BasicBlock*, Value*> PredValues;
1044 
1045   // ExtractedVals - Each new PHI we introduce is saved here so we don't
1046   // introduce redundant PHIs.
1047   DenseMap<LoweredPHIRecord, PHINode*> ExtractedVals;
1048 
1049   for (unsigned UserI = 0, UserE = PHIUsers.size(); UserI != UserE; ++UserI) {
1050     unsigned PHIId = PHIUsers[UserI].PHIId;
1051     PHINode *PN = PHIsToSlice[PHIId];
1052     unsigned Offset = PHIUsers[UserI].Shift;
1053     Type *Ty = PHIUsers[UserI].Inst->getType();
1054 
1055     PHINode *EltPHI;
1056 
1057     // If we've already lowered a user like this, reuse the previously lowered
1058     // value.
1059     if ((EltPHI = ExtractedVals[LoweredPHIRecord(PN, Offset, Ty)]) == nullptr) {
1060 
1061       // Otherwise, Create the new PHI node for this user.
1062       EltPHI = PHINode::Create(Ty, PN->getNumIncomingValues(),
1063                                PN->getName()+".off"+Twine(Offset), PN);
1064       assert(EltPHI->getType() != PN->getType() &&
1065              "Truncate didn't shrink phi?");
1066 
1067       for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) {
1068         BasicBlock *Pred = PN->getIncomingBlock(i);
1069         Value *&PredVal = PredValues[Pred];
1070 
1071         // If we already have a value for this predecessor, reuse it.
1072         if (PredVal) {
1073           EltPHI->addIncoming(PredVal, Pred);
1074           continue;
1075         }
1076 
1077         // Handle the PHI self-reuse case.
1078         Value *InVal = PN->getIncomingValue(i);
1079         if (InVal == PN) {
1080           PredVal = EltPHI;
1081           EltPHI->addIncoming(PredVal, Pred);
1082           continue;
1083         }
1084 
1085         if (PHINode *InPHI = dyn_cast<PHINode>(PN)) {
1086           // If the incoming value was a PHI, and if it was one of the PHIs we
1087           // already rewrote it, just use the lowered value.
1088           if (Value *Res = ExtractedVals[LoweredPHIRecord(InPHI, Offset, Ty)]) {
1089             PredVal = Res;
1090             EltPHI->addIncoming(PredVal, Pred);
1091             continue;
1092           }
1093         }
1094 
1095         // Otherwise, do an extract in the predecessor.
1096         Builder.SetInsertPoint(Pred->getTerminator());
1097         Value *Res = InVal;
1098         if (Offset)
1099           Res = Builder.CreateLShr(Res, ConstantInt::get(InVal->getType(),
1100                                                           Offset), "extract");
1101         Res = Builder.CreateTrunc(Res, Ty, "extract.t");
1102         PredVal = Res;
1103         EltPHI->addIncoming(Res, Pred);
1104 
1105         // If the incoming value was a PHI, and if it was one of the PHIs we are
1106         // rewriting, we will ultimately delete the code we inserted.  This
1107         // means we need to revisit that PHI to make sure we extract out the
1108         // needed piece.
1109         if (PHINode *OldInVal = dyn_cast<PHINode>(PN->getIncomingValue(i)))
1110           if (PHIsInspected.count(OldInVal)) {
1111             unsigned RefPHIId =
1112                 find(PHIsToSlice, OldInVal) - PHIsToSlice.begin();
1113             PHIUsers.push_back(PHIUsageRecord(RefPHIId, Offset,
1114                                               cast<Instruction>(Res)));
1115             ++UserE;
1116           }
1117       }
1118       PredValues.clear();
1119 
1120       LLVM_DEBUG(dbgs() << "  Made element PHI for offset " << Offset << ": "
1121                         << *EltPHI << '\n');
1122       ExtractedVals[LoweredPHIRecord(PN, Offset, Ty)] = EltPHI;
1123     }
1124 
1125     // Replace the use of this piece with the PHI node.
1126     replaceInstUsesWith(*PHIUsers[UserI].Inst, EltPHI);
1127   }
1128 
1129   // Replace all the remaining uses of the PHI nodes (self uses and the lshrs)
1130   // with undefs.
1131   Value *Undef = UndefValue::get(FirstPhi.getType());
1132   for (unsigned i = 1, e = PHIsToSlice.size(); i != e; ++i)
1133     replaceInstUsesWith(*PHIsToSlice[i], Undef);
1134   return replaceInstUsesWith(FirstPhi, Undef);
1135 }
1136 
1137 // PHINode simplification
1138 //
1139 Instruction *InstCombiner::visitPHINode(PHINode &PN) {
1140   if (Value *V = SimplifyInstruction(&PN, SQ.getWithInstruction(&PN)))
1141     return replaceInstUsesWith(PN, V);
1142 
1143   if (Instruction *Result = FoldPHIArgZextsIntoPHI(PN))
1144     return Result;
1145 
1146   // If all PHI operands are the same operation, pull them through the PHI,
1147   // reducing code size.
1148   if (isa<Instruction>(PN.getIncomingValue(0)) &&
1149       isa<Instruction>(PN.getIncomingValue(1)) &&
1150       cast<Instruction>(PN.getIncomingValue(0))->getOpcode() ==
1151       cast<Instruction>(PN.getIncomingValue(1))->getOpcode() &&
1152       // FIXME: The hasOneUse check will fail for PHIs that use the value more
1153       // than themselves more than once.
1154       PN.getIncomingValue(0)->hasOneUse())
1155     if (Instruction *Result = FoldPHIArgOpIntoPHI(PN))
1156       return Result;
1157 
1158   // If this is a trivial cycle in the PHI node graph, remove it.  Basically, if
1159   // this PHI only has a single use (a PHI), and if that PHI only has one use (a
1160   // PHI)... break the cycle.
1161   if (PN.hasOneUse()) {
1162     if (Instruction *Result = FoldIntegerTypedPHI(PN))
1163       return Result;
1164 
1165     Instruction *PHIUser = cast<Instruction>(PN.user_back());
1166     if (PHINode *PU = dyn_cast<PHINode>(PHIUser)) {
1167       SmallPtrSet<PHINode*, 16> PotentiallyDeadPHIs;
1168       PotentiallyDeadPHIs.insert(&PN);
1169       if (DeadPHICycle(PU, PotentiallyDeadPHIs))
1170         return replaceInstUsesWith(PN, UndefValue::get(PN.getType()));
1171     }
1172 
1173     // If this phi has a single use, and if that use just computes a value for
1174     // the next iteration of a loop, delete the phi.  This occurs with unused
1175     // induction variables, e.g. "for (int j = 0; ; ++j);".  Detecting this
1176     // common case here is good because the only other things that catch this
1177     // are induction variable analysis (sometimes) and ADCE, which is only run
1178     // late.
1179     if (PHIUser->hasOneUse() &&
1180         (isa<BinaryOperator>(PHIUser) || isa<GetElementPtrInst>(PHIUser)) &&
1181         PHIUser->user_back() == &PN) {
1182       return replaceInstUsesWith(PN, UndefValue::get(PN.getType()));
1183     }
1184     // When a PHI is used only to be compared with zero, it is safe to replace
1185     // an incoming value proved as known nonzero with any non-zero constant.
1186     // For example, in the code below, the incoming value %v can be replaced
1187     // with any non-zero constant based on the fact that the PHI is only used to
1188     // be compared with zero and %v is a known non-zero value:
1189     // %v = select %cond, 1, 2
1190     // %p = phi [%v, BB] ...
1191     //      icmp eq, %p, 0
1192     auto *CmpInst = dyn_cast<ICmpInst>(PHIUser);
1193     // FIXME: To be simple, handle only integer type for now.
1194     if (CmpInst && isa<IntegerType>(PN.getType()) && CmpInst->isEquality() &&
1195         match(CmpInst->getOperand(1), m_Zero())) {
1196       ConstantInt *NonZeroConst = nullptr;
1197       for (unsigned i = 0, e = PN.getNumIncomingValues(); i != e; ++i) {
1198         Instruction *CtxI = PN.getIncomingBlock(i)->getTerminator();
1199         Value *VA = PN.getIncomingValue(i);
1200         if (isKnownNonZero(VA, DL, 0, &AC, CtxI, &DT)) {
1201           if (!NonZeroConst)
1202             NonZeroConst = GetAnyNonZeroConstInt(PN);
1203           PN.setIncomingValue(i, NonZeroConst);
1204         }
1205       }
1206     }
1207   }
1208 
1209   // We sometimes end up with phi cycles that non-obviously end up being the
1210   // same value, for example:
1211   //   z = some value; x = phi (y, z); y = phi (x, z)
1212   // where the phi nodes don't necessarily need to be in the same block.  Do a
1213   // quick check to see if the PHI node only contains a single non-phi value, if
1214   // so, scan to see if the phi cycle is actually equal to that value.
1215   {
1216     unsigned InValNo = 0, NumIncomingVals = PN.getNumIncomingValues();
1217     // Scan for the first non-phi operand.
1218     while (InValNo != NumIncomingVals &&
1219            isa<PHINode>(PN.getIncomingValue(InValNo)))
1220       ++InValNo;
1221 
1222     if (InValNo != NumIncomingVals) {
1223       Value *NonPhiInVal = PN.getIncomingValue(InValNo);
1224 
1225       // Scan the rest of the operands to see if there are any conflicts, if so
1226       // there is no need to recursively scan other phis.
1227       for (++InValNo; InValNo != NumIncomingVals; ++InValNo) {
1228         Value *OpVal = PN.getIncomingValue(InValNo);
1229         if (OpVal != NonPhiInVal && !isa<PHINode>(OpVal))
1230           break;
1231       }
1232 
1233       // If we scanned over all operands, then we have one unique value plus
1234       // phi values.  Scan PHI nodes to see if they all merge in each other or
1235       // the value.
1236       if (InValNo == NumIncomingVals) {
1237         SmallPtrSet<PHINode*, 16> ValueEqualPHIs;
1238         if (PHIsEqualValue(&PN, NonPhiInVal, ValueEqualPHIs))
1239           return replaceInstUsesWith(PN, NonPhiInVal);
1240       }
1241     }
1242   }
1243 
1244   // If there are multiple PHIs, sort their operands so that they all list
1245   // the blocks in the same order. This will help identical PHIs be eliminated
1246   // by other passes. Other passes shouldn't depend on this for correctness
1247   // however.
1248   PHINode *FirstPN = cast<PHINode>(PN.getParent()->begin());
1249   if (&PN != FirstPN)
1250     for (unsigned i = 0, e = FirstPN->getNumIncomingValues(); i != e; ++i) {
1251       BasicBlock *BBA = PN.getIncomingBlock(i);
1252       BasicBlock *BBB = FirstPN->getIncomingBlock(i);
1253       if (BBA != BBB) {
1254         Value *VA = PN.getIncomingValue(i);
1255         unsigned j = PN.getBasicBlockIndex(BBB);
1256         Value *VB = PN.getIncomingValue(j);
1257         PN.setIncomingBlock(i, BBB);
1258         PN.setIncomingValue(i, VB);
1259         PN.setIncomingBlock(j, BBA);
1260         PN.setIncomingValue(j, VA);
1261         // NOTE: Instcombine normally would want us to "return &PN" if we
1262         // modified any of the operands of an instruction.  However, since we
1263         // aren't adding or removing uses (just rearranging them) we don't do
1264         // this in this case.
1265       }
1266     }
1267 
1268   // If this is an integer PHI and we know that it has an illegal type, see if
1269   // it is only used by trunc or trunc(lshr) operations.  If so, we split the
1270   // PHI into the various pieces being extracted.  This sort of thing is
1271   // introduced when SROA promotes an aggregate to a single large integer type.
1272   if (PN.getType()->isIntegerTy() &&
1273       !DL.isLegalInteger(PN.getType()->getPrimitiveSizeInBits()))
1274     if (Instruction *Res = SliceUpIllegalIntegerPHI(PN))
1275       return Res;
1276 
1277   return nullptr;
1278 }
1279