BasicBlockUtils.h revision 276479
1//===-- Transform/Utils/BasicBlockUtils.h - BasicBlock Utils ----*- C++ -*-===//
2//
3//                     The LLVM Compiler Infrastructure
4//
5// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
9//
10// This family of functions perform manipulations on basic blocks, and
11// instructions contained within basic blocks.
12//
13//===----------------------------------------------------------------------===//
14
15#ifndef LLVM_TRANSFORMS_UTILS_BASICBLOCKUTILS_H
16#define LLVM_TRANSFORMS_UTILS_BASICBLOCKUTILS_H
17
18// FIXME: Move to this file: BasicBlock::removePredecessor, BB::splitBasicBlock
19
20#include "llvm/IR/BasicBlock.h"
21#include "llvm/IR/CFG.h"
22
23namespace llvm {
24
25class AliasAnalysis;
26class DominatorTree;
27class Instruction;
28class MDNode;
29class Pass;
30class ReturnInst;
31class TargetLibraryInfo;
32class TerminatorInst;
33
34/// DeleteDeadBlock - Delete the specified block, which must have no
35/// predecessors.
36void DeleteDeadBlock(BasicBlock *BB);
37
38/// FoldSingleEntryPHINodes - We know that BB has one predecessor.  If there are
39/// any single-entry PHI nodes in it, fold them away.  This handles the case
40/// when all entries to the PHI nodes in a block are guaranteed equal, such as
41/// when the block has exactly one predecessor.
42void FoldSingleEntryPHINodes(BasicBlock *BB, Pass *P = nullptr);
43
44/// DeleteDeadPHIs - Examine each PHI in the given block and delete it if it
45/// is dead. Also recursively delete any operands that become dead as
46/// a result. This includes tracing the def-use list from the PHI to see if
47/// it is ultimately unused or if it reaches an unused cycle. Return true
48/// if any PHIs were deleted.
49bool DeleteDeadPHIs(BasicBlock *BB, const TargetLibraryInfo *TLI = nullptr);
50
51/// MergeBlockIntoPredecessor - Attempts to merge a block into its predecessor,
52/// if possible.  The return value indicates success or failure.
53bool MergeBlockIntoPredecessor(BasicBlock *BB, Pass *P = nullptr);
54
55// ReplaceInstWithValue - Replace all uses of an instruction (specified by BI)
56// with a value, then remove and delete the original instruction.
57//
58void ReplaceInstWithValue(BasicBlock::InstListType &BIL,
59                          BasicBlock::iterator &BI, Value *V);
60
61// ReplaceInstWithInst - Replace the instruction specified by BI with the
62// instruction specified by I.  The original instruction is deleted and BI is
63// updated to point to the new instruction.
64//
65void ReplaceInstWithInst(BasicBlock::InstListType &BIL,
66                         BasicBlock::iterator &BI, Instruction *I);
67
68// ReplaceInstWithInst - Replace the instruction specified by From with the
69// instruction specified by To.
70//
71void ReplaceInstWithInst(Instruction *From, Instruction *To);
72
73/// SplitCriticalEdge - If this edge is a critical edge, insert a new node to
74/// split the critical edge.  This will update DominatorTree and
75/// DominatorFrontier information if it is available, thus calling this pass
76/// will not invalidate either of them. This returns the new block if the edge
77/// was split, null otherwise.
78///
79/// If MergeIdenticalEdges is true (not the default), *all* edges from TI to the
80/// specified successor will be merged into the same critical edge block.
81/// This is most commonly interesting with switch instructions, which may
82/// have many edges to any one destination.  This ensures that all edges to that
83/// dest go to one block instead of each going to a different block, but isn't
84/// the standard definition of a "critical edge".
85///
86/// It is invalid to call this function on a critical edge that starts at an
87/// IndirectBrInst.  Splitting these edges will almost always create an invalid
88/// program because the address of the new block won't be the one that is jumped
89/// to.
90///
91BasicBlock *SplitCriticalEdge(TerminatorInst *TI, unsigned SuccNum,
92                              Pass *P = nullptr,
93                              bool MergeIdenticalEdges = false,
94                              bool DontDeleteUselessPHIs = false,
95                              bool SplitLandingPads = false);
96
97inline BasicBlock *SplitCriticalEdge(BasicBlock *BB, succ_iterator SI,
98                                     Pass *P = nullptr) {
99  return SplitCriticalEdge(BB->getTerminator(), SI.getSuccessorIndex(), P);
100}
101
102/// SplitCriticalEdge - If the edge from *PI to BB is not critical, return
103/// false.  Otherwise, split all edges between the two blocks and return true.
104/// This updates all of the same analyses as the other SplitCriticalEdge
105/// function.  If P is specified, it updates the analyses
106/// described above.
107inline bool SplitCriticalEdge(BasicBlock *Succ, pred_iterator PI,
108                              Pass *P = nullptr) {
109  bool MadeChange = false;
110  TerminatorInst *TI = (*PI)->getTerminator();
111  for (unsigned i = 0, e = TI->getNumSuccessors(); i != e; ++i)
112    if (TI->getSuccessor(i) == Succ)
113      MadeChange |= !!SplitCriticalEdge(TI, i, P);
114  return MadeChange;
115}
116
117/// SplitCriticalEdge - If an edge from Src to Dst is critical, split the edge
118/// and return true, otherwise return false.  This method requires that there be
119/// an edge between the two blocks.  If P is specified, it updates the analyses
120/// described above.
121inline BasicBlock *SplitCriticalEdge(BasicBlock *Src, BasicBlock *Dst,
122                                     Pass *P = nullptr,
123                                     bool MergeIdenticalEdges = false,
124                                     bool DontDeleteUselessPHIs = false) {
125  TerminatorInst *TI = Src->getTerminator();
126  unsigned i = 0;
127  while (1) {
128    assert(i != TI->getNumSuccessors() && "Edge doesn't exist!");
129    if (TI->getSuccessor(i) == Dst)
130      return SplitCriticalEdge(TI, i, P, MergeIdenticalEdges,
131                               DontDeleteUselessPHIs);
132    ++i;
133  }
134}
135
136/// SplitEdge -  Split the edge connecting specified block. Pass P must
137/// not be NULL.
138BasicBlock *SplitEdge(BasicBlock *From, BasicBlock *To, Pass *P);
139
140/// SplitBlock - Split the specified block at the specified instruction - every
141/// thing before SplitPt stays in Old and everything starting with SplitPt moves
142/// to a new block.  The two blocks are joined by an unconditional branch and
143/// the loop info is updated.
144///
145BasicBlock *SplitBlock(BasicBlock *Old, Instruction *SplitPt, Pass *P);
146
147/// SplitBlockPredecessors - This method transforms BB by introducing a new
148/// basic block into the function, and moving some of the predecessors of BB to
149/// be predecessors of the new block.  The new predecessors are indicated by the
150/// Preds array, which has NumPreds elements in it.  The new block is given a
151/// suffix of 'Suffix'.  This function returns the new block.
152///
153/// This currently updates the LLVM IR, AliasAnalysis, DominatorTree,
154/// DominanceFrontier, LoopInfo, and LCCSA but no other analyses.
155/// In particular, it does not preserve LoopSimplify (because it's
156/// complicated to handle the case where one of the edges being split
157/// is an exit of a loop with other exits).
158///
159BasicBlock *SplitBlockPredecessors(BasicBlock *BB, ArrayRef<BasicBlock*> Preds,
160                                   const char *Suffix, Pass *P = nullptr);
161
162/// SplitLandingPadPredecessors - This method transforms the landing pad,
163/// OrigBB, by introducing two new basic blocks into the function. One of those
164/// new basic blocks gets the predecessors listed in Preds. The other basic
165/// block gets the remaining predecessors of OrigBB. The landingpad instruction
166/// OrigBB is clone into both of the new basic blocks. The new blocks are given
167/// the suffixes 'Suffix1' and 'Suffix2', and are returned in the NewBBs vector.
168///
169/// This currently updates the LLVM IR, AliasAnalysis, DominatorTree,
170/// DominanceFrontier, LoopInfo, and LCCSA but no other analyses. In particular,
171/// it does not preserve LoopSimplify (because it's complicated to handle the
172/// case where one of the edges being split is an exit of a loop with other
173/// exits).
174///
175void SplitLandingPadPredecessors(BasicBlock *OrigBB,ArrayRef<BasicBlock*> Preds,
176                                 const char *Suffix, const char *Suffix2,
177                                 Pass *P, SmallVectorImpl<BasicBlock*> &NewBBs);
178
179/// FoldReturnIntoUncondBranch - This method duplicates the specified return
180/// instruction into a predecessor which ends in an unconditional branch. If
181/// the return instruction returns a value defined by a PHI, propagate the
182/// right value into the return. It returns the new return instruction in the
183/// predecessor.
184ReturnInst *FoldReturnIntoUncondBranch(ReturnInst *RI, BasicBlock *BB,
185                                       BasicBlock *Pred);
186
187/// SplitBlockAndInsertIfThen - Split the containing block at the
188/// specified instruction - everything before and including SplitBefore stays
189/// in the old basic block, and everything after SplitBefore is moved to a
190/// new block. The two blocks are connected by a conditional branch
191/// (with value of Cmp being the condition).
192/// Before:
193///   Head
194///   SplitBefore
195///   Tail
196/// After:
197///   Head
198///   if (Cond)
199///     ThenBlock
200///   SplitBefore
201///   Tail
202///
203/// If Unreachable is true, then ThenBlock ends with
204/// UnreachableInst, otherwise it branches to Tail.
205/// Returns the NewBasicBlock's terminator.
206///
207/// Updates DT if given.
208TerminatorInst *SplitBlockAndInsertIfThen(Value *Cond, Instruction *SplitBefore,
209                                          bool Unreachable,
210                                          MDNode *BranchWeights = nullptr,
211                                          DominatorTree *DT = nullptr);
212
213/// SplitBlockAndInsertIfThenElse is similar to SplitBlockAndInsertIfThen,
214/// but also creates the ElseBlock.
215/// Before:
216///   Head
217///   SplitBefore
218///   Tail
219/// After:
220///   Head
221///   if (Cond)
222///     ThenBlock
223///   else
224///     ElseBlock
225///   SplitBefore
226///   Tail
227void SplitBlockAndInsertIfThenElse(Value *Cond, Instruction *SplitBefore,
228                                   TerminatorInst **ThenTerm,
229                                   TerminatorInst **ElseTerm,
230                                   MDNode *BranchWeights = nullptr);
231
232///
233/// GetIfCondition - Check whether BB is the merge point of a if-region.
234/// If so, return the boolean condition that determines which entry into
235/// BB will be taken.  Also, return by references the block that will be
236/// entered from if the condition is true, and the block that will be
237/// entered if the condition is false.
238Value *GetIfCondition(BasicBlock *BB, BasicBlock *&IfTrue,
239                      BasicBlock *&IfFalse);
240} // End llvm namespace
241
242#endif
243