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