LLVM  mainline
BasicBlockUtils.h
Go to the documentation of this file.
00001 //===-- Transform/Utils/BasicBlockUtils.h - BasicBlock Utils ----*- C++ -*-===//
00002 //
00003 //                     The LLVM Compiler Infrastructure
00004 //
00005 // This file is distributed under the University of Illinois Open Source
00006 // License. See LICENSE.TXT for details.
00007 //
00008 //===----------------------------------------------------------------------===//
00009 //
00010 // This family of functions perform manipulations on basic blocks, and
00011 // instructions contained within basic blocks.
00012 //
00013 //===----------------------------------------------------------------------===//
00014 
00015 #ifndef LLVM_TRANSFORMS_UTILS_BASICBLOCKUTILS_H
00016 #define LLVM_TRANSFORMS_UTILS_BASICBLOCKUTILS_H
00017 
00018 // FIXME: Move to this file: BasicBlock::removePredecessor, BB::splitBasicBlock
00019 
00020 #include "llvm/IR/BasicBlock.h"
00021 #include "llvm/IR/CFG.h"
00022 
00023 namespace llvm {
00024 
00025 class MemoryDependenceAnalysis;
00026 class DominatorTree;
00027 class LoopInfo;
00028 class Instruction;
00029 class MDNode;
00030 class ReturnInst;
00031 class TargetLibraryInfo;
00032 class TerminatorInst;
00033 
00034 /// DeleteDeadBlock - Delete the specified block, which must have no
00035 /// predecessors.
00036 void DeleteDeadBlock(BasicBlock *BB);
00037 
00038 /// FoldSingleEntryPHINodes - We know that BB has one predecessor.  If there are
00039 /// any single-entry PHI nodes in it, fold them away.  This handles the case
00040 /// when all entries to the PHI nodes in a block are guaranteed equal, such as
00041 /// when the block has exactly one predecessor.
00042 void FoldSingleEntryPHINodes(BasicBlock *BB,
00043                              MemoryDependenceAnalysis *MemDep = nullptr);
00044 
00045 /// DeleteDeadPHIs - Examine each PHI in the given block and delete it if it
00046 /// is dead. Also recursively delete any operands that become dead as
00047 /// a result. This includes tracing the def-use list from the PHI to see if
00048 /// it is ultimately unused or if it reaches an unused cycle. Return true
00049 /// if any PHIs were deleted.
00050 bool DeleteDeadPHIs(BasicBlock *BB, const TargetLibraryInfo *TLI = nullptr);
00051 
00052 /// MergeBlockIntoPredecessor - Attempts to merge a block into its predecessor,
00053 /// if possible.  The return value indicates success or failure.
00054 bool MergeBlockIntoPredecessor(BasicBlock *BB, DominatorTree *DT = nullptr,
00055                                LoopInfo *LI = nullptr,
00056                                MemoryDependenceAnalysis *MemDep = nullptr);
00057 
00058 // ReplaceInstWithValue - Replace all uses of an instruction (specified by BI)
00059 // with a value, then remove and delete the original instruction.
00060 //
00061 void ReplaceInstWithValue(BasicBlock::InstListType &BIL,
00062                           BasicBlock::iterator &BI, Value *V);
00063 
00064 // ReplaceInstWithInst - Replace the instruction specified by BI with the
00065 // instruction specified by I. Copies DebugLoc from BI to I, if I doesn't
00066 // already have a DebugLoc. The original instruction is deleted and BI is
00067 // updated to point to the new instruction.
00068 //
00069 void ReplaceInstWithInst(BasicBlock::InstListType &BIL,
00070                          BasicBlock::iterator &BI, Instruction *I);
00071 
00072 // ReplaceInstWithInst - Replace the instruction specified by From with the
00073 // instruction specified by To. Copies DebugLoc from BI to I, if I doesn't
00074 // already have a DebugLoc.
00075 //
00076 void ReplaceInstWithInst(Instruction *From, Instruction *To);
00077 
00078 /// \brief Option class for critical edge splitting.
00079 ///
00080 /// This provides a builder interface for overriding the default options used
00081 /// during critical edge splitting.
00082 struct CriticalEdgeSplittingOptions {
00083   DominatorTree *DT;
00084   LoopInfo *LI;
00085   bool MergeIdenticalEdges;
00086   bool DontDeleteUselessPHIs;
00087   bool PreserveLCSSA;
00088 
00089   CriticalEdgeSplittingOptions(DominatorTree *DT = nullptr,
00090                                LoopInfo *LI = nullptr)
00091       : DT(DT), LI(LI), MergeIdenticalEdges(false),
00092         DontDeleteUselessPHIs(false), PreserveLCSSA(false) {}
00093 
00094   CriticalEdgeSplittingOptions &setMergeIdenticalEdges() {
00095     MergeIdenticalEdges = true;
00096     return *this;
00097   }
00098 
00099   CriticalEdgeSplittingOptions &setDontDeleteUselessPHIs() {
00100     DontDeleteUselessPHIs = true;
00101     return *this;
00102   }
00103 
00104   CriticalEdgeSplittingOptions &setPreserveLCSSA() {
00105     PreserveLCSSA = true;
00106     return *this;
00107   }
00108 };
00109 
00110 /// SplitCriticalEdge - If this edge is a critical edge, insert a new node to
00111 /// split the critical edge.  This will update the analyses passed in through
00112 /// the option struct. This returns the new block if the edge was split, null
00113 /// otherwise.
00114 ///
00115 /// If MergeIdenticalEdges in the options struct is true (not the default),
00116 /// *all* edges from TI to the specified successor will be merged into the same
00117 /// critical edge block. This is most commonly interesting with switch
00118 /// instructions, which may have many edges to any one destination.  This
00119 /// ensures that all edges to that dest go to one block instead of each going
00120 /// to a different block, but isn't the standard definition of a "critical
00121 /// edge".
00122 ///
00123 /// It is invalid to call this function on a critical edge that starts at an
00124 /// IndirectBrInst.  Splitting these edges will almost always create an invalid
00125 /// program because the address of the new block won't be the one that is jumped
00126 /// to.
00127 ///
00128 BasicBlock *SplitCriticalEdge(TerminatorInst *TI, unsigned SuccNum,
00129                               const CriticalEdgeSplittingOptions &Options =
00130                                   CriticalEdgeSplittingOptions());
00131 
00132 inline BasicBlock *
00133 SplitCriticalEdge(BasicBlock *BB, succ_iterator SI,
00134                   const CriticalEdgeSplittingOptions &Options =
00135                       CriticalEdgeSplittingOptions()) {
00136   return SplitCriticalEdge(BB->getTerminator(), SI.getSuccessorIndex(),
00137                            Options);
00138 }
00139 
00140 /// SplitCriticalEdge - If the edge from *PI to BB is not critical, return
00141 /// false.  Otherwise, split all edges between the two blocks and return true.
00142 /// This updates all of the same analyses as the other SplitCriticalEdge
00143 /// function.  If P is specified, it updates the analyses
00144 /// described above.
00145 inline bool SplitCriticalEdge(BasicBlock *Succ, pred_iterator PI,
00146                               const CriticalEdgeSplittingOptions &Options =
00147                                   CriticalEdgeSplittingOptions()) {
00148   bool MadeChange = false;
00149   TerminatorInst *TI = (*PI)->getTerminator();
00150   for (unsigned i = 0, e = TI->getNumSuccessors(); i != e; ++i)
00151     if (TI->getSuccessor(i) == Succ)
00152       MadeChange |= !!SplitCriticalEdge(TI, i, Options);
00153   return MadeChange;
00154 }
00155 
00156 /// SplitCriticalEdge - If an edge from Src to Dst is critical, split the edge
00157 /// and return true, otherwise return false.  This method requires that there be
00158 /// an edge between the two blocks.  It updates the analyses
00159 /// passed in the options struct
00160 inline BasicBlock *
00161 SplitCriticalEdge(BasicBlock *Src, BasicBlock *Dst,
00162                   const CriticalEdgeSplittingOptions &Options =
00163                       CriticalEdgeSplittingOptions()) {
00164   TerminatorInst *TI = Src->getTerminator();
00165   unsigned i = 0;
00166   while (1) {
00167     assert(i != TI->getNumSuccessors() && "Edge doesn't exist!");
00168     if (TI->getSuccessor(i) == Dst)
00169       return SplitCriticalEdge(TI, i, Options);
00170     ++i;
00171   }
00172 }
00173 
00174 // SplitAllCriticalEdges - Loop over all of the edges in the CFG,
00175 // breaking critical edges as they are found.
00176 // Returns the number of broken edges.
00177 unsigned SplitAllCriticalEdges(Function &F,
00178                                const CriticalEdgeSplittingOptions &Options =
00179                                    CriticalEdgeSplittingOptions());
00180 
00181 /// SplitEdge -  Split the edge connecting specified block.
00182 BasicBlock *SplitEdge(BasicBlock *From, BasicBlock *To,
00183                       DominatorTree *DT = nullptr, LoopInfo *LI = nullptr);
00184 
00185 /// SplitBlock - Split the specified block at the specified instruction - every
00186 /// thing before SplitPt stays in Old and everything starting with SplitPt moves
00187 /// to a new block.  The two blocks are joined by an unconditional branch and
00188 /// the loop info is updated.
00189 ///
00190 BasicBlock *SplitBlock(BasicBlock *Old, Instruction *SplitPt,
00191                        DominatorTree *DT = nullptr, LoopInfo *LI = nullptr);
00192 
00193 /// SplitBlockPredecessors - This method introduces at least one new basic block
00194 /// into the function and moves some of the predecessors of BB to be
00195 /// predecessors of the new block. The new predecessors are indicated by the
00196 /// Preds array. The new block is given a suffix of 'Suffix'. Returns new basic
00197 /// block to which predecessors from Preds are now pointing.
00198 ///
00199 /// If BB is a landingpad block then additional basicblock might be introduced.
00200 /// It will have Suffix+".split_lp". See SplitLandingPadPredecessors for more
00201 /// details on this case.
00202 ///
00203 /// This currently updates the LLVM IR, DominatorTree, LoopInfo, and LCCSA but
00204 /// no other analyses. In particular, it does not preserve LoopSimplify
00205 /// (because it's complicated to handle the case where one of the edges being
00206 /// split is an exit of a loop with other exits).
00207 ///
00208 BasicBlock *SplitBlockPredecessors(BasicBlock *BB, ArrayRef<BasicBlock *> Preds,
00209                                    const char *Suffix,
00210                                    DominatorTree *DT = nullptr,
00211                                    LoopInfo *LI = nullptr,
00212                                    bool PreserveLCSSA = false);
00213 
00214 /// SplitLandingPadPredecessors - This method transforms the landing pad,
00215 /// OrigBB, by introducing two new basic blocks into the function. One of those
00216 /// new basic blocks gets the predecessors listed in Preds. The other basic
00217 /// block gets the remaining predecessors of OrigBB. The landingpad instruction
00218 /// OrigBB is clone into both of the new basic blocks. The new blocks are given
00219 /// the suffixes 'Suffix1' and 'Suffix2', and are returned in the NewBBs vector.
00220 ///
00221 /// This currently updates the LLVM IR, DominatorTree, LoopInfo, and LCCSA but
00222 /// no other analyses. In particular, it does not preserve LoopSimplify
00223 /// (because it's complicated to handle the case where one of the edges being
00224 /// split is an exit of a loop with other exits).
00225 ///
00226 void SplitLandingPadPredecessors(BasicBlock *OrigBB,
00227                                  ArrayRef<BasicBlock *> Preds,
00228                                  const char *Suffix, const char *Suffix2,
00229                                  SmallVectorImpl<BasicBlock *> &NewBBs,
00230                                  DominatorTree *DT = nullptr,
00231                                  LoopInfo *LI = nullptr,
00232                                  bool PreserveLCSSA = false);
00233 
00234 /// FoldReturnIntoUncondBranch - This method duplicates the specified return
00235 /// instruction into a predecessor which ends in an unconditional branch. If
00236 /// the return instruction returns a value defined by a PHI, propagate the
00237 /// right value into the return. It returns the new return instruction in the
00238 /// predecessor.
00239 ReturnInst *FoldReturnIntoUncondBranch(ReturnInst *RI, BasicBlock *BB,
00240                                        BasicBlock *Pred);
00241 
00242 /// SplitBlockAndInsertIfThen - Split the containing block at the
00243 /// specified instruction - everything before and including SplitBefore stays
00244 /// in the old basic block, and everything after SplitBefore is moved to a
00245 /// new block. The two blocks are connected by a conditional branch
00246 /// (with value of Cmp being the condition).
00247 /// Before:
00248 ///   Head
00249 ///   SplitBefore
00250 ///   Tail
00251 /// After:
00252 ///   Head
00253 ///   if (Cond)
00254 ///     ThenBlock
00255 ///   SplitBefore
00256 ///   Tail
00257 ///
00258 /// If Unreachable is true, then ThenBlock ends with
00259 /// UnreachableInst, otherwise it branches to Tail.
00260 /// Returns the NewBasicBlock's terminator.
00261 ///
00262 /// Updates DT if given.
00263 TerminatorInst *SplitBlockAndInsertIfThen(Value *Cond, Instruction *SplitBefore,
00264                                           bool Unreachable,
00265                                           MDNode *BranchWeights = nullptr,
00266                                           DominatorTree *DT = nullptr);
00267 
00268 /// SplitBlockAndInsertIfThenElse is similar to SplitBlockAndInsertIfThen,
00269 /// but also creates the ElseBlock.
00270 /// Before:
00271 ///   Head
00272 ///   SplitBefore
00273 ///   Tail
00274 /// After:
00275 ///   Head
00276 ///   if (Cond)
00277 ///     ThenBlock
00278 ///   else
00279 ///     ElseBlock
00280 ///   SplitBefore
00281 ///   Tail
00282 void SplitBlockAndInsertIfThenElse(Value *Cond, Instruction *SplitBefore,
00283                                    TerminatorInst **ThenTerm,
00284                                    TerminatorInst **ElseTerm,
00285                                    MDNode *BranchWeights = nullptr);
00286 
00287 ///
00288 /// GetIfCondition - Check whether BB is the merge point of a if-region.
00289 /// If so, return the boolean condition that determines which entry into
00290 /// BB will be taken.  Also, return by references the block that will be
00291 /// entered from if the condition is true, and the block that will be
00292 /// entered if the condition is false.
00293 Value *GetIfCondition(BasicBlock *BB, BasicBlock *&IfTrue,
00294                       BasicBlock *&IfFalse);
00295 } // End llvm namespace
00296 
00297 #endif