46 #define DEBUG_TYPE "simple-loop-unswitch"
50 STATISTIC(NumBranches,
"Number of branches unswitched");
51 STATISTIC(NumSwitches,
"Number of switches unswitched");
52 STATISTIC(NumTrivial,
"Number of unswitches that are trivial");
56 assert(!isa<Constant>(LIC) &&
"Why are we unswitching on a constant?");
76 "Cannot have empty predecessors of the loop exit block if we split "
77 "off a block to unswitch!");
111 if (UnswitchedNode->
getIDom() == OldPHNode)
117 for (
auto *IDom = UnswitchedNode->
getIDom(); IDom != OldPHNode;
146 assert(DomNodes.
empty() &&
"Must start with no dominator nodes.");
147 assert(DomSet.
empty() &&
"Must start with an empty dominator set.");
154 for (
int i = 0; i < (int)DomNodes.
size(); ++i)
163 DomSet.
insert(InnerN->getBlock());
173 if (!DomSet.
count(SuccBB))
181 AppendDomFrontier(UnswitchedNode);
184 for (
int i = 0; i < (int)Worklist.
size(); ++i) {
185 auto *BB = Worklist[i];
189 "Cannot be dominated by a block you can reach!");
200 AppendDomFrontier(Node);
241 for (
auto i : seq<int>(0, PN->getNumOperands())) {
242 assert(PN->getIncomingBlock(i) == &OldExitingBB &&
243 "Found incoming block different from unique predecessor!");
244 PN->setIncomingBlock(i, &OldPH);
260 assert(&ExitBB != &UnswitchedBB &&
261 "Must have different loop exit and unswitched blocks!");
270 PN->getName() +
".split", InsertPt);
281 for (
int i = PN->getNumIncomingValues() - 1; i >= 0; --i) {
282 if (PN->getIncomingBlock(i) != &OldExitingBB)
285 Value *Incoming = PN->removeIncomingValue(i);
286 NewPN->addIncoming(Incoming, &OldPH);
292 NewPN->addIncoming(PN, &ExitBB);
313 DEBUG(
dbgs() <<
" Trying to unswitch branch: " << BI <<
"\n");
333 int LoopExitSuccIdx = 0;
335 if (!ExitBlockSet.count(LoopExitBB)) {
339 if (!ExitBlockSet.count(LoopExitBB))
342 auto *ContinueBB = BI.
getSuccessor(1 - LoopExitSuccIdx);
344 "Cannot have both successors exit and still be in the loop!");
350 DEBUG(
dbgs() <<
" unswitching trivial branch when: " << CondVal
351 <<
" == " << LoopCond <<
"\n");
367 "A branch's parent isn't a predecessor!");
368 UnswitchedBB = LoopExitBB;
370 UnswitchedBB =
SplitBlock(LoopExitBB, &LoopExitBB->front(), &DT, &LI);
386 if (UnswitchedBB == LoopExitBB)
397 if (UnswitchedBB != LoopExitBB)
434 DEBUG(
dbgs() <<
" Trying to unswitch switch: " << SI <<
"\n");
450 for (
auto Case : SI.
cases()) {
451 auto *SuccBB = Case.getCaseSuccessor();
452 if (ExitBlockSet.count(SuccBB) &&
454 ExitCaseIndices.push_back(Case.getCaseIndex());
461 else if (ExitCaseIndices.
empty())
464 DEBUG(
dbgs() <<
" unswitching trivial cases...\n");
470 for (
unsigned Index :
reverse(ExitCaseIndices)) {
473 ExitCases.
push_back({CaseI->getCaseValue(), CaseI->getCaseSuccessor()});
484 return Case.getCaseSuccessor() ==
487 CommonSuccBB = SI.
case_begin()->getCaseSuccessor();
497 ParentBB->getContext(),
498 Twine(ParentBB->getName()) +
".unreachable_default",
499 ParentBB->getParent());
511 CommonSuccBB =
nullptr;
536 UnswitchedExitBBs.
insert(DefaultExitBB);
544 DefaultExitBB = SplitExitBBMap[DefaultExitBB] = SplitBB;
549 for (
auto &CasePair :
reverse(ExitCases)) {
557 if (UnswitchedExitBBs.insert(ExitBB).second)
564 BasicBlock *&SplitExitBB = SplitExitBBMap[ExitBB];
573 CasePair.second = SplitExitBB;
578 for (
auto CasePair :
reverse(ExitCases)) {
582 NewSI->addCase(CaseVal, UnswitchedBB);
589 NewSI->setDefaultDest(DefaultExitBB);
594 for (
auto Case : SI.
cases())
595 NewSI->addCase(Case.getCaseValue(), NewPH);
625 bool Changed =
false;
640 Visited.
insert(CurrentBB);
651 if (
auto *
SI = dyn_cast<SwitchInst>(CurrentTerm)) {
655 if (isa<Constant>(
SI->getCondition()))
670 if (!BI || BI->isConditional())
673 CurrentBB = BI->getSuccessor(0);
685 if (!BI->isConditional() || isa<Constant>(BI->getCondition()))
699 assert(!BI->isConditional() &&
700 "Cannot form a conditional branch by unswitching1");
701 CurrentBB = BI->getSuccessor(0);
706 }
while (L.
contains(CurrentBB) && Visited.
insert(CurrentBB).second);
720 "Loops must be in LCSSA form before unswitching.");
721 bool Changed =
false;
741 DEBUG(
dbgs() <<
"Unswitching loop in " << F.
getName() <<
": " << L <<
"\n");
756 class SimpleLoopUnswitchLegacyPass :
public LoopPass {
760 explicit SimpleLoopUnswitchLegacyPass() :
LoopPass(
ID) {
781 DEBUG(
dbgs() <<
"Unswitching loop in " << F.
getName() <<
": " << *L <<
"\n");
783 auto &DT = getAnalysis<DominatorTreeWrapperPass>().getDomTree();
784 auto &LI = getAnalysis<LoopInfoWrapperPass>().getLoopInfo();
785 auto &AC = getAnalysis<AssumptionCacheTracker>().getAssumptionCache(F);
799 "Simple unswitch loops",
false,
false)
807 return new SimpleLoopUnswitchLegacyPass();
Pass interface - Implemented by all 'passes'.
SymbolTableList< Instruction >::iterator eraseFromParent()
This method unlinks 'this' from the containing basic block and deletes it.
void push_back(const T &Elt)
This routine provides some synthesis utilities to produce sequences of values.
static bool unswitchTrivialBranch(Loop &L, BranchInst &BI, DominatorTree &DT, LoopInfo &LI)
Unswitch a trivial branch if the condition is loop invariant.
static ConstantInt * getFalse(LLVMContext &Context)
CaseIt case_end()
Returns a read/write iterator that points one past the last in the SwitchInst.
static PassRegistry * getPassRegistry()
getPassRegistry - Access the global registry object, which is automatically initialized at applicatio...
iterator_range< CaseIt > cases()
Iteration adapter for range-for loops.
PreservedAnalyses getLoopPassPreservedAnalyses()
Returns the minimum set of Analyses that all loop passes must preserve.
STATISTIC(NumFunctions,"Total number of functions")
BasicBlock * SplitBlock(BasicBlock *Old, Instruction *SplitPt, DominatorTree *DT=nullptr, LoopInfo *LI=nullptr)
Split the specified block at the specified instruction - everything before SplitPt stays in Old and e...
An immutable pass that tracks lazily created AssumptionCache objects.
CaseIt case_begin()
Returns a read/write iterator that points to the first case in the SwitchInst.
bool mayHaveSideEffects() const
Return true if the instruction may have side effects.
A cache of .assume calls within a function.
bool all_of(R &&range, UnaryPredicate P)
Provide wrappers to std::all_of which take ranges instead of having to pass begin/end explicitly...
const Instruction & front() const
The adaptor from a function pass to a loop pass computes these analyses and makes them available to t...
This defines the Use class.
static bool areLoopExitPHIsLoopInvariant(Loop &L, BasicBlock &ExitingBB, BasicBlock &ExitBB)
Check that all the LCSSA PHI nodes in the loop exit block have trivial incoming values along this edg...
void reserve(size_type N)
size_type size() const
Determine the number of elements in the SetVector.
BlockT * getHeader() const
PreservedAnalyses run(Loop &L, LoopAnalysisManager &AM, LoopStandardAnalysisResults &AR, LPMUpdater &U)
StringRef getName() const
Return a constant reference to the value's name.
iterator begin()
Instruction iterator methods.
std::pair< iterator, bool > insert(const std::pair< KeyT, ValueT > &KV)
AnalysisUsage & addRequired()
#define INITIALIZE_PASS_DEPENDENCY(depName)
void initializeSimpleLoopUnswitchLegacyPassPass(PassRegistry &)
simple loop Simple unswitch false
Twine - A lightweight data structure for efficiently representing the concatenation of temporary valu...
A Use represents the edge between a Value definition and its users.
DomTreeNodeBase< NodeT > * addNewBlock(NodeT *BB, NodeT *DomBB)
Add a new node to the dominator tree information.
bool isLoopInvariant(const Value *V) const
Return true if the specified value is loop invariant.
bool isLoopSimplifyForm() const
Return true if the Loop is in the form that the LoopSimplify form transforms loops to...
LLVM_NODISCARD bool empty() const
void getExitBlocks(SmallVectorImpl< BlockT * > &ExitBlocks) const
Return all of the successor blocks of this loop.
static bool unswitchAllTrivialConditions(Loop &L, DominatorTree &DT, LoopInfo &LI)
This routine scans the loop to find a branch or switch which occurs before any side effects occur...
auto reverse(ContainerTy &&C, typename std::enable_if< has_rbegin< ContainerTy >::value >::type *=nullptr) -> decltype(make_range(C.rbegin(), C.rend()))
static void rewritePHINodesForExitAndUnswitchedBlocks(BasicBlock &ExitBB, BasicBlock &UnswitchedBB, BasicBlock &OldExitingBB, BasicBlock &OldPH)
Rewrite the PHI nodes in the loop exit basic block and the split off unswitched block.
bool insert(const value_type &X)
Insert a new element into the SetVector.
DomTreeNodeBase * getIDom() const
BasicBlock * getSuccessor(unsigned i) const
Base class for the actual dominator tree node.
This header provides classes for managing per-loop analyses.
void replaceAllUsesWith(Value *V)
Change all uses of this to point to a new Value.
static void replaceLoopUsesWithConstant(Loop &L, Value &LIC, Constant &Replacement)
Concrete subclass of DominatorTreeBase that is used to compute a normal dominator tree...
Subclasses of this class are all able to terminate a basic block.
A set of analyses that are preserved following a run of a transformation pass.
BlockT * getLoopPreheader() const
If there is a preheader for this loop, return it.
LLVM Basic Block Representation.
Conditional or Unconditional Branch instruction.
static void updateDTAfterUnswitch(BasicBlock *UnswitchedBB, BasicBlock *OldPH, DominatorTree &DT)
Update the dominator tree after unswitching a particular former exit block.
This function has undefined behavior.
This is an important base class in LLVM.
LLVM_ATTRIBUTE_ALWAYS_INLINE iterator begin()
This file contains the declarations for the subclasses of Constant, which represent the different fla...
std::pair< iterator, bool > insert(PtrType Ptr)
Inserts Ptr if and only if there is no element in the container equal to Ptr.
Interval::pred_iterator pred_begin(Interval *I)
pred_begin/pred_end - define methods so that Intervals may be used just like BasicBlocks can with the...
static bool unswitchLoop(Loop &L, DominatorTree &DT, LoopInfo &LI, AssumptionCache &AC)
Unswitch control flow predicated on loop invariant conditions.
Represent the analysis usage information of a pass.
void splice(iterator where, iplist_impl &L2)
bool contains(const LoopT *L) const
Return true if the specified loop is contained within in this loop.
bool any_of(R &&Range, UnaryPredicate P)
Provide wrappers to std::any_of which take ranges instead of having to pass begin/end explicitly...
const InstListType & getInstList() const
Return the underlying instruction list container.
INITIALIZE_PASS_END(RegBankSelect, DEBUG_TYPE,"Assign register bank of generic virtual registers", false, false) RegBankSelect
INITIALIZE_PASS_BEGIN(SimpleLoopUnswitchLegacyPass,"simple-loop-unswitch","Simple unswitch loops", false, false) INITIALIZE_PASS_END(SimpleLoopUnswitchLegacyPass
Interval::pred_iterator pred_end(Interval *I)
static BasicBlock * Create(LLVMContext &Context, const Twine &Name="", Function *Parent=nullptr, BasicBlock *InsertBefore=nullptr)
Creates a new BasicBlock.
bool pred_empty(const BasicBlock *BB)
CaseIt removeCase(CaseIt I)
This method removes the specified case and its successor from the switch instruction.
LLVM_NODISCARD bool empty() const
void verifyDomTree() const
Verify the correctness of the domtree by re-computing it.
static PreservedAnalyses all()
Construct a special preserved set that preserves all passes.
LLVMContext & getContext() const
All values hold a context through their type.
void setSuccessor(unsigned idx, BasicBlock *NewSucc)
bool isConditional() const
This class provides an interface for updating the loop pass manager based on mutations to the loop ne...
A SetVector that performs no allocations if smaller than a certain size.
SmallPtrSet - This class implements a set which is optimized for holding SmallSize or less elements...
This is the shared class of boolean and integer constants.
static SwitchInst * Create(Value *Value, BasicBlock *Default, unsigned NumCases, Instruction *InsertBefore=nullptr)
bool isLCSSAForm(DominatorTree &DT) const
Return true if the Loop is in LCSSA form.
This is a 'vector' (really, a variable-sized array), optimized for the case when the array is small...
static void rewritePHINodesForUnswitchedExitBlock(BasicBlock &UnswitchedBB, BasicBlock &OldExitingBB, BasicBlock &OldPH)
Rewrite the PHI nodes in an unswitched loop exit basic block.
size_type count(ConstPtrType Ptr) const
count - Return 1 if the specified pointer is in the set, 0 otherwise.
simple loop Simple unswitch loops
Pass * createSimpleLoopUnswitchLegacyPass()
Create the legacy pass object for the simple loop unswitcher.
static BranchInst * Create(BasicBlock *IfTrue, Instruction *InsertBefore=nullptr)
static PHINode * Create(Type *Ty, unsigned NumReservedValues, const Twine &NameStr="", Instruction *InsertBefore=nullptr)
Constructors - NumReservedValues is a hint for the number of incoming edges that this phi node will h...
static ConstantInt * getTrue(LLVMContext &Context)
raw_ostream & dbgs()
dbgs() - This returns a reference to a raw_ostream for debugging messages.
void swap(llvm::BitVector &LHS, llvm::BitVector &RHS)
Implement std::swap in terms of BitVector swap.
Value * getCondition() const
iterator insert(iterator I, T &&Elt)
llvm_unreachable("Unknown RegBank!")
LLVM_ATTRIBUTE_ALWAYS_INLINE iterator end()
Value * getCondition() const
BasicBlock * getDefaultDest() const
Represents a single loop in the control flow graph.
LLVM_ATTRIBUTE_ALWAYS_INLINE size_type size() const
void getLoopAnalysisUsage(AnalysisUsage &AU)
Helper to consistently add the set of standard passes to a loop pass's AnalysisUsage.
LLVM_NODISCARD std::enable_if<!is_simple_type< Y >::value, typename cast_retty< X, const Y >::ret_type >::type dyn_cast(const Y &Val)
static bool unswitchTrivialSwitch(Loop &L, SwitchInst &SI, DominatorTree &DT, LoopInfo &LI)
Unswitch a trivial switch if the condition is loop invariant.
unsigned getNumCases() const
Return the number of 'cases' in this switch instruction, excluding the default case.
const BasicBlock * getUniquePredecessor() const
Return the predecessor of this block if it has a unique predecessor block.
assert(ImpDefSCC.getReg()==AMDGPU::SCC &&ImpDefSCC.isDef())
LLVM Value Representation.
succ_range successors(BasicBlock *BB)
void setDefaultDest(BasicBlock *DefaultCase)
BasicBlock * SplitEdge(BasicBlock *From, BasicBlock *To, DominatorTree *DT=nullptr, LoopInfo *LI=nullptr)
Split the edge connecting specified block.
This file defines a set of templates that efficiently compute a dominator tree over a generic graph...
A container for analyses that lazily runs them and caches their results.
const TerminatorInst * getTerminator() const LLVM_READONLY
Returns the terminator instruction if the block is well formed or null if the block is not well forme...
NodeT * findNearestCommonDominator(NodeT *A, NodeT *B) const
findNearestCommonDominator - Find nearest common dominator basic block for basic block A and B...
static void updateLoopExitIDom(BasicBlock *LoopExitBB, Loop &L, DominatorTree &DT)
Update the dominator tree after removing one exiting predecessor of a loop exit block.
void changeImmediateDominator(DomTreeNodeBase< NodeT > *N, DomTreeNodeBase< NodeT > *NewIDom)
changeImmediateDominator - This method is used to update the dominator tree information when a node's...
const BasicBlock * getParent() const