10b57cec5SDimitry Andric //===- InstCombinePHI.cpp -------------------------------------------------===//
20b57cec5SDimitry Andric //
30b57cec5SDimitry Andric // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
40b57cec5SDimitry Andric // See https://llvm.org/LICENSE.txt for license information.
50b57cec5SDimitry Andric // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
60b57cec5SDimitry Andric //
70b57cec5SDimitry Andric //===----------------------------------------------------------------------===//
80b57cec5SDimitry Andric //
90b57cec5SDimitry Andric // This file implements the visitPHINode function.
100b57cec5SDimitry Andric //
110b57cec5SDimitry Andric //===----------------------------------------------------------------------===//
120b57cec5SDimitry Andric
130b57cec5SDimitry Andric #include "InstCombineInternal.h"
140b57cec5SDimitry Andric #include "llvm/ADT/STLExtras.h"
150b57cec5SDimitry Andric #include "llvm/ADT/SmallPtrSet.h"
16e8d8bef9SDimitry Andric #include "llvm/ADT/Statistic.h"
170b57cec5SDimitry Andric #include "llvm/Analysis/InstructionSimplify.h"
180b57cec5SDimitry Andric #include "llvm/Analysis/ValueTracking.h"
190b57cec5SDimitry Andric #include "llvm/IR/PatternMatch.h"
20480093f4SDimitry Andric #include "llvm/Support/CommandLine.h"
21e8d8bef9SDimitry Andric #include "llvm/Transforms/InstCombine/InstCombiner.h"
22480093f4SDimitry Andric #include "llvm/Transforms/Utils/Local.h"
23bdd1243dSDimitry Andric #include <optional>
24e8d8bef9SDimitry Andric
250b57cec5SDimitry Andric using namespace llvm;
260b57cec5SDimitry Andric using namespace llvm::PatternMatch;
270b57cec5SDimitry Andric
280b57cec5SDimitry Andric #define DEBUG_TYPE "instcombine"
290b57cec5SDimitry Andric
300b57cec5SDimitry Andric static cl::opt<unsigned>
310b57cec5SDimitry Andric MaxNumPhis("instcombine-max-num-phis", cl::init(512),
320b57cec5SDimitry Andric cl::desc("Maximum number phis to handle in intptr/ptrint folding"));
330b57cec5SDimitry Andric
34e8d8bef9SDimitry Andric STATISTIC(NumPHIsOfInsertValues,
35e8d8bef9SDimitry Andric "Number of phi-of-insertvalue turned into insertvalue-of-phis");
36e8d8bef9SDimitry Andric STATISTIC(NumPHIsOfExtractValues,
37e8d8bef9SDimitry Andric "Number of phi-of-extractvalue turned into extractvalue-of-phi");
38e8d8bef9SDimitry Andric STATISTIC(NumPHICSEs, "Number of PHI's that got CSE'd");
39e8d8bef9SDimitry Andric
400b57cec5SDimitry Andric /// The PHI arguments will be folded into a single operation with a PHI node
410b57cec5SDimitry Andric /// as input. The debug location of the single operation will be the merged
420b57cec5SDimitry Andric /// locations of the original PHI node arguments.
PHIArgMergedDebugLoc(Instruction * Inst,PHINode & PN)43e8d8bef9SDimitry Andric void InstCombinerImpl::PHIArgMergedDebugLoc(Instruction *Inst, PHINode &PN) {
440b57cec5SDimitry Andric auto *FirstInst = cast<Instruction>(PN.getIncomingValue(0));
450b57cec5SDimitry Andric Inst->setDebugLoc(FirstInst->getDebugLoc());
460b57cec5SDimitry Andric // We do not expect a CallInst here, otherwise, N-way merging of DebugLoc
470b57cec5SDimitry Andric // will be inefficient.
480b57cec5SDimitry Andric assert(!isa<CallInst>(Inst));
490b57cec5SDimitry Andric
501fd87a68SDimitry Andric for (Value *V : drop_begin(PN.incoming_values())) {
511fd87a68SDimitry Andric auto *I = cast<Instruction>(V);
520b57cec5SDimitry Andric Inst->applyMergedLocation(Inst->getDebugLoc(), I->getDebugLoc());
530b57cec5SDimitry Andric }
540b57cec5SDimitry Andric }
550b57cec5SDimitry Andric
560b57cec5SDimitry Andric // Replace Integer typed PHI PN if the PHI's value is used as a pointer value.
570b57cec5SDimitry Andric // If there is an existing pointer typed PHI that produces the same value as PN,
580b57cec5SDimitry Andric // replace PN and the IntToPtr operation with it. Otherwise, synthesize a new
590b57cec5SDimitry Andric // PHI node:
600b57cec5SDimitry Andric //
610b57cec5SDimitry Andric // Case-1:
620b57cec5SDimitry Andric // bb1:
630b57cec5SDimitry Andric // int_init = PtrToInt(ptr_init)
640b57cec5SDimitry Andric // br label %bb2
650b57cec5SDimitry Andric // bb2:
660b57cec5SDimitry Andric // int_val = PHI([int_init, %bb1], [int_val_inc, %bb2]
670b57cec5SDimitry Andric // ptr_val = PHI([ptr_init, %bb1], [ptr_val_inc, %bb2]
680b57cec5SDimitry Andric // ptr_val2 = IntToPtr(int_val)
690b57cec5SDimitry Andric // ...
700b57cec5SDimitry Andric // use(ptr_val2)
710b57cec5SDimitry Andric // ptr_val_inc = ...
720b57cec5SDimitry Andric // inc_val_inc = PtrToInt(ptr_val_inc)
730b57cec5SDimitry Andric //
740b57cec5SDimitry Andric // ==>
750b57cec5SDimitry Andric // bb1:
760b57cec5SDimitry Andric // br label %bb2
770b57cec5SDimitry Andric // bb2:
780b57cec5SDimitry Andric // ptr_val = PHI([ptr_init, %bb1], [ptr_val_inc, %bb2]
790b57cec5SDimitry Andric // ...
800b57cec5SDimitry Andric // use(ptr_val)
810b57cec5SDimitry Andric // ptr_val_inc = ...
820b57cec5SDimitry Andric //
830b57cec5SDimitry Andric // Case-2:
840b57cec5SDimitry Andric // bb1:
850b57cec5SDimitry Andric // int_ptr = BitCast(ptr_ptr)
860b57cec5SDimitry Andric // int_init = Load(int_ptr)
870b57cec5SDimitry Andric // br label %bb2
880b57cec5SDimitry Andric // bb2:
890b57cec5SDimitry Andric // int_val = PHI([int_init, %bb1], [int_val_inc, %bb2]
900b57cec5SDimitry Andric // ptr_val2 = IntToPtr(int_val)
910b57cec5SDimitry Andric // ...
920b57cec5SDimitry Andric // use(ptr_val2)
930b57cec5SDimitry Andric // ptr_val_inc = ...
940b57cec5SDimitry Andric // inc_val_inc = PtrToInt(ptr_val_inc)
950b57cec5SDimitry Andric // ==>
960b57cec5SDimitry Andric // bb1:
970b57cec5SDimitry Andric // ptr_init = Load(ptr_ptr)
980b57cec5SDimitry Andric // br label %bb2
990b57cec5SDimitry Andric // bb2:
1000b57cec5SDimitry Andric // ptr_val = PHI([ptr_init, %bb1], [ptr_val_inc, %bb2]
1010b57cec5SDimitry Andric // ...
1020b57cec5SDimitry Andric // use(ptr_val)
1030b57cec5SDimitry Andric // ptr_val_inc = ...
1040b57cec5SDimitry Andric // ...
1050b57cec5SDimitry Andric //
foldIntegerTypedPHI(PHINode & PN)106bdd1243dSDimitry Andric bool InstCombinerImpl::foldIntegerTypedPHI(PHINode &PN) {
1070b57cec5SDimitry Andric if (!PN.getType()->isIntegerTy())
108bdd1243dSDimitry Andric return false;
1090b57cec5SDimitry Andric if (!PN.hasOneUse())
110bdd1243dSDimitry Andric return false;
1110b57cec5SDimitry Andric
1120b57cec5SDimitry Andric auto *IntToPtr = dyn_cast<IntToPtrInst>(PN.user_back());
1130b57cec5SDimitry Andric if (!IntToPtr)
114bdd1243dSDimitry Andric return false;
1150b57cec5SDimitry Andric
1160b57cec5SDimitry Andric // Check if the pointer is actually used as pointer:
1170b57cec5SDimitry Andric auto HasPointerUse = [](Instruction *IIP) {
1180b57cec5SDimitry Andric for (User *U : IIP->users()) {
1190b57cec5SDimitry Andric Value *Ptr = nullptr;
1200b57cec5SDimitry Andric if (LoadInst *LoadI = dyn_cast<LoadInst>(U)) {
1210b57cec5SDimitry Andric Ptr = LoadI->getPointerOperand();
1220b57cec5SDimitry Andric } else if (StoreInst *SI = dyn_cast<StoreInst>(U)) {
1230b57cec5SDimitry Andric Ptr = SI->getPointerOperand();
1240b57cec5SDimitry Andric } else if (GetElementPtrInst *GI = dyn_cast<GetElementPtrInst>(U)) {
1250b57cec5SDimitry Andric Ptr = GI->getPointerOperand();
1260b57cec5SDimitry Andric }
1270b57cec5SDimitry Andric
1280b57cec5SDimitry Andric if (Ptr && Ptr == IIP)
1290b57cec5SDimitry Andric return true;
1300b57cec5SDimitry Andric }
1310b57cec5SDimitry Andric return false;
1320b57cec5SDimitry Andric };
1330b57cec5SDimitry Andric
1340b57cec5SDimitry Andric if (!HasPointerUse(IntToPtr))
135bdd1243dSDimitry Andric return false;
1360b57cec5SDimitry Andric
1370b57cec5SDimitry Andric if (DL.getPointerSizeInBits(IntToPtr->getAddressSpace()) !=
1380b57cec5SDimitry Andric DL.getTypeSizeInBits(IntToPtr->getOperand(0)->getType()))
139bdd1243dSDimitry Andric return false;
1400b57cec5SDimitry Andric
1410b57cec5SDimitry Andric SmallVector<Value *, 4> AvailablePtrVals;
1421fd87a68SDimitry Andric for (auto Incoming : zip(PN.blocks(), PN.incoming_values())) {
1431fd87a68SDimitry Andric BasicBlock *BB = std::get<0>(Incoming);
1441fd87a68SDimitry Andric Value *Arg = std::get<1>(Incoming);
1450b57cec5SDimitry Andric
1460b57cec5SDimitry Andric // First look backward:
1470b57cec5SDimitry Andric if (auto *PI = dyn_cast<PtrToIntInst>(Arg)) {
1480b57cec5SDimitry Andric AvailablePtrVals.emplace_back(PI->getOperand(0));
1490b57cec5SDimitry Andric continue;
1500b57cec5SDimitry Andric }
1510b57cec5SDimitry Andric
1520b57cec5SDimitry Andric // Next look forward:
1530b57cec5SDimitry Andric Value *ArgIntToPtr = nullptr;
1540b57cec5SDimitry Andric for (User *U : Arg->users()) {
1550b57cec5SDimitry Andric if (isa<IntToPtrInst>(U) && U->getType() == IntToPtr->getType() &&
1561fd87a68SDimitry Andric (DT.dominates(cast<Instruction>(U), BB) ||
1571fd87a68SDimitry Andric cast<Instruction>(U)->getParent() == BB)) {
1580b57cec5SDimitry Andric ArgIntToPtr = U;
1590b57cec5SDimitry Andric break;
1600b57cec5SDimitry Andric }
1610b57cec5SDimitry Andric }
1620b57cec5SDimitry Andric
1630b57cec5SDimitry Andric if (ArgIntToPtr) {
1640b57cec5SDimitry Andric AvailablePtrVals.emplace_back(ArgIntToPtr);
1650b57cec5SDimitry Andric continue;
1660b57cec5SDimitry Andric }
1670b57cec5SDimitry Andric
1680b57cec5SDimitry Andric // If Arg is defined by a PHI, allow it. This will also create
1690b57cec5SDimitry Andric // more opportunities iteratively.
1700b57cec5SDimitry Andric if (isa<PHINode>(Arg)) {
1710b57cec5SDimitry Andric AvailablePtrVals.emplace_back(Arg);
1720b57cec5SDimitry Andric continue;
1730b57cec5SDimitry Andric }
1740b57cec5SDimitry Andric
1750b57cec5SDimitry Andric // For a single use integer load:
1760b57cec5SDimitry Andric auto *LoadI = dyn_cast<LoadInst>(Arg);
1770b57cec5SDimitry Andric if (!LoadI)
178bdd1243dSDimitry Andric return false;
1790b57cec5SDimitry Andric
1800b57cec5SDimitry Andric if (!LoadI->hasOneUse())
181bdd1243dSDimitry Andric return false;
1820b57cec5SDimitry Andric
1830b57cec5SDimitry Andric // Push the integer typed Load instruction into the available
1840b57cec5SDimitry Andric // value set, and fix it up later when the pointer typed PHI
1850b57cec5SDimitry Andric // is synthesized.
1860b57cec5SDimitry Andric AvailablePtrVals.emplace_back(LoadI);
1870b57cec5SDimitry Andric }
1880b57cec5SDimitry Andric
1890b57cec5SDimitry Andric // Now search for a matching PHI
1900b57cec5SDimitry Andric auto *BB = PN.getParent();
1910b57cec5SDimitry Andric assert(AvailablePtrVals.size() == PN.getNumIncomingValues() &&
1920b57cec5SDimitry Andric "Not enough available ptr typed incoming values");
1930b57cec5SDimitry Andric PHINode *MatchingPtrPHI = nullptr;
1940b57cec5SDimitry Andric unsigned NumPhis = 0;
1951fd87a68SDimitry Andric for (PHINode &PtrPHI : BB->phis()) {
1960b57cec5SDimitry Andric // FIXME: consider handling this in AggressiveInstCombine
1971fd87a68SDimitry Andric if (NumPhis++ > MaxNumPhis)
198bdd1243dSDimitry Andric return false;
1991fd87a68SDimitry Andric if (&PtrPHI == &PN || PtrPHI.getType() != IntToPtr->getType())
2000b57cec5SDimitry Andric continue;
2011fd87a68SDimitry Andric if (any_of(zip(PN.blocks(), AvailablePtrVals),
2021fd87a68SDimitry Andric [&](const auto &BlockAndValue) {
2031fd87a68SDimitry Andric BasicBlock *BB = std::get<0>(BlockAndValue);
2041fd87a68SDimitry Andric Value *V = std::get<1>(BlockAndValue);
2051fd87a68SDimitry Andric return PtrPHI.getIncomingValueForBlock(BB) != V;
2061fd87a68SDimitry Andric }))
2071fd87a68SDimitry Andric continue;
2081fd87a68SDimitry Andric MatchingPtrPHI = &PtrPHI;
2090b57cec5SDimitry Andric break;
2100b57cec5SDimitry Andric }
2110b57cec5SDimitry Andric
2120b57cec5SDimitry Andric if (MatchingPtrPHI) {
2130b57cec5SDimitry Andric assert(MatchingPtrPHI->getType() == IntToPtr->getType() &&
2140b57cec5SDimitry Andric "Phi's Type does not match with IntToPtr");
215bdd1243dSDimitry Andric // Explicitly replace the inttoptr (rather than inserting a ptrtoint) here,
216bdd1243dSDimitry Andric // to make sure another transform can't undo it in the meantime.
217bdd1243dSDimitry Andric replaceInstUsesWith(*IntToPtr, MatchingPtrPHI);
218bdd1243dSDimitry Andric eraseInstFromFunction(*IntToPtr);
219bdd1243dSDimitry Andric eraseInstFromFunction(PN);
220bdd1243dSDimitry Andric return true;
2210b57cec5SDimitry Andric }
2220b57cec5SDimitry Andric
2230b57cec5SDimitry Andric // If it requires a conversion for every PHI operand, do not do it.
2240b57cec5SDimitry Andric if (all_of(AvailablePtrVals, [&](Value *V) {
2250b57cec5SDimitry Andric return (V->getType() != IntToPtr->getType()) || isa<IntToPtrInst>(V);
2260b57cec5SDimitry Andric }))
227bdd1243dSDimitry Andric return false;
2280b57cec5SDimitry Andric
2290b57cec5SDimitry Andric // If any of the operand that requires casting is a terminator
2308c27c554SDimitry Andric // instruction, do not do it. Similarly, do not do the transform if the value
2318c27c554SDimitry Andric // is PHI in a block with no insertion point, for example, a catchswitch
2328c27c554SDimitry Andric // block, since we will not be able to insert a cast after the PHI.
2330b57cec5SDimitry Andric if (any_of(AvailablePtrVals, [&](Value *V) {
2340b57cec5SDimitry Andric if (V->getType() == IntToPtr->getType())
2350b57cec5SDimitry Andric return false;
2360b57cec5SDimitry Andric auto *Inst = dyn_cast<Instruction>(V);
2378c27c554SDimitry Andric if (!Inst)
2388c27c554SDimitry Andric return false;
2398c27c554SDimitry Andric if (Inst->isTerminator())
2408c27c554SDimitry Andric return true;
2418c27c554SDimitry Andric auto *BB = Inst->getParent();
2428c27c554SDimitry Andric if (isa<PHINode>(Inst) && BB->getFirstInsertionPt() == BB->end())
2438c27c554SDimitry Andric return true;
2448c27c554SDimitry Andric return false;
2450b57cec5SDimitry Andric }))
246bdd1243dSDimitry Andric return false;
2470b57cec5SDimitry Andric
2480b57cec5SDimitry Andric PHINode *NewPtrPHI = PHINode::Create(
2490b57cec5SDimitry Andric IntToPtr->getType(), PN.getNumIncomingValues(), PN.getName() + ".ptr");
2500b57cec5SDimitry Andric
2515f757f3fSDimitry Andric InsertNewInstBefore(NewPtrPHI, PN.getIterator());
2520b57cec5SDimitry Andric SmallDenseMap<Value *, Instruction *> Casts;
2531fd87a68SDimitry Andric for (auto Incoming : zip(PN.blocks(), AvailablePtrVals)) {
2541fd87a68SDimitry Andric auto *IncomingBB = std::get<0>(Incoming);
2551fd87a68SDimitry Andric auto *IncomingVal = std::get<1>(Incoming);
2560b57cec5SDimitry Andric
2570b57cec5SDimitry Andric if (IncomingVal->getType() == IntToPtr->getType()) {
2580b57cec5SDimitry Andric NewPtrPHI->addIncoming(IncomingVal, IncomingBB);
2590b57cec5SDimitry Andric continue;
2600b57cec5SDimitry Andric }
2610b57cec5SDimitry Andric
2620b57cec5SDimitry Andric #ifndef NDEBUG
2630b57cec5SDimitry Andric LoadInst *LoadI = dyn_cast<LoadInst>(IncomingVal);
2640b57cec5SDimitry Andric assert((isa<PHINode>(IncomingVal) ||
2650b57cec5SDimitry Andric IncomingVal->getType()->isPointerTy() ||
2660b57cec5SDimitry Andric (LoadI && LoadI->hasOneUse())) &&
2670b57cec5SDimitry Andric "Can not replace LoadInst with multiple uses");
2680b57cec5SDimitry Andric #endif
2690b57cec5SDimitry Andric // Need to insert a BitCast.
2700b57cec5SDimitry Andric // For an integer Load instruction with a single use, the load + IntToPtr
2710b57cec5SDimitry Andric // cast will be simplified into a pointer load:
2720b57cec5SDimitry Andric // %v = load i64, i64* %a.ip, align 8
2730b57cec5SDimitry Andric // %v.cast = inttoptr i64 %v to float **
2740b57cec5SDimitry Andric // ==>
2750b57cec5SDimitry Andric // %v.ptrp = bitcast i64 * %a.ip to float **
2760b57cec5SDimitry Andric // %v.cast = load float *, float ** %v.ptrp, align 8
2770b57cec5SDimitry Andric Instruction *&CI = Casts[IncomingVal];
2780b57cec5SDimitry Andric if (!CI) {
2790b57cec5SDimitry Andric CI = CastInst::CreateBitOrPointerCast(IncomingVal, IntToPtr->getType(),
2800b57cec5SDimitry Andric IncomingVal->getName() + ".ptr");
2810b57cec5SDimitry Andric if (auto *IncomingI = dyn_cast<Instruction>(IncomingVal)) {
2820b57cec5SDimitry Andric BasicBlock::iterator InsertPos(IncomingI);
2830b57cec5SDimitry Andric InsertPos++;
2848c27c554SDimitry Andric BasicBlock *BB = IncomingI->getParent();
2850b57cec5SDimitry Andric if (isa<PHINode>(IncomingI))
2868c27c554SDimitry Andric InsertPos = BB->getFirstInsertionPt();
2878c27c554SDimitry Andric assert(InsertPos != BB->end() && "should have checked above");
2885f757f3fSDimitry Andric InsertNewInstBefore(CI, InsertPos);
2890b57cec5SDimitry Andric } else {
2900b57cec5SDimitry Andric auto *InsertBB = &IncomingBB->getParent()->getEntryBlock();
2915f757f3fSDimitry Andric InsertNewInstBefore(CI, InsertBB->getFirstInsertionPt());
2920b57cec5SDimitry Andric }
2930b57cec5SDimitry Andric }
2940b57cec5SDimitry Andric NewPtrPHI->addIncoming(CI, IncomingBB);
2950b57cec5SDimitry Andric }
2960b57cec5SDimitry Andric
297bdd1243dSDimitry Andric // Explicitly replace the inttoptr (rather than inserting a ptrtoint) here,
298bdd1243dSDimitry Andric // to make sure another transform can't undo it in the meantime.
299bdd1243dSDimitry Andric replaceInstUsesWith(*IntToPtr, NewPtrPHI);
300bdd1243dSDimitry Andric eraseInstFromFunction(*IntToPtr);
301bdd1243dSDimitry Andric eraseInstFromFunction(PN);
302bdd1243dSDimitry Andric return true;
3030b57cec5SDimitry Andric }
3040b57cec5SDimitry Andric
305349cc55cSDimitry Andric // Remove RoundTrip IntToPtr/PtrToInt Cast on PHI-Operand and
306349cc55cSDimitry Andric // fold Phi-operand to bitcast.
foldPHIArgIntToPtrToPHI(PHINode & PN)307349cc55cSDimitry Andric Instruction *InstCombinerImpl::foldPHIArgIntToPtrToPHI(PHINode &PN) {
308349cc55cSDimitry Andric // convert ptr2int ( phi[ int2ptr(ptr2int(x))] ) --> ptr2int ( phi [ x ] )
309349cc55cSDimitry Andric // Make sure all uses of phi are ptr2int.
310349cc55cSDimitry Andric if (!all_of(PN.users(), [](User *U) { return isa<PtrToIntInst>(U); }))
311349cc55cSDimitry Andric return nullptr;
312349cc55cSDimitry Andric
313349cc55cSDimitry Andric // Iterating over all operands to check presence of target pointers for
314349cc55cSDimitry Andric // optimization.
315349cc55cSDimitry Andric bool OperandWithRoundTripCast = false;
316349cc55cSDimitry Andric for (unsigned OpNum = 0; OpNum != PN.getNumIncomingValues(); ++OpNum) {
317349cc55cSDimitry Andric if (auto *NewOp =
318349cc55cSDimitry Andric simplifyIntToPtrRoundTripCast(PN.getIncomingValue(OpNum))) {
31906c3fb27SDimitry Andric replaceOperand(PN, OpNum, NewOp);
320349cc55cSDimitry Andric OperandWithRoundTripCast = true;
321349cc55cSDimitry Andric }
322349cc55cSDimitry Andric }
323349cc55cSDimitry Andric if (!OperandWithRoundTripCast)
324349cc55cSDimitry Andric return nullptr;
325349cc55cSDimitry Andric return &PN;
326349cc55cSDimitry Andric }
327349cc55cSDimitry Andric
328e8d8bef9SDimitry Andric /// If we have something like phi [insertvalue(a,b,0), insertvalue(c,d,0)],
329e8d8bef9SDimitry Andric /// turn this into a phi[a,c] and phi[b,d] and a single insertvalue.
330e8d8bef9SDimitry Andric Instruction *
foldPHIArgInsertValueInstructionIntoPHI(PHINode & PN)331e8d8bef9SDimitry Andric InstCombinerImpl::foldPHIArgInsertValueInstructionIntoPHI(PHINode &PN) {
332e8d8bef9SDimitry Andric auto *FirstIVI = cast<InsertValueInst>(PN.getIncomingValue(0));
333e8d8bef9SDimitry Andric
334e8d8bef9SDimitry Andric // Scan to see if all operands are `insertvalue`'s with the same indicies,
335e8d8bef9SDimitry Andric // and all have a single use.
3361fd87a68SDimitry Andric for (Value *V : drop_begin(PN.incoming_values())) {
3371fd87a68SDimitry Andric auto *I = dyn_cast<InsertValueInst>(V);
338e8d8bef9SDimitry Andric if (!I || !I->hasOneUser() || I->getIndices() != FirstIVI->getIndices())
339e8d8bef9SDimitry Andric return nullptr;
340e8d8bef9SDimitry Andric }
341e8d8bef9SDimitry Andric
342e8d8bef9SDimitry Andric // For each operand of an `insertvalue`
343e8d8bef9SDimitry Andric std::array<PHINode *, 2> NewOperands;
344e8d8bef9SDimitry Andric for (int OpIdx : {0, 1}) {
345e8d8bef9SDimitry Andric auto *&NewOperand = NewOperands[OpIdx];
346e8d8bef9SDimitry Andric // Create a new PHI node to receive the values the operand has in each
347e8d8bef9SDimitry Andric // incoming basic block.
348e8d8bef9SDimitry Andric NewOperand = PHINode::Create(
349e8d8bef9SDimitry Andric FirstIVI->getOperand(OpIdx)->getType(), PN.getNumIncomingValues(),
350e8d8bef9SDimitry Andric FirstIVI->getOperand(OpIdx)->getName() + ".pn");
351e8d8bef9SDimitry Andric // And populate each operand's PHI with said values.
352e8d8bef9SDimitry Andric for (auto Incoming : zip(PN.blocks(), PN.incoming_values()))
353e8d8bef9SDimitry Andric NewOperand->addIncoming(
354e8d8bef9SDimitry Andric cast<InsertValueInst>(std::get<1>(Incoming))->getOperand(OpIdx),
355e8d8bef9SDimitry Andric std::get<0>(Incoming));
3565f757f3fSDimitry Andric InsertNewInstBefore(NewOperand, PN.getIterator());
357e8d8bef9SDimitry Andric }
358e8d8bef9SDimitry Andric
359e8d8bef9SDimitry Andric // And finally, create `insertvalue` over the newly-formed PHI nodes.
360e8d8bef9SDimitry Andric auto *NewIVI = InsertValueInst::Create(NewOperands[0], NewOperands[1],
361e8d8bef9SDimitry Andric FirstIVI->getIndices(), PN.getName());
362e8d8bef9SDimitry Andric
363e8d8bef9SDimitry Andric PHIArgMergedDebugLoc(NewIVI, PN);
364e8d8bef9SDimitry Andric ++NumPHIsOfInsertValues;
365e8d8bef9SDimitry Andric return NewIVI;
366e8d8bef9SDimitry Andric }
367e8d8bef9SDimitry Andric
368e8d8bef9SDimitry Andric /// If we have something like phi [extractvalue(a,0), extractvalue(b,0)],
369e8d8bef9SDimitry Andric /// turn this into a phi[a,b] and a single extractvalue.
370e8d8bef9SDimitry Andric Instruction *
foldPHIArgExtractValueInstructionIntoPHI(PHINode & PN)371e8d8bef9SDimitry Andric InstCombinerImpl::foldPHIArgExtractValueInstructionIntoPHI(PHINode &PN) {
372e8d8bef9SDimitry Andric auto *FirstEVI = cast<ExtractValueInst>(PN.getIncomingValue(0));
373e8d8bef9SDimitry Andric
374e8d8bef9SDimitry Andric // Scan to see if all operands are `extractvalue`'s with the same indicies,
375e8d8bef9SDimitry Andric // and all have a single use.
3761fd87a68SDimitry Andric for (Value *V : drop_begin(PN.incoming_values())) {
3771fd87a68SDimitry Andric auto *I = dyn_cast<ExtractValueInst>(V);
378e8d8bef9SDimitry Andric if (!I || !I->hasOneUser() || I->getIndices() != FirstEVI->getIndices() ||
379e8d8bef9SDimitry Andric I->getAggregateOperand()->getType() !=
380e8d8bef9SDimitry Andric FirstEVI->getAggregateOperand()->getType())
381e8d8bef9SDimitry Andric return nullptr;
382e8d8bef9SDimitry Andric }
383e8d8bef9SDimitry Andric
384e8d8bef9SDimitry Andric // Create a new PHI node to receive the values the aggregate operand has
385e8d8bef9SDimitry Andric // in each incoming basic block.
386e8d8bef9SDimitry Andric auto *NewAggregateOperand = PHINode::Create(
387e8d8bef9SDimitry Andric FirstEVI->getAggregateOperand()->getType(), PN.getNumIncomingValues(),
388e8d8bef9SDimitry Andric FirstEVI->getAggregateOperand()->getName() + ".pn");
389e8d8bef9SDimitry Andric // And populate the PHI with said values.
390e8d8bef9SDimitry Andric for (auto Incoming : zip(PN.blocks(), PN.incoming_values()))
391e8d8bef9SDimitry Andric NewAggregateOperand->addIncoming(
392e8d8bef9SDimitry Andric cast<ExtractValueInst>(std::get<1>(Incoming))->getAggregateOperand(),
393e8d8bef9SDimitry Andric std::get<0>(Incoming));
3945f757f3fSDimitry Andric InsertNewInstBefore(NewAggregateOperand, PN.getIterator());
395e8d8bef9SDimitry Andric
396e8d8bef9SDimitry Andric // And finally, create `extractvalue` over the newly-formed PHI nodes.
397e8d8bef9SDimitry Andric auto *NewEVI = ExtractValueInst::Create(NewAggregateOperand,
398e8d8bef9SDimitry Andric FirstEVI->getIndices(), PN.getName());
399e8d8bef9SDimitry Andric
400e8d8bef9SDimitry Andric PHIArgMergedDebugLoc(NewEVI, PN);
401e8d8bef9SDimitry Andric ++NumPHIsOfExtractValues;
402e8d8bef9SDimitry Andric return NewEVI;
403e8d8bef9SDimitry Andric }
404e8d8bef9SDimitry Andric
4050b57cec5SDimitry Andric /// If we have something like phi [add (a,b), add(a,c)] and if a/b/c and the
406e8d8bef9SDimitry Andric /// adds all have a single user, turn this into a phi and a single binop.
foldPHIArgBinOpIntoPHI(PHINode & PN)407e8d8bef9SDimitry Andric Instruction *InstCombinerImpl::foldPHIArgBinOpIntoPHI(PHINode &PN) {
4080b57cec5SDimitry Andric Instruction *FirstInst = cast<Instruction>(PN.getIncomingValue(0));
4090b57cec5SDimitry Andric assert(isa<BinaryOperator>(FirstInst) || isa<CmpInst>(FirstInst));
4100b57cec5SDimitry Andric unsigned Opc = FirstInst->getOpcode();
4110b57cec5SDimitry Andric Value *LHSVal = FirstInst->getOperand(0);
4120b57cec5SDimitry Andric Value *RHSVal = FirstInst->getOperand(1);
4130b57cec5SDimitry Andric
4140b57cec5SDimitry Andric Type *LHSType = LHSVal->getType();
4150b57cec5SDimitry Andric Type *RHSType = RHSVal->getType();
4160b57cec5SDimitry Andric
417e8d8bef9SDimitry Andric // Scan to see if all operands are the same opcode, and all have one user.
4181fd87a68SDimitry Andric for (Value *V : drop_begin(PN.incoming_values())) {
4191fd87a68SDimitry Andric Instruction *I = dyn_cast<Instruction>(V);
420e8d8bef9SDimitry Andric if (!I || I->getOpcode() != Opc || !I->hasOneUser() ||
4210b57cec5SDimitry Andric // Verify type of the LHS matches so we don't fold cmp's of different
4220b57cec5SDimitry Andric // types.
4230b57cec5SDimitry Andric I->getOperand(0)->getType() != LHSType ||
4240b57cec5SDimitry Andric I->getOperand(1)->getType() != RHSType)
4250b57cec5SDimitry Andric return nullptr;
4260b57cec5SDimitry Andric
4270b57cec5SDimitry Andric // If they are CmpInst instructions, check their predicates
4280b57cec5SDimitry Andric if (CmpInst *CI = dyn_cast<CmpInst>(I))
4290b57cec5SDimitry Andric if (CI->getPredicate() != cast<CmpInst>(FirstInst)->getPredicate())
4300b57cec5SDimitry Andric return nullptr;
4310b57cec5SDimitry Andric
4320b57cec5SDimitry Andric // Keep track of which operand needs a phi node.
4330b57cec5SDimitry Andric if (I->getOperand(0) != LHSVal) LHSVal = nullptr;
4340b57cec5SDimitry Andric if (I->getOperand(1) != RHSVal) RHSVal = nullptr;
4350b57cec5SDimitry Andric }
4360b57cec5SDimitry Andric
4370b57cec5SDimitry Andric // If both LHS and RHS would need a PHI, don't do this transformation,
4380b57cec5SDimitry Andric // because it would increase the number of PHIs entering the block,
4390b57cec5SDimitry Andric // which leads to higher register pressure. This is especially
4400b57cec5SDimitry Andric // bad when the PHIs are in the header of a loop.
4410b57cec5SDimitry Andric if (!LHSVal && !RHSVal)
4420b57cec5SDimitry Andric return nullptr;
4430b57cec5SDimitry Andric
4440b57cec5SDimitry Andric // Otherwise, this is safe to transform!
4450b57cec5SDimitry Andric
4460b57cec5SDimitry Andric Value *InLHS = FirstInst->getOperand(0);
4470b57cec5SDimitry Andric Value *InRHS = FirstInst->getOperand(1);
4480b57cec5SDimitry Andric PHINode *NewLHS = nullptr, *NewRHS = nullptr;
4490b57cec5SDimitry Andric if (!LHSVal) {
4500b57cec5SDimitry Andric NewLHS = PHINode::Create(LHSType, PN.getNumIncomingValues(),
4510b57cec5SDimitry Andric FirstInst->getOperand(0)->getName() + ".pn");
4520b57cec5SDimitry Andric NewLHS->addIncoming(InLHS, PN.getIncomingBlock(0));
4535f757f3fSDimitry Andric InsertNewInstBefore(NewLHS, PN.getIterator());
4540b57cec5SDimitry Andric LHSVal = NewLHS;
4550b57cec5SDimitry Andric }
4560b57cec5SDimitry Andric
4570b57cec5SDimitry Andric if (!RHSVal) {
4580b57cec5SDimitry Andric NewRHS = PHINode::Create(RHSType, PN.getNumIncomingValues(),
4590b57cec5SDimitry Andric FirstInst->getOperand(1)->getName() + ".pn");
4600b57cec5SDimitry Andric NewRHS->addIncoming(InRHS, PN.getIncomingBlock(0));
4615f757f3fSDimitry Andric InsertNewInstBefore(NewRHS, PN.getIterator());
4620b57cec5SDimitry Andric RHSVal = NewRHS;
4630b57cec5SDimitry Andric }
4640b57cec5SDimitry Andric
4650b57cec5SDimitry Andric // Add all operands to the new PHIs.
4660b57cec5SDimitry Andric if (NewLHS || NewRHS) {
4671fd87a68SDimitry Andric for (auto Incoming : drop_begin(zip(PN.blocks(), PN.incoming_values()))) {
4681fd87a68SDimitry Andric BasicBlock *InBB = std::get<0>(Incoming);
4691fd87a68SDimitry Andric Value *InVal = std::get<1>(Incoming);
4701fd87a68SDimitry Andric Instruction *InInst = cast<Instruction>(InVal);
4710b57cec5SDimitry Andric if (NewLHS) {
4720b57cec5SDimitry Andric Value *NewInLHS = InInst->getOperand(0);
4731fd87a68SDimitry Andric NewLHS->addIncoming(NewInLHS, InBB);
4740b57cec5SDimitry Andric }
4750b57cec5SDimitry Andric if (NewRHS) {
4760b57cec5SDimitry Andric Value *NewInRHS = InInst->getOperand(1);
4771fd87a68SDimitry Andric NewRHS->addIncoming(NewInRHS, InBB);
4780b57cec5SDimitry Andric }
4790b57cec5SDimitry Andric }
4800b57cec5SDimitry Andric }
4810b57cec5SDimitry Andric
4820b57cec5SDimitry Andric if (CmpInst *CIOp = dyn_cast<CmpInst>(FirstInst)) {
4830b57cec5SDimitry Andric CmpInst *NewCI = CmpInst::Create(CIOp->getOpcode(), CIOp->getPredicate(),
4840b57cec5SDimitry Andric LHSVal, RHSVal);
4850b57cec5SDimitry Andric PHIArgMergedDebugLoc(NewCI, PN);
4860b57cec5SDimitry Andric return NewCI;
4870b57cec5SDimitry Andric }
4880b57cec5SDimitry Andric
4890b57cec5SDimitry Andric BinaryOperator *BinOp = cast<BinaryOperator>(FirstInst);
4900b57cec5SDimitry Andric BinaryOperator *NewBinOp =
4910b57cec5SDimitry Andric BinaryOperator::Create(BinOp->getOpcode(), LHSVal, RHSVal);
4920b57cec5SDimitry Andric
4930b57cec5SDimitry Andric NewBinOp->copyIRFlags(PN.getIncomingValue(0));
4940b57cec5SDimitry Andric
4951fd87a68SDimitry Andric for (Value *V : drop_begin(PN.incoming_values()))
4961fd87a68SDimitry Andric NewBinOp->andIRFlags(V);
4970b57cec5SDimitry Andric
4980b57cec5SDimitry Andric PHIArgMergedDebugLoc(NewBinOp, PN);
4990b57cec5SDimitry Andric return NewBinOp;
5000b57cec5SDimitry Andric }
5010b57cec5SDimitry Andric
foldPHIArgGEPIntoPHI(PHINode & PN)502e8d8bef9SDimitry Andric Instruction *InstCombinerImpl::foldPHIArgGEPIntoPHI(PHINode &PN) {
5030b57cec5SDimitry Andric GetElementPtrInst *FirstInst =cast<GetElementPtrInst>(PN.getIncomingValue(0));
5040b57cec5SDimitry Andric
5050b57cec5SDimitry Andric SmallVector<Value*, 16> FixedOperands(FirstInst->op_begin(),
5060b57cec5SDimitry Andric FirstInst->op_end());
5070b57cec5SDimitry Andric // This is true if all GEP bases are allocas and if all indices into them are
5080b57cec5SDimitry Andric // constants.
5090b57cec5SDimitry Andric bool AllBasePointersAreAllocas = true;
5100b57cec5SDimitry Andric
5110b57cec5SDimitry Andric // We don't want to replace this phi if the replacement would require
5120b57cec5SDimitry Andric // more than one phi, which leads to higher register pressure. This is
5130b57cec5SDimitry Andric // especially bad when the PHIs are in the header of a loop.
5140b57cec5SDimitry Andric bool NeededPhi = false;
5150b57cec5SDimitry Andric
5160b57cec5SDimitry Andric bool AllInBounds = true;
5170b57cec5SDimitry Andric
518e8d8bef9SDimitry Andric // Scan to see if all operands are the same opcode, and all have one user.
5191fd87a68SDimitry Andric for (Value *V : drop_begin(PN.incoming_values())) {
5201fd87a68SDimitry Andric GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(V);
52181ad6265SDimitry Andric if (!GEP || !GEP->hasOneUser() ||
52281ad6265SDimitry Andric GEP->getSourceElementType() != FirstInst->getSourceElementType() ||
5230b57cec5SDimitry Andric GEP->getNumOperands() != FirstInst->getNumOperands())
5240b57cec5SDimitry Andric return nullptr;
5250b57cec5SDimitry Andric
5260b57cec5SDimitry Andric AllInBounds &= GEP->isInBounds();
5270b57cec5SDimitry Andric
5280b57cec5SDimitry Andric // Keep track of whether or not all GEPs are of alloca pointers.
5290b57cec5SDimitry Andric if (AllBasePointersAreAllocas &&
5300b57cec5SDimitry Andric (!isa<AllocaInst>(GEP->getOperand(0)) ||
5310b57cec5SDimitry Andric !GEP->hasAllConstantIndices()))
5320b57cec5SDimitry Andric AllBasePointersAreAllocas = false;
5330b57cec5SDimitry Andric
5340b57cec5SDimitry Andric // Compare the operand lists.
5351fd87a68SDimitry Andric for (unsigned Op = 0, E = FirstInst->getNumOperands(); Op != E; ++Op) {
5361fd87a68SDimitry Andric if (FirstInst->getOperand(Op) == GEP->getOperand(Op))
5370b57cec5SDimitry Andric continue;
5380b57cec5SDimitry Andric
5390b57cec5SDimitry Andric // Don't merge two GEPs when two operands differ (introducing phi nodes)
5400b57cec5SDimitry Andric // if one of the PHIs has a constant for the index. The index may be
5410b57cec5SDimitry Andric // substantially cheaper to compute for the constants, so making it a
5420b57cec5SDimitry Andric // variable index could pessimize the path. This also handles the case
5430b57cec5SDimitry Andric // for struct indices, which must always be constant.
5441fd87a68SDimitry Andric if (isa<ConstantInt>(FirstInst->getOperand(Op)) ||
5451fd87a68SDimitry Andric isa<ConstantInt>(GEP->getOperand(Op)))
5460b57cec5SDimitry Andric return nullptr;
5470b57cec5SDimitry Andric
5481fd87a68SDimitry Andric if (FirstInst->getOperand(Op)->getType() !=
5491fd87a68SDimitry Andric GEP->getOperand(Op)->getType())
5500b57cec5SDimitry Andric return nullptr;
5510b57cec5SDimitry Andric
5520b57cec5SDimitry Andric // If we already needed a PHI for an earlier operand, and another operand
5530b57cec5SDimitry Andric // also requires a PHI, we'd be introducing more PHIs than we're
5540b57cec5SDimitry Andric // eliminating, which increases register pressure on entry to the PHI's
5550b57cec5SDimitry Andric // block.
5560b57cec5SDimitry Andric if (NeededPhi)
5570b57cec5SDimitry Andric return nullptr;
5580b57cec5SDimitry Andric
5591fd87a68SDimitry Andric FixedOperands[Op] = nullptr; // Needs a PHI.
5600b57cec5SDimitry Andric NeededPhi = true;
5610b57cec5SDimitry Andric }
5620b57cec5SDimitry Andric }
5630b57cec5SDimitry Andric
5640b57cec5SDimitry Andric // If all of the base pointers of the PHI'd GEPs are from allocas, don't
5650b57cec5SDimitry Andric // bother doing this transformation. At best, this will just save a bit of
5660b57cec5SDimitry Andric // offset calculation, but all the predecessors will have to materialize the
5670b57cec5SDimitry Andric // stack address into a register anyway. We'd actually rather *clone* the
5680b57cec5SDimitry Andric // load up into the predecessors so that we have a load of a gep of an alloca,
5690b57cec5SDimitry Andric // which can usually all be folded into the load.
5700b57cec5SDimitry Andric if (AllBasePointersAreAllocas)
5710b57cec5SDimitry Andric return nullptr;
5720b57cec5SDimitry Andric
5730b57cec5SDimitry Andric // Otherwise, this is safe to transform. Insert PHI nodes for each operand
5740b57cec5SDimitry Andric // that is variable.
5750b57cec5SDimitry Andric SmallVector<PHINode*, 16> OperandPhis(FixedOperands.size());
5760b57cec5SDimitry Andric
5770b57cec5SDimitry Andric bool HasAnyPHIs = false;
5781fd87a68SDimitry Andric for (unsigned I = 0, E = FixedOperands.size(); I != E; ++I) {
5791fd87a68SDimitry Andric if (FixedOperands[I])
5801fd87a68SDimitry Andric continue; // operand doesn't need a phi.
5811fd87a68SDimitry Andric Value *FirstOp = FirstInst->getOperand(I);
5821fd87a68SDimitry Andric PHINode *NewPN =
5831fd87a68SDimitry Andric PHINode::Create(FirstOp->getType(), E, FirstOp->getName() + ".pn");
5845f757f3fSDimitry Andric InsertNewInstBefore(NewPN, PN.getIterator());
5850b57cec5SDimitry Andric
5860b57cec5SDimitry Andric NewPN->addIncoming(FirstOp, PN.getIncomingBlock(0));
5871fd87a68SDimitry Andric OperandPhis[I] = NewPN;
5881fd87a68SDimitry Andric FixedOperands[I] = NewPN;
5890b57cec5SDimitry Andric HasAnyPHIs = true;
5900b57cec5SDimitry Andric }
5910b57cec5SDimitry Andric
5920b57cec5SDimitry Andric // Add all operands to the new PHIs.
5930b57cec5SDimitry Andric if (HasAnyPHIs) {
5941fd87a68SDimitry Andric for (auto Incoming : drop_begin(zip(PN.blocks(), PN.incoming_values()))) {
5951fd87a68SDimitry Andric BasicBlock *InBB = std::get<0>(Incoming);
5961fd87a68SDimitry Andric Value *InVal = std::get<1>(Incoming);
5971fd87a68SDimitry Andric GetElementPtrInst *InGEP = cast<GetElementPtrInst>(InVal);
5980b57cec5SDimitry Andric
5991fd87a68SDimitry Andric for (unsigned Op = 0, E = OperandPhis.size(); Op != E; ++Op)
6001fd87a68SDimitry Andric if (PHINode *OpPhi = OperandPhis[Op])
6011fd87a68SDimitry Andric OpPhi->addIncoming(InGEP->getOperand(Op), InBB);
6020b57cec5SDimitry Andric }
6030b57cec5SDimitry Andric }
6040b57cec5SDimitry Andric
6050b57cec5SDimitry Andric Value *Base = FixedOperands[0];
6060b57cec5SDimitry Andric GetElementPtrInst *NewGEP =
6070b57cec5SDimitry Andric GetElementPtrInst::Create(FirstInst->getSourceElementType(), Base,
608bdd1243dSDimitry Andric ArrayRef(FixedOperands).slice(1));
6090b57cec5SDimitry Andric if (AllInBounds) NewGEP->setIsInBounds();
6100b57cec5SDimitry Andric PHIArgMergedDebugLoc(NewGEP, PN);
6110b57cec5SDimitry Andric return NewGEP;
6120b57cec5SDimitry Andric }
6130b57cec5SDimitry Andric
6140b57cec5SDimitry Andric /// Return true if we know that it is safe to sink the load out of the block
6150b57cec5SDimitry Andric /// that defines it. This means that it must be obvious the value of the load is
6160b57cec5SDimitry Andric /// not changed from the point of the load to the end of the block it is in.
6170b57cec5SDimitry Andric ///
6180b57cec5SDimitry Andric /// Finally, it is safe, but not profitable, to sink a load targeting a
6190b57cec5SDimitry Andric /// non-address-taken alloca. Doing so will cause us to not promote the alloca
6200b57cec5SDimitry Andric /// to a register.
isSafeAndProfitableToSinkLoad(LoadInst * L)6210b57cec5SDimitry Andric static bool isSafeAndProfitableToSinkLoad(LoadInst *L) {
6220b57cec5SDimitry Andric BasicBlock::iterator BBI = L->getIterator(), E = L->getParent()->end();
6230b57cec5SDimitry Andric
6240b57cec5SDimitry Andric for (++BBI; BBI != E; ++BBI)
625d409305fSDimitry Andric if (BBI->mayWriteToMemory()) {
626d409305fSDimitry Andric // Calls that only access inaccessible memory do not block sinking the
627d409305fSDimitry Andric // load.
628d409305fSDimitry Andric if (auto *CB = dyn_cast<CallBase>(BBI))
629d409305fSDimitry Andric if (CB->onlyAccessesInaccessibleMemory())
630d409305fSDimitry Andric continue;
6310b57cec5SDimitry Andric return false;
632d409305fSDimitry Andric }
6330b57cec5SDimitry Andric
6340b57cec5SDimitry Andric // Check for non-address taken alloca. If not address-taken already, it isn't
6350b57cec5SDimitry Andric // profitable to do this xform.
6360b57cec5SDimitry Andric if (AllocaInst *AI = dyn_cast<AllocaInst>(L->getOperand(0))) {
6371fd87a68SDimitry Andric bool IsAddressTaken = false;
6380b57cec5SDimitry Andric for (User *U : AI->users()) {
6390b57cec5SDimitry Andric if (isa<LoadInst>(U)) continue;
6400b57cec5SDimitry Andric if (StoreInst *SI = dyn_cast<StoreInst>(U)) {
6410b57cec5SDimitry Andric // If storing TO the alloca, then the address isn't taken.
6420b57cec5SDimitry Andric if (SI->getOperand(1) == AI) continue;
6430b57cec5SDimitry Andric }
6441fd87a68SDimitry Andric IsAddressTaken = true;
6450b57cec5SDimitry Andric break;
6460b57cec5SDimitry Andric }
6470b57cec5SDimitry Andric
6481fd87a68SDimitry Andric if (!IsAddressTaken && AI->isStaticAlloca())
6490b57cec5SDimitry Andric return false;
6500b57cec5SDimitry Andric }
6510b57cec5SDimitry Andric
6520b57cec5SDimitry Andric // If this load is a load from a GEP with a constant offset from an alloca,
6530b57cec5SDimitry Andric // then we don't want to sink it. In its present form, it will be
6540b57cec5SDimitry Andric // load [constant stack offset]. Sinking it will cause us to have to
6550b57cec5SDimitry Andric // materialize the stack addresses in each predecessor in a register only to
6560b57cec5SDimitry Andric // do a shared load from register in the successor.
6570b57cec5SDimitry Andric if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(L->getOperand(0)))
6580b57cec5SDimitry Andric if (AllocaInst *AI = dyn_cast<AllocaInst>(GEP->getOperand(0)))
6590b57cec5SDimitry Andric if (AI->isStaticAlloca() && GEP->hasAllConstantIndices())
6600b57cec5SDimitry Andric return false;
6610b57cec5SDimitry Andric
6620b57cec5SDimitry Andric return true;
6630b57cec5SDimitry Andric }
6640b57cec5SDimitry Andric
foldPHIArgLoadIntoPHI(PHINode & PN)665e8d8bef9SDimitry Andric Instruction *InstCombinerImpl::foldPHIArgLoadIntoPHI(PHINode &PN) {
6660b57cec5SDimitry Andric LoadInst *FirstLI = cast<LoadInst>(PN.getIncomingValue(0));
6670b57cec5SDimitry Andric
66881ad6265SDimitry Andric // Can't forward swifterror through a phi.
66981ad6265SDimitry Andric if (FirstLI->getOperand(0)->isSwiftError())
67081ad6265SDimitry Andric return nullptr;
67181ad6265SDimitry Andric
6720b57cec5SDimitry Andric // FIXME: This is overconservative; this transform is allowed in some cases
6730b57cec5SDimitry Andric // for atomic operations.
6740b57cec5SDimitry Andric if (FirstLI->isAtomic())
6750b57cec5SDimitry Andric return nullptr;
6760b57cec5SDimitry Andric
6770b57cec5SDimitry Andric // When processing loads, we need to propagate two bits of information to the
6780eae32dcSDimitry Andric // sunk load: whether it is volatile, and what its alignment is.
6791fd87a68SDimitry Andric bool IsVolatile = FirstLI->isVolatile();
6805ffd83dbSDimitry Andric Align LoadAlignment = FirstLI->getAlign();
6811fd87a68SDimitry Andric const unsigned LoadAddrSpace = FirstLI->getPointerAddressSpace();
6820b57cec5SDimitry Andric
6830b57cec5SDimitry Andric // We can't sink the load if the loaded value could be modified between the
6840b57cec5SDimitry Andric // load and the PHI.
6850b57cec5SDimitry Andric if (FirstLI->getParent() != PN.getIncomingBlock(0) ||
6860b57cec5SDimitry Andric !isSafeAndProfitableToSinkLoad(FirstLI))
6870b57cec5SDimitry Andric return nullptr;
6880b57cec5SDimitry Andric
6890b57cec5SDimitry Andric // If the PHI is of volatile loads and the load block has multiple
6900b57cec5SDimitry Andric // successors, sinking it would remove a load of the volatile value from
6910b57cec5SDimitry Andric // the path through the other successor.
6921fd87a68SDimitry Andric if (IsVolatile &&
6930b57cec5SDimitry Andric FirstLI->getParent()->getTerminator()->getNumSuccessors() != 1)
6940b57cec5SDimitry Andric return nullptr;
6950b57cec5SDimitry Andric
6961fd87a68SDimitry Andric for (auto Incoming : drop_begin(zip(PN.blocks(), PN.incoming_values()))) {
6971fd87a68SDimitry Andric BasicBlock *InBB = std::get<0>(Incoming);
6981fd87a68SDimitry Andric Value *InVal = std::get<1>(Incoming);
6991fd87a68SDimitry Andric LoadInst *LI = dyn_cast<LoadInst>(InVal);
7001fd87a68SDimitry Andric if (!LI || !LI->hasOneUser() || LI->isAtomic())
7011fd87a68SDimitry Andric return nullptr;
7021fd87a68SDimitry Andric
7031fd87a68SDimitry Andric // Make sure all arguments are the same type of operation.
7041fd87a68SDimitry Andric if (LI->isVolatile() != IsVolatile ||
7051fd87a68SDimitry Andric LI->getPointerAddressSpace() != LoadAddrSpace)
7060b57cec5SDimitry Andric return nullptr;
7070b57cec5SDimitry Andric
70881ad6265SDimitry Andric // Can't forward swifterror through a phi.
70981ad6265SDimitry Andric if (LI->getOperand(0)->isSwiftError())
71081ad6265SDimitry Andric return nullptr;
71181ad6265SDimitry Andric
7120b57cec5SDimitry Andric // We can't sink the load if the loaded value could be modified between
7130b57cec5SDimitry Andric // the load and the PHI.
7141fd87a68SDimitry Andric if (LI->getParent() != InBB || !isSafeAndProfitableToSinkLoad(LI))
7150b57cec5SDimitry Andric return nullptr;
7160b57cec5SDimitry Andric
7170eae32dcSDimitry Andric LoadAlignment = std::min(LoadAlignment, LI->getAlign());
7180b57cec5SDimitry Andric
7190b57cec5SDimitry Andric // If the PHI is of volatile loads and the load block has multiple
7200b57cec5SDimitry Andric // successors, sinking it would remove a load of the volatile value from
7210b57cec5SDimitry Andric // the path through the other successor.
7221fd87a68SDimitry Andric if (IsVolatile && LI->getParent()->getTerminator()->getNumSuccessors() != 1)
7230b57cec5SDimitry Andric return nullptr;
7240b57cec5SDimitry Andric }
7250b57cec5SDimitry Andric
7260b57cec5SDimitry Andric // Okay, they are all the same operation. Create a new PHI node of the
7270b57cec5SDimitry Andric // correct type, and PHI together all of the LHS's of the instructions.
7280b57cec5SDimitry Andric PHINode *NewPN = PHINode::Create(FirstLI->getOperand(0)->getType(),
7290b57cec5SDimitry Andric PN.getNumIncomingValues(),
7300b57cec5SDimitry Andric PN.getName()+".in");
7310b57cec5SDimitry Andric
7320b57cec5SDimitry Andric Value *InVal = FirstLI->getOperand(0);
7330b57cec5SDimitry Andric NewPN->addIncoming(InVal, PN.getIncomingBlock(0));
7340b57cec5SDimitry Andric LoadInst *NewLI =
7351fd87a68SDimitry Andric new LoadInst(FirstLI->getType(), NewPN, "", IsVolatile, LoadAlignment);
7360b57cec5SDimitry Andric
7370b57cec5SDimitry Andric unsigned KnownIDs[] = {
7380b57cec5SDimitry Andric LLVMContext::MD_tbaa,
7390b57cec5SDimitry Andric LLVMContext::MD_range,
7400b57cec5SDimitry Andric LLVMContext::MD_invariant_load,
7410b57cec5SDimitry Andric LLVMContext::MD_alias_scope,
7420b57cec5SDimitry Andric LLVMContext::MD_noalias,
7430b57cec5SDimitry Andric LLVMContext::MD_nonnull,
7440b57cec5SDimitry Andric LLVMContext::MD_align,
7450b57cec5SDimitry Andric LLVMContext::MD_dereferenceable,
7460b57cec5SDimitry Andric LLVMContext::MD_dereferenceable_or_null,
7470b57cec5SDimitry Andric LLVMContext::MD_access_group,
74806c3fb27SDimitry Andric LLVMContext::MD_noundef,
7490b57cec5SDimitry Andric };
7500b57cec5SDimitry Andric
7510b57cec5SDimitry Andric for (unsigned ID : KnownIDs)
7520b57cec5SDimitry Andric NewLI->setMetadata(ID, FirstLI->getMetadata(ID));
7530b57cec5SDimitry Andric
7540b57cec5SDimitry Andric // Add all operands to the new PHI and combine TBAA metadata.
7551fd87a68SDimitry Andric for (auto Incoming : drop_begin(zip(PN.blocks(), PN.incoming_values()))) {
7561fd87a68SDimitry Andric BasicBlock *BB = std::get<0>(Incoming);
7571fd87a68SDimitry Andric Value *V = std::get<1>(Incoming);
7581fd87a68SDimitry Andric LoadInst *LI = cast<LoadInst>(V);
7590b57cec5SDimitry Andric combineMetadata(NewLI, LI, KnownIDs, true);
7600b57cec5SDimitry Andric Value *NewInVal = LI->getOperand(0);
7610b57cec5SDimitry Andric if (NewInVal != InVal)
7620b57cec5SDimitry Andric InVal = nullptr;
7631fd87a68SDimitry Andric NewPN->addIncoming(NewInVal, BB);
7640b57cec5SDimitry Andric }
7650b57cec5SDimitry Andric
7660b57cec5SDimitry Andric if (InVal) {
7670b57cec5SDimitry Andric // The new PHI unions all of the same values together. This is really
7680b57cec5SDimitry Andric // common, so we handle it intelligently here for compile-time speed.
7690b57cec5SDimitry Andric NewLI->setOperand(0, InVal);
7700b57cec5SDimitry Andric delete NewPN;
7710b57cec5SDimitry Andric } else {
7725f757f3fSDimitry Andric InsertNewInstBefore(NewPN, PN.getIterator());
7730b57cec5SDimitry Andric }
7740b57cec5SDimitry Andric
7750b57cec5SDimitry Andric // If this was a volatile load that we are merging, make sure to loop through
7760b57cec5SDimitry Andric // and mark all the input loads as non-volatile. If we don't do this, we will
7770b57cec5SDimitry Andric // insert a new volatile load and the old ones will not be deletable.
7781fd87a68SDimitry Andric if (IsVolatile)
7790b57cec5SDimitry Andric for (Value *IncValue : PN.incoming_values())
7800b57cec5SDimitry Andric cast<LoadInst>(IncValue)->setVolatile(false);
7810b57cec5SDimitry Andric
7820b57cec5SDimitry Andric PHIArgMergedDebugLoc(NewLI, PN);
7830b57cec5SDimitry Andric return NewLI;
7840b57cec5SDimitry Andric }
7850b57cec5SDimitry Andric
7860b57cec5SDimitry Andric /// TODO: This function could handle other cast types, but then it might
7870b57cec5SDimitry Andric /// require special-casing a cast from the 'i1' type. See the comment in
7880b57cec5SDimitry Andric /// FoldPHIArgOpIntoPHI() about pessimizing illegal integer types.
foldPHIArgZextsIntoPHI(PHINode & Phi)789e8d8bef9SDimitry Andric Instruction *InstCombinerImpl::foldPHIArgZextsIntoPHI(PHINode &Phi) {
7900b57cec5SDimitry Andric // We cannot create a new instruction after the PHI if the terminator is an
7910b57cec5SDimitry Andric // EHPad because there is no valid insertion point.
7920b57cec5SDimitry Andric if (Instruction *TI = Phi.getParent()->getTerminator())
7930b57cec5SDimitry Andric if (TI->isEHPad())
7940b57cec5SDimitry Andric return nullptr;
7950b57cec5SDimitry Andric
7960b57cec5SDimitry Andric // Early exit for the common case of a phi with two operands. These are
7970b57cec5SDimitry Andric // handled elsewhere. See the comment below where we check the count of zexts
7980b57cec5SDimitry Andric // and constants for more details.
7990b57cec5SDimitry Andric unsigned NumIncomingValues = Phi.getNumIncomingValues();
8000b57cec5SDimitry Andric if (NumIncomingValues < 3)
8010b57cec5SDimitry Andric return nullptr;
8020b57cec5SDimitry Andric
8030b57cec5SDimitry Andric // Find the narrower type specified by the first zext.
8040b57cec5SDimitry Andric Type *NarrowType = nullptr;
8050b57cec5SDimitry Andric for (Value *V : Phi.incoming_values()) {
8060b57cec5SDimitry Andric if (auto *Zext = dyn_cast<ZExtInst>(V)) {
8070b57cec5SDimitry Andric NarrowType = Zext->getSrcTy();
8080b57cec5SDimitry Andric break;
8090b57cec5SDimitry Andric }
8100b57cec5SDimitry Andric }
8110b57cec5SDimitry Andric if (!NarrowType)
8120b57cec5SDimitry Andric return nullptr;
8130b57cec5SDimitry Andric
8140b57cec5SDimitry Andric // Walk the phi operands checking that we only have zexts or constants that
8150b57cec5SDimitry Andric // we can shrink for free. Store the new operands for the new phi.
8160b57cec5SDimitry Andric SmallVector<Value *, 4> NewIncoming;
8170b57cec5SDimitry Andric unsigned NumZexts = 0;
8180b57cec5SDimitry Andric unsigned NumConsts = 0;
8190b57cec5SDimitry Andric for (Value *V : Phi.incoming_values()) {
8200b57cec5SDimitry Andric if (auto *Zext = dyn_cast<ZExtInst>(V)) {
821e8d8bef9SDimitry Andric // All zexts must be identical and have one user.
822e8d8bef9SDimitry Andric if (Zext->getSrcTy() != NarrowType || !Zext->hasOneUser())
8230b57cec5SDimitry Andric return nullptr;
8240b57cec5SDimitry Andric NewIncoming.push_back(Zext->getOperand(0));
8250b57cec5SDimitry Andric NumZexts++;
8260b57cec5SDimitry Andric } else if (auto *C = dyn_cast<Constant>(V)) {
8270b57cec5SDimitry Andric // Make sure that constants can fit in the new type.
8285f757f3fSDimitry Andric Constant *Trunc = getLosslessUnsignedTrunc(C, NarrowType);
8295f757f3fSDimitry Andric if (!Trunc)
8300b57cec5SDimitry Andric return nullptr;
8310b57cec5SDimitry Andric NewIncoming.push_back(Trunc);
8320b57cec5SDimitry Andric NumConsts++;
8330b57cec5SDimitry Andric } else {
8340b57cec5SDimitry Andric // If it's not a cast or a constant, bail out.
8350b57cec5SDimitry Andric return nullptr;
8360b57cec5SDimitry Andric }
8370b57cec5SDimitry Andric }
8380b57cec5SDimitry Andric
8390b57cec5SDimitry Andric // The more common cases of a phi with no constant operands or just one
8400b57cec5SDimitry Andric // variable operand are handled by FoldPHIArgOpIntoPHI() and foldOpIntoPhi()
8410b57cec5SDimitry Andric // respectively. foldOpIntoPhi() wants to do the opposite transform that is
8420b57cec5SDimitry Andric // performed here. It tries to replicate a cast in the phi operand's basic
8430b57cec5SDimitry Andric // block to expose other folding opportunities. Thus, InstCombine will
8440b57cec5SDimitry Andric // infinite loop without this check.
8450b57cec5SDimitry Andric if (NumConsts == 0 || NumZexts < 2)
8460b57cec5SDimitry Andric return nullptr;
8470b57cec5SDimitry Andric
8480b57cec5SDimitry Andric // All incoming values are zexts or constants that are safe to truncate.
8490b57cec5SDimitry Andric // Create a new phi node of the narrow type, phi together all of the new
8500b57cec5SDimitry Andric // operands, and zext the result back to the original type.
8510b57cec5SDimitry Andric PHINode *NewPhi = PHINode::Create(NarrowType, NumIncomingValues,
8520b57cec5SDimitry Andric Phi.getName() + ".shrunk");
8531fd87a68SDimitry Andric for (unsigned I = 0; I != NumIncomingValues; ++I)
8541fd87a68SDimitry Andric NewPhi->addIncoming(NewIncoming[I], Phi.getIncomingBlock(I));
8550b57cec5SDimitry Andric
8565f757f3fSDimitry Andric InsertNewInstBefore(NewPhi, Phi.getIterator());
8570b57cec5SDimitry Andric return CastInst::CreateZExtOrBitCast(NewPhi, Phi.getType());
8580b57cec5SDimitry Andric }
8590b57cec5SDimitry Andric
8600b57cec5SDimitry Andric /// If all operands to a PHI node are the same "unary" operator and they all are
8610b57cec5SDimitry Andric /// only used by the PHI, PHI together their inputs, and do the operation once,
8620b57cec5SDimitry Andric /// to the result of the PHI.
foldPHIArgOpIntoPHI(PHINode & PN)863e8d8bef9SDimitry Andric Instruction *InstCombinerImpl::foldPHIArgOpIntoPHI(PHINode &PN) {
8640b57cec5SDimitry Andric // We cannot create a new instruction after the PHI if the terminator is an
8650b57cec5SDimitry Andric // EHPad because there is no valid insertion point.
8660b57cec5SDimitry Andric if (Instruction *TI = PN.getParent()->getTerminator())
8670b57cec5SDimitry Andric if (TI->isEHPad())
8680b57cec5SDimitry Andric return nullptr;
8690b57cec5SDimitry Andric
8700b57cec5SDimitry Andric Instruction *FirstInst = cast<Instruction>(PN.getIncomingValue(0));
8710b57cec5SDimitry Andric
8720b57cec5SDimitry Andric if (isa<GetElementPtrInst>(FirstInst))
873e8d8bef9SDimitry Andric return foldPHIArgGEPIntoPHI(PN);
8740b57cec5SDimitry Andric if (isa<LoadInst>(FirstInst))
875e8d8bef9SDimitry Andric return foldPHIArgLoadIntoPHI(PN);
876e8d8bef9SDimitry Andric if (isa<InsertValueInst>(FirstInst))
877e8d8bef9SDimitry Andric return foldPHIArgInsertValueInstructionIntoPHI(PN);
878e8d8bef9SDimitry Andric if (isa<ExtractValueInst>(FirstInst))
879e8d8bef9SDimitry Andric return foldPHIArgExtractValueInstructionIntoPHI(PN);
8800b57cec5SDimitry Andric
8810b57cec5SDimitry Andric // Scan the instruction, looking for input operations that can be folded away.
8820b57cec5SDimitry Andric // If all input operands to the phi are the same instruction (e.g. a cast from
8830b57cec5SDimitry Andric // the same type or "+42") we can pull the operation through the PHI, reducing
8840b57cec5SDimitry Andric // code size and simplifying code.
8850b57cec5SDimitry Andric Constant *ConstantOp = nullptr;
8860b57cec5SDimitry Andric Type *CastSrcTy = nullptr;
8870b57cec5SDimitry Andric
8880b57cec5SDimitry Andric if (isa<CastInst>(FirstInst)) {
8890b57cec5SDimitry Andric CastSrcTy = FirstInst->getOperand(0)->getType();
8900b57cec5SDimitry Andric
8910b57cec5SDimitry Andric // Be careful about transforming integer PHIs. We don't want to pessimize
8920b57cec5SDimitry Andric // the code by turning an i32 into an i1293.
8930b57cec5SDimitry Andric if (PN.getType()->isIntegerTy() && CastSrcTy->isIntegerTy()) {
8940b57cec5SDimitry Andric if (!shouldChangeType(PN.getType(), CastSrcTy))
8950b57cec5SDimitry Andric return nullptr;
8960b57cec5SDimitry Andric }
8970b57cec5SDimitry Andric } else if (isa<BinaryOperator>(FirstInst) || isa<CmpInst>(FirstInst)) {
8980b57cec5SDimitry Andric // Can fold binop, compare or shift here if the RHS is a constant,
8990b57cec5SDimitry Andric // otherwise call FoldPHIArgBinOpIntoPHI.
9000b57cec5SDimitry Andric ConstantOp = dyn_cast<Constant>(FirstInst->getOperand(1));
9010b57cec5SDimitry Andric if (!ConstantOp)
902e8d8bef9SDimitry Andric return foldPHIArgBinOpIntoPHI(PN);
9030b57cec5SDimitry Andric } else {
9040b57cec5SDimitry Andric return nullptr; // Cannot fold this operation.
9050b57cec5SDimitry Andric }
9060b57cec5SDimitry Andric
9070b57cec5SDimitry Andric // Check to see if all arguments are the same operation.
9081fd87a68SDimitry Andric for (Value *V : drop_begin(PN.incoming_values())) {
9091fd87a68SDimitry Andric Instruction *I = dyn_cast<Instruction>(V);
910e8d8bef9SDimitry Andric if (!I || !I->hasOneUser() || !I->isSameOperationAs(FirstInst))
9110b57cec5SDimitry Andric return nullptr;
9120b57cec5SDimitry Andric if (CastSrcTy) {
9130b57cec5SDimitry Andric if (I->getOperand(0)->getType() != CastSrcTy)
9140b57cec5SDimitry Andric return nullptr; // Cast operation must match.
9150b57cec5SDimitry Andric } else if (I->getOperand(1) != ConstantOp) {
9160b57cec5SDimitry Andric return nullptr;
9170b57cec5SDimitry Andric }
9180b57cec5SDimitry Andric }
9190b57cec5SDimitry Andric
9200b57cec5SDimitry Andric // Okay, they are all the same operation. Create a new PHI node of the
9210b57cec5SDimitry Andric // correct type, and PHI together all of the LHS's of the instructions.
9220b57cec5SDimitry Andric PHINode *NewPN = PHINode::Create(FirstInst->getOperand(0)->getType(),
9230b57cec5SDimitry Andric PN.getNumIncomingValues(),
9240b57cec5SDimitry Andric PN.getName()+".in");
9250b57cec5SDimitry Andric
9260b57cec5SDimitry Andric Value *InVal = FirstInst->getOperand(0);
9270b57cec5SDimitry Andric NewPN->addIncoming(InVal, PN.getIncomingBlock(0));
9280b57cec5SDimitry Andric
9290b57cec5SDimitry Andric // Add all operands to the new PHI.
9301fd87a68SDimitry Andric for (auto Incoming : drop_begin(zip(PN.blocks(), PN.incoming_values()))) {
9311fd87a68SDimitry Andric BasicBlock *BB = std::get<0>(Incoming);
9321fd87a68SDimitry Andric Value *V = std::get<1>(Incoming);
9331fd87a68SDimitry Andric Value *NewInVal = cast<Instruction>(V)->getOperand(0);
9340b57cec5SDimitry Andric if (NewInVal != InVal)
9350b57cec5SDimitry Andric InVal = nullptr;
9361fd87a68SDimitry Andric NewPN->addIncoming(NewInVal, BB);
9370b57cec5SDimitry Andric }
9380b57cec5SDimitry Andric
9390b57cec5SDimitry Andric Value *PhiVal;
9400b57cec5SDimitry Andric if (InVal) {
9410b57cec5SDimitry Andric // The new PHI unions all of the same values together. This is really
9420b57cec5SDimitry Andric // common, so we handle it intelligently here for compile-time speed.
9430b57cec5SDimitry Andric PhiVal = InVal;
9440b57cec5SDimitry Andric delete NewPN;
9450b57cec5SDimitry Andric } else {
9465f757f3fSDimitry Andric InsertNewInstBefore(NewPN, PN.getIterator());
9470b57cec5SDimitry Andric PhiVal = NewPN;
9480b57cec5SDimitry Andric }
9490b57cec5SDimitry Andric
9500b57cec5SDimitry Andric // Insert and return the new operation.
9510b57cec5SDimitry Andric if (CastInst *FirstCI = dyn_cast<CastInst>(FirstInst)) {
9520b57cec5SDimitry Andric CastInst *NewCI = CastInst::Create(FirstCI->getOpcode(), PhiVal,
9530b57cec5SDimitry Andric PN.getType());
9540b57cec5SDimitry Andric PHIArgMergedDebugLoc(NewCI, PN);
9550b57cec5SDimitry Andric return NewCI;
9560b57cec5SDimitry Andric }
9570b57cec5SDimitry Andric
9580b57cec5SDimitry Andric if (BinaryOperator *BinOp = dyn_cast<BinaryOperator>(FirstInst)) {
9590b57cec5SDimitry Andric BinOp = BinaryOperator::Create(BinOp->getOpcode(), PhiVal, ConstantOp);
9600b57cec5SDimitry Andric BinOp->copyIRFlags(PN.getIncomingValue(0));
9610b57cec5SDimitry Andric
9621fd87a68SDimitry Andric for (Value *V : drop_begin(PN.incoming_values()))
9631fd87a68SDimitry Andric BinOp->andIRFlags(V);
9640b57cec5SDimitry Andric
9650b57cec5SDimitry Andric PHIArgMergedDebugLoc(BinOp, PN);
9660b57cec5SDimitry Andric return BinOp;
9670b57cec5SDimitry Andric }
9680b57cec5SDimitry Andric
9690b57cec5SDimitry Andric CmpInst *CIOp = cast<CmpInst>(FirstInst);
9700b57cec5SDimitry Andric CmpInst *NewCI = CmpInst::Create(CIOp->getOpcode(), CIOp->getPredicate(),
9710b57cec5SDimitry Andric PhiVal, ConstantOp);
9720b57cec5SDimitry Andric PHIArgMergedDebugLoc(NewCI, PN);
9730b57cec5SDimitry Andric return NewCI;
9740b57cec5SDimitry Andric }
9750b57cec5SDimitry Andric
9760b57cec5SDimitry Andric /// Return true if this PHI node is only used by a PHI node cycle that is dead.
isDeadPHICycle(PHINode * PN,SmallPtrSetImpl<PHINode * > & PotentiallyDeadPHIs)9771fd87a68SDimitry Andric static bool isDeadPHICycle(PHINode *PN,
9780b57cec5SDimitry Andric SmallPtrSetImpl<PHINode *> &PotentiallyDeadPHIs) {
9790b57cec5SDimitry Andric if (PN->use_empty()) return true;
9800b57cec5SDimitry Andric if (!PN->hasOneUse()) return false;
9810b57cec5SDimitry Andric
9820b57cec5SDimitry Andric // Remember this node, and if we find the cycle, return.
9830b57cec5SDimitry Andric if (!PotentiallyDeadPHIs.insert(PN).second)
9840b57cec5SDimitry Andric return true;
9850b57cec5SDimitry Andric
9860b57cec5SDimitry Andric // Don't scan crazily complex things.
9870b57cec5SDimitry Andric if (PotentiallyDeadPHIs.size() == 16)
9880b57cec5SDimitry Andric return false;
9890b57cec5SDimitry Andric
9900b57cec5SDimitry Andric if (PHINode *PU = dyn_cast<PHINode>(PN->user_back()))
9911fd87a68SDimitry Andric return isDeadPHICycle(PU, PotentiallyDeadPHIs);
9920b57cec5SDimitry Andric
9930b57cec5SDimitry Andric return false;
9940b57cec5SDimitry Andric }
9950b57cec5SDimitry Andric
9960b57cec5SDimitry Andric /// Return true if this phi node is always equal to NonPhiInVal.
9970b57cec5SDimitry Andric /// This happens with mutually cyclic phi nodes like:
9980b57cec5SDimitry Andric /// z = some value; x = phi (y, z); y = phi (x, z)
PHIsEqualValue(PHINode * PN,Value * & NonPhiInVal,SmallPtrSetImpl<PHINode * > & ValueEqualPHIs)9995f757f3fSDimitry Andric static bool PHIsEqualValue(PHINode *PN, Value *&NonPhiInVal,
10000b57cec5SDimitry Andric SmallPtrSetImpl<PHINode *> &ValueEqualPHIs) {
10010b57cec5SDimitry Andric // See if we already saw this PHI node.
10020b57cec5SDimitry Andric if (!ValueEqualPHIs.insert(PN).second)
10030b57cec5SDimitry Andric return true;
10040b57cec5SDimitry Andric
10050b57cec5SDimitry Andric // Don't scan crazily complex things.
10060b57cec5SDimitry Andric if (ValueEqualPHIs.size() == 16)
10070b57cec5SDimitry Andric return false;
10080b57cec5SDimitry Andric
10090b57cec5SDimitry Andric // Scan the operands to see if they are either phi nodes or are equal to
10100b57cec5SDimitry Andric // the value.
10110b57cec5SDimitry Andric for (Value *Op : PN->incoming_values()) {
10120b57cec5SDimitry Andric if (PHINode *OpPN = dyn_cast<PHINode>(Op)) {
10135f757f3fSDimitry Andric if (!PHIsEqualValue(OpPN, NonPhiInVal, ValueEqualPHIs)) {
10145f757f3fSDimitry Andric if (NonPhiInVal)
10150b57cec5SDimitry Andric return false;
10165f757f3fSDimitry Andric NonPhiInVal = OpPN;
10175f757f3fSDimitry Andric }
10180b57cec5SDimitry Andric } else if (Op != NonPhiInVal)
10190b57cec5SDimitry Andric return false;
10200b57cec5SDimitry Andric }
10210b57cec5SDimitry Andric
10220b57cec5SDimitry Andric return true;
10230b57cec5SDimitry Andric }
10240b57cec5SDimitry Andric
10250b57cec5SDimitry Andric /// Return an existing non-zero constant if this phi node has one, otherwise
10260b57cec5SDimitry Andric /// return constant 1.
getAnyNonZeroConstInt(PHINode & PN)10271fd87a68SDimitry Andric static ConstantInt *getAnyNonZeroConstInt(PHINode &PN) {
10280b57cec5SDimitry Andric assert(isa<IntegerType>(PN.getType()) && "Expect only integer type phi");
10290b57cec5SDimitry Andric for (Value *V : PN.operands())
10300b57cec5SDimitry Andric if (auto *ConstVA = dyn_cast<ConstantInt>(V))
10310b57cec5SDimitry Andric if (!ConstVA->isZero())
10320b57cec5SDimitry Andric return ConstVA;
10330b57cec5SDimitry Andric return ConstantInt::get(cast<IntegerType>(PN.getType()), 1);
10340b57cec5SDimitry Andric }
10350b57cec5SDimitry Andric
10360b57cec5SDimitry Andric namespace {
10370b57cec5SDimitry Andric struct PHIUsageRecord {
10380b57cec5SDimitry Andric unsigned PHIId; // The ID # of the PHI (something determinstic to sort on)
10390b57cec5SDimitry Andric unsigned Shift; // The amount shifted.
10400b57cec5SDimitry Andric Instruction *Inst; // The trunc instruction.
10410b57cec5SDimitry Andric
PHIUsageRecord__anon063dd3dc0611::PHIUsageRecord10421fd87a68SDimitry Andric PHIUsageRecord(unsigned Pn, unsigned Sh, Instruction *User)
10431fd87a68SDimitry Andric : PHIId(Pn), Shift(Sh), Inst(User) {}
10440b57cec5SDimitry Andric
operator <__anon063dd3dc0611::PHIUsageRecord10450b57cec5SDimitry Andric bool operator<(const PHIUsageRecord &RHS) const {
10460b57cec5SDimitry Andric if (PHIId < RHS.PHIId) return true;
10470b57cec5SDimitry Andric if (PHIId > RHS.PHIId) return false;
10480b57cec5SDimitry Andric if (Shift < RHS.Shift) return true;
10490b57cec5SDimitry Andric if (Shift > RHS.Shift) return false;
10500b57cec5SDimitry Andric return Inst->getType()->getPrimitiveSizeInBits() <
10510b57cec5SDimitry Andric RHS.Inst->getType()->getPrimitiveSizeInBits();
10520b57cec5SDimitry Andric }
10530b57cec5SDimitry Andric };
10540b57cec5SDimitry Andric
10550b57cec5SDimitry Andric struct LoweredPHIRecord {
10560b57cec5SDimitry Andric PHINode *PN; // The PHI that was lowered.
10570b57cec5SDimitry Andric unsigned Shift; // The amount shifted.
10580b57cec5SDimitry Andric unsigned Width; // The width extracted.
10590b57cec5SDimitry Andric
LoweredPHIRecord__anon063dd3dc0611::LoweredPHIRecord10601fd87a68SDimitry Andric LoweredPHIRecord(PHINode *Phi, unsigned Sh, Type *Ty)
10611fd87a68SDimitry Andric : PN(Phi), Shift(Sh), Width(Ty->getPrimitiveSizeInBits()) {}
10620b57cec5SDimitry Andric
10630b57cec5SDimitry Andric // Ctor form used by DenseMap.
LoweredPHIRecord__anon063dd3dc0611::LoweredPHIRecord10641fd87a68SDimitry Andric LoweredPHIRecord(PHINode *Phi, unsigned Sh) : PN(Phi), Shift(Sh), Width(0) {}
10650b57cec5SDimitry Andric };
1066e8d8bef9SDimitry Andric } // namespace
10670b57cec5SDimitry Andric
10680b57cec5SDimitry Andric namespace llvm {
10690b57cec5SDimitry Andric template<>
10700b57cec5SDimitry Andric struct DenseMapInfo<LoweredPHIRecord> {
getEmptyKeyllvm::DenseMapInfo10710b57cec5SDimitry Andric static inline LoweredPHIRecord getEmptyKey() {
10720b57cec5SDimitry Andric return LoweredPHIRecord(nullptr, 0);
10730b57cec5SDimitry Andric }
getTombstoneKeyllvm::DenseMapInfo10740b57cec5SDimitry Andric static inline LoweredPHIRecord getTombstoneKey() {
10750b57cec5SDimitry Andric return LoweredPHIRecord(nullptr, 1);
10760b57cec5SDimitry Andric }
getHashValuellvm::DenseMapInfo10770b57cec5SDimitry Andric static unsigned getHashValue(const LoweredPHIRecord &Val) {
10780b57cec5SDimitry Andric return DenseMapInfo<PHINode*>::getHashValue(Val.PN) ^ (Val.Shift>>3) ^
10790b57cec5SDimitry Andric (Val.Width>>3);
10800b57cec5SDimitry Andric }
isEqualllvm::DenseMapInfo10810b57cec5SDimitry Andric static bool isEqual(const LoweredPHIRecord &LHS,
10820b57cec5SDimitry Andric const LoweredPHIRecord &RHS) {
10830b57cec5SDimitry Andric return LHS.PN == RHS.PN && LHS.Shift == RHS.Shift &&
10840b57cec5SDimitry Andric LHS.Width == RHS.Width;
10850b57cec5SDimitry Andric }
10860b57cec5SDimitry Andric };
1087e8d8bef9SDimitry Andric } // namespace llvm
10880b57cec5SDimitry Andric
10890b57cec5SDimitry Andric
10900b57cec5SDimitry Andric /// This is an integer PHI and we know that it has an illegal type: see if it is
10910b57cec5SDimitry Andric /// only used by trunc or trunc(lshr) operations. If so, we split the PHI into
10920b57cec5SDimitry Andric /// the various pieces being extracted. This sort of thing is introduced when
10930b57cec5SDimitry Andric /// SROA promotes an aggregate to large integer values.
10940b57cec5SDimitry Andric ///
10950b57cec5SDimitry Andric /// TODO: The user of the trunc may be an bitcast to float/double/vector or an
10960b57cec5SDimitry Andric /// inttoptr. We should produce new PHIs in the right type.
10970b57cec5SDimitry Andric ///
SliceUpIllegalIntegerPHI(PHINode & FirstPhi)1098e8d8bef9SDimitry Andric Instruction *InstCombinerImpl::SliceUpIllegalIntegerPHI(PHINode &FirstPhi) {
10990b57cec5SDimitry Andric // PHIUsers - Keep track of all of the truncated values extracted from a set
11000b57cec5SDimitry Andric // of PHIs, along with their offset. These are the things we want to rewrite.
11010b57cec5SDimitry Andric SmallVector<PHIUsageRecord, 16> PHIUsers;
11020b57cec5SDimitry Andric
11030b57cec5SDimitry Andric // PHIs are often mutually cyclic, so we keep track of a whole set of PHI
11040b57cec5SDimitry Andric // nodes which are extracted from. PHIsToSlice is a set we use to avoid
11050b57cec5SDimitry Andric // revisiting PHIs, PHIsInspected is a ordered list of PHIs that we need to
11060b57cec5SDimitry Andric // check the uses of (to ensure they are all extracts).
11070b57cec5SDimitry Andric SmallVector<PHINode*, 8> PHIsToSlice;
11080b57cec5SDimitry Andric SmallPtrSet<PHINode*, 8> PHIsInspected;
11090b57cec5SDimitry Andric
11100b57cec5SDimitry Andric PHIsToSlice.push_back(&FirstPhi);
11110b57cec5SDimitry Andric PHIsInspected.insert(&FirstPhi);
11120b57cec5SDimitry Andric
11130b57cec5SDimitry Andric for (unsigned PHIId = 0; PHIId != PHIsToSlice.size(); ++PHIId) {
11140b57cec5SDimitry Andric PHINode *PN = PHIsToSlice[PHIId];
11150b57cec5SDimitry Andric
11160b57cec5SDimitry Andric // Scan the input list of the PHI. If any input is an invoke, and if the
11170b57cec5SDimitry Andric // input is defined in the predecessor, then we won't be split the critical
11180b57cec5SDimitry Andric // edge which is required to insert a truncate. Because of this, we have to
11190b57cec5SDimitry Andric // bail out.
11201fd87a68SDimitry Andric for (auto Incoming : zip(PN->blocks(), PN->incoming_values())) {
11211fd87a68SDimitry Andric BasicBlock *BB = std::get<0>(Incoming);
11221fd87a68SDimitry Andric Value *V = std::get<1>(Incoming);
11231fd87a68SDimitry Andric InvokeInst *II = dyn_cast<InvokeInst>(V);
11241fd87a68SDimitry Andric if (!II)
11251fd87a68SDimitry Andric continue;
11261fd87a68SDimitry Andric if (II->getParent() != BB)
11270b57cec5SDimitry Andric continue;
11280b57cec5SDimitry Andric
11290b57cec5SDimitry Andric // If we have a phi, and if it's directly in the predecessor, then we have
11300b57cec5SDimitry Andric // a critical edge where we need to put the truncate. Since we can't
11310b57cec5SDimitry Andric // split the edge in instcombine, we have to bail out.
11320b57cec5SDimitry Andric return nullptr;
11330b57cec5SDimitry Andric }
11340b57cec5SDimitry Andric
113581ad6265SDimitry Andric // If the incoming value is a PHI node before a catchswitch, we cannot
113681ad6265SDimitry Andric // extract the value within that BB because we cannot insert any non-PHI
113781ad6265SDimitry Andric // instructions in the BB.
113881ad6265SDimitry Andric for (auto *Pred : PN->blocks())
113981ad6265SDimitry Andric if (Pred->getFirstInsertionPt() == Pred->end())
114081ad6265SDimitry Andric return nullptr;
114181ad6265SDimitry Andric
11420b57cec5SDimitry Andric for (User *U : PN->users()) {
11430b57cec5SDimitry Andric Instruction *UserI = cast<Instruction>(U);
11440b57cec5SDimitry Andric
11450b57cec5SDimitry Andric // If the user is a PHI, inspect its uses recursively.
11460b57cec5SDimitry Andric if (PHINode *UserPN = dyn_cast<PHINode>(UserI)) {
11470b57cec5SDimitry Andric if (PHIsInspected.insert(UserPN).second)
11480b57cec5SDimitry Andric PHIsToSlice.push_back(UserPN);
11490b57cec5SDimitry Andric continue;
11500b57cec5SDimitry Andric }
11510b57cec5SDimitry Andric
11520b57cec5SDimitry Andric // Truncates are always ok.
11530b57cec5SDimitry Andric if (isa<TruncInst>(UserI)) {
11540b57cec5SDimitry Andric PHIUsers.push_back(PHIUsageRecord(PHIId, 0, UserI));
11550b57cec5SDimitry Andric continue;
11560b57cec5SDimitry Andric }
11570b57cec5SDimitry Andric
11580b57cec5SDimitry Andric // Otherwise it must be a lshr which can only be used by one trunc.
11590b57cec5SDimitry Andric if (UserI->getOpcode() != Instruction::LShr ||
11600b57cec5SDimitry Andric !UserI->hasOneUse() || !isa<TruncInst>(UserI->user_back()) ||
11610b57cec5SDimitry Andric !isa<ConstantInt>(UserI->getOperand(1)))
11620b57cec5SDimitry Andric return nullptr;
11630b57cec5SDimitry Andric
11640b57cec5SDimitry Andric // Bail on out of range shifts.
11650b57cec5SDimitry Andric unsigned SizeInBits = UserI->getType()->getScalarSizeInBits();
11660b57cec5SDimitry Andric if (cast<ConstantInt>(UserI->getOperand(1))->getValue().uge(SizeInBits))
11670b57cec5SDimitry Andric return nullptr;
11680b57cec5SDimitry Andric
11690b57cec5SDimitry Andric unsigned Shift = cast<ConstantInt>(UserI->getOperand(1))->getZExtValue();
11700b57cec5SDimitry Andric PHIUsers.push_back(PHIUsageRecord(PHIId, Shift, UserI->user_back()));
11710b57cec5SDimitry Andric }
11720b57cec5SDimitry Andric }
11730b57cec5SDimitry Andric
11740b57cec5SDimitry Andric // If we have no users, they must be all self uses, just nuke the PHI.
11750b57cec5SDimitry Andric if (PHIUsers.empty())
1176fe6060f1SDimitry Andric return replaceInstUsesWith(FirstPhi, PoisonValue::get(FirstPhi.getType()));
11770b57cec5SDimitry Andric
11780b57cec5SDimitry Andric // If this phi node is transformable, create new PHIs for all the pieces
11790b57cec5SDimitry Andric // extracted out of it. First, sort the users by their offset and size.
11800b57cec5SDimitry Andric array_pod_sort(PHIUsers.begin(), PHIUsers.end());
11810b57cec5SDimitry Andric
11820b57cec5SDimitry Andric LLVM_DEBUG(dbgs() << "SLICING UP PHI: " << FirstPhi << '\n';
11831fd87a68SDimitry Andric for (unsigned I = 1; I != PHIsToSlice.size(); ++I) dbgs()
11841fd87a68SDimitry Andric << "AND USER PHI #" << I << ": " << *PHIsToSlice[I] << '\n');
11850b57cec5SDimitry Andric
11860b57cec5SDimitry Andric // PredValues - This is a temporary used when rewriting PHI nodes. It is
11870b57cec5SDimitry Andric // hoisted out here to avoid construction/destruction thrashing.
11880b57cec5SDimitry Andric DenseMap<BasicBlock*, Value*> PredValues;
11890b57cec5SDimitry Andric
11900b57cec5SDimitry Andric // ExtractedVals - Each new PHI we introduce is saved here so we don't
11910b57cec5SDimitry Andric // introduce redundant PHIs.
11920b57cec5SDimitry Andric DenseMap<LoweredPHIRecord, PHINode*> ExtractedVals;
11930b57cec5SDimitry Andric
11940b57cec5SDimitry Andric for (unsigned UserI = 0, UserE = PHIUsers.size(); UserI != UserE; ++UserI) {
11950b57cec5SDimitry Andric unsigned PHIId = PHIUsers[UserI].PHIId;
11960b57cec5SDimitry Andric PHINode *PN = PHIsToSlice[PHIId];
11970b57cec5SDimitry Andric unsigned Offset = PHIUsers[UserI].Shift;
11980b57cec5SDimitry Andric Type *Ty = PHIUsers[UserI].Inst->getType();
11990b57cec5SDimitry Andric
12000b57cec5SDimitry Andric PHINode *EltPHI;
12010b57cec5SDimitry Andric
12020b57cec5SDimitry Andric // If we've already lowered a user like this, reuse the previously lowered
12030b57cec5SDimitry Andric // value.
12040b57cec5SDimitry Andric if ((EltPHI = ExtractedVals[LoweredPHIRecord(PN, Offset, Ty)]) == nullptr) {
12050b57cec5SDimitry Andric
12060b57cec5SDimitry Andric // Otherwise, Create the new PHI node for this user.
12070b57cec5SDimitry Andric EltPHI = PHINode::Create(Ty, PN->getNumIncomingValues(),
12080b57cec5SDimitry Andric PN->getName()+".off"+Twine(Offset), PN);
12090b57cec5SDimitry Andric assert(EltPHI->getType() != PN->getType() &&
12100b57cec5SDimitry Andric "Truncate didn't shrink phi?");
12110b57cec5SDimitry Andric
12121fd87a68SDimitry Andric for (auto Incoming : zip(PN->blocks(), PN->incoming_values())) {
12131fd87a68SDimitry Andric BasicBlock *Pred = std::get<0>(Incoming);
12141fd87a68SDimitry Andric Value *InVal = std::get<1>(Incoming);
12150b57cec5SDimitry Andric Value *&PredVal = PredValues[Pred];
12160b57cec5SDimitry Andric
12170b57cec5SDimitry Andric // If we already have a value for this predecessor, reuse it.
12180b57cec5SDimitry Andric if (PredVal) {
12190b57cec5SDimitry Andric EltPHI->addIncoming(PredVal, Pred);
12200b57cec5SDimitry Andric continue;
12210b57cec5SDimitry Andric }
12220b57cec5SDimitry Andric
12230b57cec5SDimitry Andric // Handle the PHI self-reuse case.
12240b57cec5SDimitry Andric if (InVal == PN) {
12250b57cec5SDimitry Andric PredVal = EltPHI;
12260b57cec5SDimitry Andric EltPHI->addIncoming(PredVal, Pred);
12270b57cec5SDimitry Andric continue;
12280b57cec5SDimitry Andric }
12290b57cec5SDimitry Andric
12300b57cec5SDimitry Andric if (PHINode *InPHI = dyn_cast<PHINode>(PN)) {
12310b57cec5SDimitry Andric // If the incoming value was a PHI, and if it was one of the PHIs we
12320b57cec5SDimitry Andric // already rewrote it, just use the lowered value.
12330b57cec5SDimitry Andric if (Value *Res = ExtractedVals[LoweredPHIRecord(InPHI, Offset, Ty)]) {
12340b57cec5SDimitry Andric PredVal = Res;
12350b57cec5SDimitry Andric EltPHI->addIncoming(PredVal, Pred);
12360b57cec5SDimitry Andric continue;
12370b57cec5SDimitry Andric }
12380b57cec5SDimitry Andric }
12390b57cec5SDimitry Andric
12400b57cec5SDimitry Andric // Otherwise, do an extract in the predecessor.
12410b57cec5SDimitry Andric Builder.SetInsertPoint(Pred->getTerminator());
12420b57cec5SDimitry Andric Value *Res = InVal;
12430b57cec5SDimitry Andric if (Offset)
12441fd87a68SDimitry Andric Res = Builder.CreateLShr(
12451fd87a68SDimitry Andric Res, ConstantInt::get(InVal->getType(), Offset), "extract");
12460b57cec5SDimitry Andric Res = Builder.CreateTrunc(Res, Ty, "extract.t");
12470b57cec5SDimitry Andric PredVal = Res;
12480b57cec5SDimitry Andric EltPHI->addIncoming(Res, Pred);
12490b57cec5SDimitry Andric
12500b57cec5SDimitry Andric // If the incoming value was a PHI, and if it was one of the PHIs we are
12510b57cec5SDimitry Andric // rewriting, we will ultimately delete the code we inserted. This
12520b57cec5SDimitry Andric // means we need to revisit that PHI to make sure we extract out the
12530b57cec5SDimitry Andric // needed piece.
12541fd87a68SDimitry Andric if (PHINode *OldInVal = dyn_cast<PHINode>(InVal))
12550b57cec5SDimitry Andric if (PHIsInspected.count(OldInVal)) {
12560b57cec5SDimitry Andric unsigned RefPHIId =
12570b57cec5SDimitry Andric find(PHIsToSlice, OldInVal) - PHIsToSlice.begin();
12581fd87a68SDimitry Andric PHIUsers.push_back(
12591fd87a68SDimitry Andric PHIUsageRecord(RefPHIId, Offset, cast<Instruction>(Res)));
12600b57cec5SDimitry Andric ++UserE;
12610b57cec5SDimitry Andric }
12620b57cec5SDimitry Andric }
12630b57cec5SDimitry Andric PredValues.clear();
12640b57cec5SDimitry Andric
12650b57cec5SDimitry Andric LLVM_DEBUG(dbgs() << " Made element PHI for offset " << Offset << ": "
12660b57cec5SDimitry Andric << *EltPHI << '\n');
12670b57cec5SDimitry Andric ExtractedVals[LoweredPHIRecord(PN, Offset, Ty)] = EltPHI;
12680b57cec5SDimitry Andric }
12690b57cec5SDimitry Andric
12700b57cec5SDimitry Andric // Replace the use of this piece with the PHI node.
12710b57cec5SDimitry Andric replaceInstUsesWith(*PHIUsers[UserI].Inst, EltPHI);
12720b57cec5SDimitry Andric }
12730b57cec5SDimitry Andric
12740b57cec5SDimitry Andric // Replace all the remaining uses of the PHI nodes (self uses and the lshrs)
1275fe6060f1SDimitry Andric // with poison.
1276fe6060f1SDimitry Andric Value *Poison = PoisonValue::get(FirstPhi.getType());
12771fd87a68SDimitry Andric for (PHINode *PHI : drop_begin(PHIsToSlice))
12781fd87a68SDimitry Andric replaceInstUsesWith(*PHI, Poison);
1279fe6060f1SDimitry Andric return replaceInstUsesWith(FirstPhi, Poison);
12800b57cec5SDimitry Andric }
12810b57cec5SDimitry Andric
simplifyUsingControlFlow(InstCombiner & Self,PHINode & PN,const DominatorTree & DT)12821fd87a68SDimitry Andric static Value *simplifyUsingControlFlow(InstCombiner &Self, PHINode &PN,
1283e8d8bef9SDimitry Andric const DominatorTree &DT) {
1284e8d8bef9SDimitry Andric // Simplify the following patterns:
1285e8d8bef9SDimitry Andric // if (cond)
1286e8d8bef9SDimitry Andric // / \
1287e8d8bef9SDimitry Andric // ... ...
1288e8d8bef9SDimitry Andric // \ /
1289e8d8bef9SDimitry Andric // phi [true] [false]
129081ad6265SDimitry Andric // and
129181ad6265SDimitry Andric // switch (cond)
129281ad6265SDimitry Andric // case v1: / \ case v2:
129381ad6265SDimitry Andric // ... ...
129481ad6265SDimitry Andric // \ /
129581ad6265SDimitry Andric // phi [v1] [v2]
1296e8d8bef9SDimitry Andric // Make sure all inputs are constants.
1297e8d8bef9SDimitry Andric if (!all_of(PN.operands(), [](Value *V) { return isa<ConstantInt>(V); }))
1298e8d8bef9SDimitry Andric return nullptr;
1299e8d8bef9SDimitry Andric
1300e8d8bef9SDimitry Andric BasicBlock *BB = PN.getParent();
1301e8d8bef9SDimitry Andric // Do not bother with unreachable instructions.
1302e8d8bef9SDimitry Andric if (!DT.isReachableFromEntry(BB))
1303e8d8bef9SDimitry Andric return nullptr;
1304e8d8bef9SDimitry Andric
130581ad6265SDimitry Andric // Determine which value the condition of the idom has for which successor.
130681ad6265SDimitry Andric LLVMContext &Context = PN.getContext();
1307e8d8bef9SDimitry Andric auto *IDom = DT.getNode(BB)->getIDom()->getBlock();
130881ad6265SDimitry Andric Value *Cond;
130981ad6265SDimitry Andric SmallDenseMap<ConstantInt *, BasicBlock *, 8> SuccForValue;
131081ad6265SDimitry Andric SmallDenseMap<BasicBlock *, unsigned, 8> SuccCount;
131181ad6265SDimitry Andric auto AddSucc = [&](ConstantInt *C, BasicBlock *Succ) {
131281ad6265SDimitry Andric SuccForValue[C] = Succ;
131381ad6265SDimitry Andric ++SuccCount[Succ];
131481ad6265SDimitry Andric };
131581ad6265SDimitry Andric if (auto *BI = dyn_cast<BranchInst>(IDom->getTerminator())) {
131681ad6265SDimitry Andric if (BI->isUnconditional())
131781ad6265SDimitry Andric return nullptr;
131881ad6265SDimitry Andric
131981ad6265SDimitry Andric Cond = BI->getCondition();
132081ad6265SDimitry Andric AddSucc(ConstantInt::getTrue(Context), BI->getSuccessor(0));
132181ad6265SDimitry Andric AddSucc(ConstantInt::getFalse(Context), BI->getSuccessor(1));
132281ad6265SDimitry Andric } else if (auto *SI = dyn_cast<SwitchInst>(IDom->getTerminator())) {
132381ad6265SDimitry Andric Cond = SI->getCondition();
132481ad6265SDimitry Andric ++SuccCount[SI->getDefaultDest()];
132581ad6265SDimitry Andric for (auto Case : SI->cases())
132681ad6265SDimitry Andric AddSucc(Case.getCaseValue(), Case.getCaseSuccessor());
132781ad6265SDimitry Andric } else {
132881ad6265SDimitry Andric return nullptr;
132981ad6265SDimitry Andric }
133081ad6265SDimitry Andric
133181ad6265SDimitry Andric if (Cond->getType() != PN.getType())
1332e8d8bef9SDimitry Andric return nullptr;
1333e8d8bef9SDimitry Andric
1334e8d8bef9SDimitry Andric // Check that edges outgoing from the idom's terminators dominate respective
1335e8d8bef9SDimitry Andric // inputs of the Phi.
1336bdd1243dSDimitry Andric std::optional<bool> Invert;
133781ad6265SDimitry Andric for (auto Pair : zip(PN.incoming_values(), PN.blocks())) {
133881ad6265SDimitry Andric auto *Input = cast<ConstantInt>(std::get<0>(Pair));
133981ad6265SDimitry Andric BasicBlock *Pred = std::get<1>(Pair);
134081ad6265SDimitry Andric auto IsCorrectInput = [&](ConstantInt *Input) {
134181ad6265SDimitry Andric // The input needs to be dominated by the corresponding edge of the idom.
134281ad6265SDimitry Andric // This edge cannot be a multi-edge, as that would imply that multiple
134381ad6265SDimitry Andric // different condition values follow the same edge.
134481ad6265SDimitry Andric auto It = SuccForValue.find(Input);
134581ad6265SDimitry Andric return It != SuccForValue.end() && SuccCount[It->second] == 1 &&
134681ad6265SDimitry Andric DT.dominates(BasicBlockEdge(IDom, It->second),
134781ad6265SDimitry Andric BasicBlockEdge(Pred, BB));
134881ad6265SDimitry Andric };
1349e8d8bef9SDimitry Andric
135081ad6265SDimitry Andric // Depending on the constant, the condition may need to be inverted.
135181ad6265SDimitry Andric bool NeedsInvert;
135281ad6265SDimitry Andric if (IsCorrectInput(Input))
135381ad6265SDimitry Andric NeedsInvert = false;
135481ad6265SDimitry Andric else if (IsCorrectInput(cast<ConstantInt>(ConstantExpr::getNot(Input))))
135581ad6265SDimitry Andric NeedsInvert = true;
135681ad6265SDimitry Andric else
135781ad6265SDimitry Andric return nullptr;
1358e8d8bef9SDimitry Andric
135981ad6265SDimitry Andric // Make sure the inversion requirement is always the same.
136081ad6265SDimitry Andric if (Invert && *Invert != NeedsInvert)
136181ad6265SDimitry Andric return nullptr;
136281ad6265SDimitry Andric
136381ad6265SDimitry Andric Invert = NeedsInvert;
136481ad6265SDimitry Andric }
136581ad6265SDimitry Andric
136681ad6265SDimitry Andric if (!*Invert)
1367e8d8bef9SDimitry Andric return Cond;
136881ad6265SDimitry Andric
1369e8d8bef9SDimitry Andric // This Phi is actually opposite to branching condition of IDom. We invert
1370e8d8bef9SDimitry Andric // the condition that will potentially open up some opportunities for
1371e8d8bef9SDimitry Andric // sinking.
1372e8d8bef9SDimitry Andric auto InsertPt = BB->getFirstInsertionPt();
1373e8d8bef9SDimitry Andric if (InsertPt != BB->end()) {
13745f757f3fSDimitry Andric Self.Builder.SetInsertPoint(&*BB, InsertPt);
1375e8d8bef9SDimitry Andric return Self.Builder.CreateNot(Cond);
1376e8d8bef9SDimitry Andric }
1377e8d8bef9SDimitry Andric
1378e8d8bef9SDimitry Andric return nullptr;
1379e8d8bef9SDimitry Andric }
1380e8d8bef9SDimitry Andric
13810b57cec5SDimitry Andric // PHINode simplification
13820b57cec5SDimitry Andric //
visitPHINode(PHINode & PN)1383e8d8bef9SDimitry Andric Instruction *InstCombinerImpl::visitPHINode(PHINode &PN) {
138481ad6265SDimitry Andric if (Value *V = simplifyInstruction(&PN, SQ.getWithInstruction(&PN)))
13850b57cec5SDimitry Andric return replaceInstUsesWith(PN, V);
13860b57cec5SDimitry Andric
1387e8d8bef9SDimitry Andric if (Instruction *Result = foldPHIArgZextsIntoPHI(PN))
13880b57cec5SDimitry Andric return Result;
13890b57cec5SDimitry Andric
1390349cc55cSDimitry Andric if (Instruction *Result = foldPHIArgIntToPtrToPHI(PN))
1391349cc55cSDimitry Andric return Result;
1392349cc55cSDimitry Andric
13930b57cec5SDimitry Andric // If all PHI operands are the same operation, pull them through the PHI,
13940b57cec5SDimitry Andric // reducing code size.
139506c3fb27SDimitry Andric auto *Inst0 = dyn_cast<Instruction>(PN.getIncomingValue(0));
139606c3fb27SDimitry Andric auto *Inst1 = dyn_cast<Instruction>(PN.getIncomingValue(1));
139706c3fb27SDimitry Andric if (Inst0 && Inst1 && Inst0->getOpcode() == Inst1->getOpcode() &&
139806c3fb27SDimitry Andric Inst0->hasOneUser())
1399e8d8bef9SDimitry Andric if (Instruction *Result = foldPHIArgOpIntoPHI(PN))
14000b57cec5SDimitry Andric return Result;
14010b57cec5SDimitry Andric
1402fe6060f1SDimitry Andric // If the incoming values are pointer casts of the same original value,
1403fe6060f1SDimitry Andric // replace the phi with a single cast iff we can insert a non-PHI instruction.
1404fe6060f1SDimitry Andric if (PN.getType()->isPointerTy() &&
1405fe6060f1SDimitry Andric PN.getParent()->getFirstInsertionPt() != PN.getParent()->end()) {
1406fe6060f1SDimitry Andric Value *IV0 = PN.getIncomingValue(0);
1407fe6060f1SDimitry Andric Value *IV0Stripped = IV0->stripPointerCasts();
1408fe6060f1SDimitry Andric // Set to keep track of values known to be equal to IV0Stripped after
1409fe6060f1SDimitry Andric // stripping pointer casts.
1410fe6060f1SDimitry Andric SmallPtrSet<Value *, 4> CheckedIVs;
1411fe6060f1SDimitry Andric CheckedIVs.insert(IV0);
1412fe6060f1SDimitry Andric if (IV0 != IV0Stripped &&
1413fe6060f1SDimitry Andric all_of(PN.incoming_values(), [&CheckedIVs, IV0Stripped](Value *IV) {
1414fe6060f1SDimitry Andric return !CheckedIVs.insert(IV).second ||
1415fe6060f1SDimitry Andric IV0Stripped == IV->stripPointerCasts();
1416fe6060f1SDimitry Andric })) {
1417fe6060f1SDimitry Andric return CastInst::CreatePointerCast(IV0Stripped, PN.getType());
1418fe6060f1SDimitry Andric }
1419fe6060f1SDimitry Andric }
1420fe6060f1SDimitry Andric
14210b57cec5SDimitry Andric // If this is a trivial cycle in the PHI node graph, remove it. Basically, if
14220b57cec5SDimitry Andric // this PHI only has a single use (a PHI), and if that PHI only has one use (a
14230b57cec5SDimitry Andric // PHI)... break the cycle.
14240b57cec5SDimitry Andric if (PN.hasOneUse()) {
1425bdd1243dSDimitry Andric if (foldIntegerTypedPHI(PN))
1426bdd1243dSDimitry Andric return nullptr;
14270b57cec5SDimitry Andric
14280b57cec5SDimitry Andric Instruction *PHIUser = cast<Instruction>(PN.user_back());
14290b57cec5SDimitry Andric if (PHINode *PU = dyn_cast<PHINode>(PHIUser)) {
14300b57cec5SDimitry Andric SmallPtrSet<PHINode*, 16> PotentiallyDeadPHIs;
14310b57cec5SDimitry Andric PotentiallyDeadPHIs.insert(&PN);
14321fd87a68SDimitry Andric if (isDeadPHICycle(PU, PotentiallyDeadPHIs))
1433fe6060f1SDimitry Andric return replaceInstUsesWith(PN, PoisonValue::get(PN.getType()));
14340b57cec5SDimitry Andric }
14350b57cec5SDimitry Andric
14360b57cec5SDimitry Andric // If this phi has a single use, and if that use just computes a value for
14370b57cec5SDimitry Andric // the next iteration of a loop, delete the phi. This occurs with unused
14380b57cec5SDimitry Andric // induction variables, e.g. "for (int j = 0; ; ++j);". Detecting this
14390b57cec5SDimitry Andric // common case here is good because the only other things that catch this
14400b57cec5SDimitry Andric // are induction variable analysis (sometimes) and ADCE, which is only run
14410b57cec5SDimitry Andric // late.
14420b57cec5SDimitry Andric if (PHIUser->hasOneUse() &&
14435f757f3fSDimitry Andric (isa<BinaryOperator>(PHIUser) || isa<UnaryOperator>(PHIUser) ||
14445f757f3fSDimitry Andric isa<GetElementPtrInst>(PHIUser)) &&
14450b57cec5SDimitry Andric PHIUser->user_back() == &PN) {
1446fe6060f1SDimitry Andric return replaceInstUsesWith(PN, PoisonValue::get(PN.getType()));
14470b57cec5SDimitry Andric }
14485f757f3fSDimitry Andric }
14495f757f3fSDimitry Andric
14500b57cec5SDimitry Andric // When a PHI is used only to be compared with zero, it is safe to replace
14510b57cec5SDimitry Andric // an incoming value proved as known nonzero with any non-zero constant.
14520b57cec5SDimitry Andric // For example, in the code below, the incoming value %v can be replaced
14530b57cec5SDimitry Andric // with any non-zero constant based on the fact that the PHI is only used to
14540b57cec5SDimitry Andric // be compared with zero and %v is a known non-zero value:
14550b57cec5SDimitry Andric // %v = select %cond, 1, 2
14560b57cec5SDimitry Andric // %p = phi [%v, BB] ...
14570b57cec5SDimitry Andric // icmp eq, %p, 0
14580b57cec5SDimitry Andric // FIXME: To be simple, handle only integer type for now.
14595f757f3fSDimitry Andric // This handles a small number of uses to keep the complexity down, and an
14605f757f3fSDimitry Andric // icmp(or(phi)) can equally be replaced with any non-zero constant as the
14615f757f3fSDimitry Andric // "or" will only add bits.
14625f757f3fSDimitry Andric if (!PN.hasNUsesOrMore(3)) {
14635f757f3fSDimitry Andric SmallVector<Instruction *> DropPoisonFlags;
14645f757f3fSDimitry Andric bool AllUsesOfPhiEndsInCmp = all_of(PN.users(), [&](User *U) {
14655f757f3fSDimitry Andric auto *CmpInst = dyn_cast<ICmpInst>(U);
14665f757f3fSDimitry Andric if (!CmpInst) {
14675f757f3fSDimitry Andric // This is always correct as OR only add bits and we are checking
14685f757f3fSDimitry Andric // against 0.
14695f757f3fSDimitry Andric if (U->hasOneUse() && match(U, m_c_Or(m_Specific(&PN), m_Value()))) {
14705f757f3fSDimitry Andric DropPoisonFlags.push_back(cast<Instruction>(U));
14715f757f3fSDimitry Andric CmpInst = dyn_cast<ICmpInst>(U->user_back());
14725f757f3fSDimitry Andric }
14735f757f3fSDimitry Andric }
14745f757f3fSDimitry Andric if (!CmpInst || !isa<IntegerType>(PN.getType()) ||
14755f757f3fSDimitry Andric !CmpInst->isEquality() || !match(CmpInst->getOperand(1), m_Zero())) {
14765f757f3fSDimitry Andric return false;
14775f757f3fSDimitry Andric }
14785f757f3fSDimitry Andric return true;
14795f757f3fSDimitry Andric });
14805f757f3fSDimitry Andric // All uses of PHI results in a compare with zero.
14815f757f3fSDimitry Andric if (AllUsesOfPhiEndsInCmp) {
14820b57cec5SDimitry Andric ConstantInt *NonZeroConst = nullptr;
14835ffd83dbSDimitry Andric bool MadeChange = false;
14841fd87a68SDimitry Andric for (unsigned I = 0, E = PN.getNumIncomingValues(); I != E; ++I) {
14851fd87a68SDimitry Andric Instruction *CtxI = PN.getIncomingBlock(I)->getTerminator();
14861fd87a68SDimitry Andric Value *VA = PN.getIncomingValue(I);
14870b57cec5SDimitry Andric if (isKnownNonZero(VA, DL, 0, &AC, CtxI, &DT)) {
14880b57cec5SDimitry Andric if (!NonZeroConst)
14891fd87a68SDimitry Andric NonZeroConst = getAnyNonZeroConstInt(PN);
14905ffd83dbSDimitry Andric if (NonZeroConst != VA) {
14911fd87a68SDimitry Andric replaceOperand(PN, I, NonZeroConst);
14925f757f3fSDimitry Andric // The "disjoint" flag may no longer hold after the transform.
14935f757f3fSDimitry Andric for (Instruction *I : DropPoisonFlags)
14945f757f3fSDimitry Andric I->dropPoisonGeneratingFlags();
14955ffd83dbSDimitry Andric MadeChange = true;
14960b57cec5SDimitry Andric }
14970b57cec5SDimitry Andric }
14980b57cec5SDimitry Andric }
14995ffd83dbSDimitry Andric if (MadeChange)
15005ffd83dbSDimitry Andric return &PN;
15015ffd83dbSDimitry Andric }
15020b57cec5SDimitry Andric }
15030b57cec5SDimitry Andric
15040b57cec5SDimitry Andric // We sometimes end up with phi cycles that non-obviously end up being the
15050b57cec5SDimitry Andric // same value, for example:
15060b57cec5SDimitry Andric // z = some value; x = phi (y, z); y = phi (x, z)
15070b57cec5SDimitry Andric // where the phi nodes don't necessarily need to be in the same block. Do a
15080b57cec5SDimitry Andric // quick check to see if the PHI node only contains a single non-phi value, if
15095f757f3fSDimitry Andric // so, scan to see if the phi cycle is actually equal to that value. If the
15105f757f3fSDimitry Andric // phi has no non-phi values then allow the "NonPhiInVal" to be set later if
15115f757f3fSDimitry Andric // one of the phis itself does not have a single input.
15120b57cec5SDimitry Andric {
15130b57cec5SDimitry Andric unsigned InValNo = 0, NumIncomingVals = PN.getNumIncomingValues();
15140b57cec5SDimitry Andric // Scan for the first non-phi operand.
15150b57cec5SDimitry Andric while (InValNo != NumIncomingVals &&
15160b57cec5SDimitry Andric isa<PHINode>(PN.getIncomingValue(InValNo)))
15170b57cec5SDimitry Andric ++InValNo;
15180b57cec5SDimitry Andric
15195f757f3fSDimitry Andric Value *NonPhiInVal =
15205f757f3fSDimitry Andric InValNo != NumIncomingVals ? PN.getIncomingValue(InValNo) : nullptr;
15210b57cec5SDimitry Andric
15220b57cec5SDimitry Andric // Scan the rest of the operands to see if there are any conflicts, if so
15230b57cec5SDimitry Andric // there is no need to recursively scan other phis.
15245f757f3fSDimitry Andric if (NonPhiInVal)
15250b57cec5SDimitry Andric for (++InValNo; InValNo != NumIncomingVals; ++InValNo) {
15260b57cec5SDimitry Andric Value *OpVal = PN.getIncomingValue(InValNo);
15270b57cec5SDimitry Andric if (OpVal != NonPhiInVal && !isa<PHINode>(OpVal))
15280b57cec5SDimitry Andric break;
15290b57cec5SDimitry Andric }
15300b57cec5SDimitry Andric
15310b57cec5SDimitry Andric // If we scanned over all operands, then we have one unique value plus
15320b57cec5SDimitry Andric // phi values. Scan PHI nodes to see if they all merge in each other or
15330b57cec5SDimitry Andric // the value.
15340b57cec5SDimitry Andric if (InValNo == NumIncomingVals) {
15350b57cec5SDimitry Andric SmallPtrSet<PHINode *, 16> ValueEqualPHIs;
15360b57cec5SDimitry Andric if (PHIsEqualValue(&PN, NonPhiInVal, ValueEqualPHIs))
15370b57cec5SDimitry Andric return replaceInstUsesWith(PN, NonPhiInVal);
15380b57cec5SDimitry Andric }
15390b57cec5SDimitry Andric }
15400b57cec5SDimitry Andric
15410b57cec5SDimitry Andric // If there are multiple PHIs, sort their operands so that they all list
15420b57cec5SDimitry Andric // the blocks in the same order. This will help identical PHIs be eliminated
15430b57cec5SDimitry Andric // by other passes. Other passes shouldn't depend on this for correctness
15440b57cec5SDimitry Andric // however.
15455f757f3fSDimitry Andric auto Res = PredOrder.try_emplace(PN.getParent());
15465f757f3fSDimitry Andric if (!Res.second) {
15475f757f3fSDimitry Andric const auto &Preds = Res.first->second;
15485f757f3fSDimitry Andric for (unsigned I = 0, E = PN.getNumIncomingValues(); I != E; ++I) {
15491fd87a68SDimitry Andric BasicBlock *BBA = PN.getIncomingBlock(I);
15505f757f3fSDimitry Andric BasicBlock *BBB = Preds[I];
15510b57cec5SDimitry Andric if (BBA != BBB) {
15521fd87a68SDimitry Andric Value *VA = PN.getIncomingValue(I);
15531fd87a68SDimitry Andric unsigned J = PN.getBasicBlockIndex(BBB);
15541fd87a68SDimitry Andric Value *VB = PN.getIncomingValue(J);
15551fd87a68SDimitry Andric PN.setIncomingBlock(I, BBB);
15561fd87a68SDimitry Andric PN.setIncomingValue(I, VB);
15571fd87a68SDimitry Andric PN.setIncomingBlock(J, BBA);
15581fd87a68SDimitry Andric PN.setIncomingValue(J, VA);
15590b57cec5SDimitry Andric // NOTE: Instcombine normally would want us to "return &PN" if we
15600b57cec5SDimitry Andric // modified any of the operands of an instruction. However, since we
15610b57cec5SDimitry Andric // aren't adding or removing uses (just rearranging them) we don't do
15620b57cec5SDimitry Andric // this in this case.
15630b57cec5SDimitry Andric }
15640b57cec5SDimitry Andric }
15655f757f3fSDimitry Andric } else {
15665f757f3fSDimitry Andric // Remember the block order of the first encountered phi node.
15675f757f3fSDimitry Andric append_range(Res.first->second, PN.blocks());
15685f757f3fSDimitry Andric }
15690b57cec5SDimitry Andric
1570e8d8bef9SDimitry Andric // Is there an identical PHI node in this basic block?
1571e8d8bef9SDimitry Andric for (PHINode &IdenticalPN : PN.getParent()->phis()) {
1572e8d8bef9SDimitry Andric // Ignore the PHI node itself.
1573e8d8bef9SDimitry Andric if (&IdenticalPN == &PN)
1574e8d8bef9SDimitry Andric continue;
1575e8d8bef9SDimitry Andric // Note that even though we've just canonicalized this PHI, due to the
1576e8d8bef9SDimitry Andric // worklist visitation order, there are no guarantess that *every* PHI
1577e8d8bef9SDimitry Andric // has been canonicalized, so we can't just compare operands ranges.
1578e8d8bef9SDimitry Andric if (!PN.isIdenticalToWhenDefined(&IdenticalPN))
1579e8d8bef9SDimitry Andric continue;
1580e8d8bef9SDimitry Andric // Just use that PHI instead then.
1581e8d8bef9SDimitry Andric ++NumPHICSEs;
1582e8d8bef9SDimitry Andric return replaceInstUsesWith(PN, &IdenticalPN);
1583e8d8bef9SDimitry Andric }
1584e8d8bef9SDimitry Andric
15850b57cec5SDimitry Andric // If this is an integer PHI and we know that it has an illegal type, see if
15860b57cec5SDimitry Andric // it is only used by trunc or trunc(lshr) operations. If so, we split the
15870b57cec5SDimitry Andric // PHI into the various pieces being extracted. This sort of thing is
15880b57cec5SDimitry Andric // introduced when SROA promotes an aggregate to a single large integer type.
15890b57cec5SDimitry Andric if (PN.getType()->isIntegerTy() &&
15900b57cec5SDimitry Andric !DL.isLegalInteger(PN.getType()->getPrimitiveSizeInBits()))
15910b57cec5SDimitry Andric if (Instruction *Res = SliceUpIllegalIntegerPHI(PN))
15920b57cec5SDimitry Andric return Res;
15930b57cec5SDimitry Andric
1594e8d8bef9SDimitry Andric // Ultimately, try to replace this Phi with a dominating condition.
15951fd87a68SDimitry Andric if (auto *V = simplifyUsingControlFlow(*this, PN, DT))
1596e8d8bef9SDimitry Andric return replaceInstUsesWith(PN, V);
1597e8d8bef9SDimitry Andric
15980b57cec5SDimitry Andric return nullptr;
15990b57cec5SDimitry Andric }
1600