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