blob: 1bf92e35abcbdbdcb19bc97fee331bf68bd82212 [file] [log] [blame]
Chris Lattner28537df2002-05-07 18:07:59 +00001//===-- BasicBlockUtils.cpp - BasicBlock Utilities -------------------------==//
Misha Brukmanb1c93172005-04-21 23:48:37 +00002//
John Criswell482202a2003-10-20 19:43:21 +00003// The LLVM Compiler Infrastructure
4//
Chris Lattnerf3ebc3f2007-12-29 20:36:04 +00005// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
Misha Brukmanb1c93172005-04-21 23:48:37 +00007//
John Criswell482202a2003-10-20 19:43:21 +00008//===----------------------------------------------------------------------===//
Chris Lattner28537df2002-05-07 18:07:59 +00009//
10// This family of functions perform manipulations on basic blocks, and
11// instructions contained within basic blocks.
12//
13//===----------------------------------------------------------------------===//
14
15#include "llvm/Transforms/Utils/BasicBlockUtils.h"
Chris Lattnera5b11702008-04-21 01:28:02 +000016#include "llvm/Analysis/AliasAnalysis.h"
Nick Lewycky0b682452013-07-27 01:24:00 +000017#include "llvm/Analysis/CFG.h"
Chris Lattnerf6ae9042011-01-11 08:13:40 +000018#include "llvm/Analysis/LoopInfo.h"
19#include "llvm/Analysis/MemoryDependenceAnalysis.h"
Chandler Carruth9fb823b2013-01-02 11:36:10 +000020#include "llvm/IR/Constant.h"
21#include "llvm/IR/DataLayout.h"
Chandler Carruth5ad5f152014-01-13 09:26:24 +000022#include "llvm/IR/Dominators.h"
Chandler Carruth9fb823b2013-01-02 11:36:10 +000023#include "llvm/IR/Function.h"
24#include "llvm/IR/Instructions.h"
25#include "llvm/IR/IntrinsicInst.h"
26#include "llvm/IR/Type.h"
Chandler Carruth4220e9c2014-03-04 11:17:44 +000027#include "llvm/IR/ValueHandle.h"
Torok Edwinccb29cd2009-07-11 13:10:19 +000028#include "llvm/Support/ErrorHandling.h"
Chandler Carruthed0881b2012-12-03 16:50:05 +000029#include "llvm/Transforms/Scalar.h"
30#include "llvm/Transforms/Utils/Local.h"
Chris Lattner28537df2002-05-07 18:07:59 +000031#include <algorithm>
Chris Lattnerdf3c3422004-01-09 06:12:26 +000032using namespace llvm;
Brian Gaeke960707c2003-11-11 22:41:34 +000033
Chris Lattner7eb270e2008-12-03 06:40:52 +000034/// DeleteDeadBlock - Delete the specified block, which must have no
35/// predecessors.
36void llvm::DeleteDeadBlock(BasicBlock *BB) {
Chris Lattner37e01362008-12-03 07:45:15 +000037 assert((pred_begin(BB) == pred_end(BB) ||
38 // Can delete self loop.
39 BB->getSinglePredecessor() == BB) && "Block is not dead!");
Chris Lattnerbcc904a2008-12-03 06:37:44 +000040 TerminatorInst *BBTerm = BB->getTerminator();
Jakub Staszak190db2f2013-01-14 23:16:36 +000041
Chris Lattnerbcc904a2008-12-03 06:37:44 +000042 // Loop through all of our successors and make sure they know that one
43 // of their predecessors is going away.
44 for (unsigned i = 0, e = BBTerm->getNumSuccessors(); i != e; ++i)
45 BBTerm->getSuccessor(i)->removePredecessor(BB);
Jakub Staszak190db2f2013-01-14 23:16:36 +000046
Chris Lattnerbcc904a2008-12-03 06:37:44 +000047 // Zap all the instructions in the block.
48 while (!BB->empty()) {
49 Instruction &I = BB->back();
50 // If this instruction is used, replace uses with an arbitrary value.
51 // Because control flow can't get here, we don't care what we replace the
52 // value with. Note that since this block is unreachable, and all values
53 // contained within it must dominate their uses, that all uses will
54 // eventually be removed (they are themselves dead).
55 if (!I.use_empty())
Owen Andersonb292b8c2009-07-30 23:03:37 +000056 I.replaceAllUsesWith(UndefValue::get(I.getType()));
Chris Lattnerbcc904a2008-12-03 06:37:44 +000057 BB->getInstList().pop_back();
58 }
Jakub Staszak190db2f2013-01-14 23:16:36 +000059
Chris Lattnerbcc904a2008-12-03 06:37:44 +000060 // Zap the block!
61 BB->eraseFromParent();
Chris Lattnerbcc904a2008-12-03 06:37:44 +000062}
63
Chris Lattnerdc3f6f22008-12-03 19:44:02 +000064/// FoldSingleEntryPHINodes - We know that BB has one predecessor. If there are
65/// any single-entry PHI nodes in it, fold them away. This handles the case
66/// when all entries to the PHI nodes in a block are guaranteed equal, such as
67/// when the block has exactly one predecessor.
Chandler Carruth96ada252015-07-22 09:52:54 +000068void llvm::FoldSingleEntryPHINodes(BasicBlock *BB,
Chandler Carruth5eee8952015-01-18 01:45:07 +000069 MemoryDependenceAnalysis *MemDep) {
Chris Lattnerf6ae9042011-01-11 08:13:40 +000070 if (!isa<PHINode>(BB->begin())) return;
Jakub Staszak190db2f2013-01-14 23:16:36 +000071
Chris Lattnerdc3f6f22008-12-03 19:44:02 +000072 while (PHINode *PN = dyn_cast<PHINode>(BB->begin())) {
73 if (PN->getIncomingValue(0) != PN)
74 PN->replaceAllUsesWith(PN->getIncomingValue(0));
75 else
Owen Andersonb292b8c2009-07-30 23:03:37 +000076 PN->replaceAllUsesWith(UndefValue::get(PN->getType()));
Jakub Staszak190db2f2013-01-14 23:16:36 +000077
Chris Lattnerf6ae9042011-01-11 08:13:40 +000078 if (MemDep)
79 MemDep->removeInstruction(PN); // Memdep updates AA itself.
Jakub Staszak190db2f2013-01-14 23:16:36 +000080
Chris Lattnerdc3f6f22008-12-03 19:44:02 +000081 PN->eraseFromParent();
82 }
83}
84
85
Dan Gohmanff089952009-05-02 18:29:22 +000086/// DeleteDeadPHIs - Examine each PHI in the given block and delete it if it
87/// is dead. Also recursively delete any operands that become dead as
88/// a result. This includes tracing the def-use list from the PHI to see if
Dan Gohman48f82222009-05-04 22:30:44 +000089/// it is ultimately unused or if it reaches an unused cycle.
Benjamin Kramer8bcc9712012-08-29 15:32:21 +000090bool llvm::DeleteDeadPHIs(BasicBlock *BB, const TargetLibraryInfo *TLI) {
Dan Gohmanff089952009-05-02 18:29:22 +000091 // Recursively deleting a PHI may cause multiple PHIs to be deleted
92 // or RAUW'd undef, so use an array of WeakVH for the PHIs to delete.
93 SmallVector<WeakVH, 8> PHIs;
94 for (BasicBlock::iterator I = BB->begin();
95 PHINode *PN = dyn_cast<PHINode>(I); ++I)
96 PHIs.push_back(PN);
97
Dan Gohmancb99fe92010-01-05 15:45:31 +000098 bool Changed = false;
Dan Gohmanff089952009-05-02 18:29:22 +000099 for (unsigned i = 0, e = PHIs.size(); i != e; ++i)
100 if (PHINode *PN = dyn_cast_or_null<PHINode>(PHIs[i].operator Value*()))
Benjamin Kramer8bcc9712012-08-29 15:32:21 +0000101 Changed |= RecursivelyDeleteDeadPHINode(PN, TLI);
Dan Gohmancb99fe92010-01-05 15:45:31 +0000102
103 return Changed;
Dan Gohmanff089952009-05-02 18:29:22 +0000104}
105
Dan Gohman2d02ff82009-10-31 17:33:01 +0000106/// MergeBlockIntoPredecessor - Attempts to merge a block into its predecessor,
107/// if possible. The return value indicates success or failure.
Chandler Carruthb5c11532015-01-18 02:11:23 +0000108bool llvm::MergeBlockIntoPredecessor(BasicBlock *BB, DominatorTree *DT,
Chandler Carruth96ada252015-07-22 09:52:54 +0000109 LoopInfo *LI,
Chandler Carruthb5c11532015-01-18 02:11:23 +0000110 MemoryDependenceAnalysis *MemDep) {
Dan Gohman941020e2010-08-17 17:07:02 +0000111 // Don't merge away blocks who have their address taken.
112 if (BB->hasAddressTaken()) return false;
Jakub Staszak190db2f2013-01-14 23:16:36 +0000113
Dan Gohman941020e2010-08-17 17:07:02 +0000114 // Can't merge if there are multiple predecessors, or no predecessors.
115 BasicBlock *PredBB = BB->getUniquePredecessor();
Dan Gohman2d02ff82009-10-31 17:33:01 +0000116 if (!PredBB) return false;
Dan Gohman941020e2010-08-17 17:07:02 +0000117
Dan Gohman2d02ff82009-10-31 17:33:01 +0000118 // Don't break self-loops.
119 if (PredBB == BB) return false;
David Majnemer654e1302015-07-31 17:58:14 +0000120 // Don't break unwinding instructions.
121 if (PredBB->getTerminator()->isExceptional())
122 return false;
Jakub Staszak190db2f2013-01-14 23:16:36 +0000123
Dan Gohman2d02ff82009-10-31 17:33:01 +0000124 succ_iterator SI(succ_begin(PredBB)), SE(succ_end(PredBB));
Chris Lattner930b7162011-01-08 19:08:40 +0000125 BasicBlock *OnlySucc = BB;
Dan Gohman2d02ff82009-10-31 17:33:01 +0000126 for (; SI != SE; ++SI)
127 if (*SI != OnlySucc) {
Craig Topperf40110f2014-04-25 05:29:35 +0000128 OnlySucc = nullptr; // There are multiple distinct successors!
Dan Gohman2d02ff82009-10-31 17:33:01 +0000129 break;
130 }
Jakub Staszak190db2f2013-01-14 23:16:36 +0000131
Dan Gohman2d02ff82009-10-31 17:33:01 +0000132 // Can't merge if there are multiple successors.
133 if (!OnlySucc) return false;
Devang Patel0f7a3502008-09-09 01:06:56 +0000134
Dan Gohman2d02ff82009-10-31 17:33:01 +0000135 // Can't merge if there is PHI loop.
136 for (BasicBlock::iterator BI = BB->begin(), BE = BB->end(); BI != BE; ++BI) {
137 if (PHINode *PN = dyn_cast<PHINode>(BI)) {
Pete Cooper833f34d2015-05-12 20:05:31 +0000138 for (Value *IncValue : PN->incoming_values())
139 if (IncValue == PN)
Dan Gohman2d02ff82009-10-31 17:33:01 +0000140 return false;
141 } else
142 break;
143 }
144
145 // Begin by getting rid of unneeded PHIs.
Chandler Carruthb5c11532015-01-18 02:11:23 +0000146 if (isa<PHINode>(BB->front()))
Chandler Carruth96ada252015-07-22 09:52:54 +0000147 FoldSingleEntryPHINodes(BB, MemDep);
Jakub Staszak190db2f2013-01-14 23:16:36 +0000148
Owen Andersonc0623812008-07-17 00:01:40 +0000149 // Delete the unconditional branch from the predecessor...
150 PredBB->getInstList().pop_back();
Jakub Staszak190db2f2013-01-14 23:16:36 +0000151
Owen Andersonc0623812008-07-17 00:01:40 +0000152 // Make all PHI nodes that referred to BB now refer to Pred as their
153 // source...
154 BB->replaceAllUsesWith(PredBB);
Jakub Staszak190db2f2013-01-14 23:16:36 +0000155
Jay Foad61ea0e42011-06-23 09:09:15 +0000156 // Move all definitions in the successor to the predecessor...
157 PredBB->getInstList().splice(PredBB->end(), BB->getInstList());
Jakub Staszak190db2f2013-01-14 23:16:36 +0000158
Dan Gohman2d02ff82009-10-31 17:33:01 +0000159 // Inherit predecessors name if it exists.
Owen Anderson27405ef2008-07-17 19:42:29 +0000160 if (!PredBB->hasName())
161 PredBB->takeName(BB);
Jakub Staszak190db2f2013-01-14 23:16:36 +0000162
Owen Andersonc0623812008-07-17 00:01:40 +0000163 // Finally, erase the old block and update dominator info.
Chandler Carruthb5c11532015-01-18 02:11:23 +0000164 if (DT)
165 if (DomTreeNode *DTN = DT->getNode(BB)) {
166 DomTreeNode *PredDTN = DT->getNode(PredBB);
167 SmallVector<DomTreeNode *, 8> Children(DTN->begin(), DTN->end());
168 for (SmallVectorImpl<DomTreeNode *>::iterator DI = Children.begin(),
169 DE = Children.end();
170 DI != DE; ++DI)
171 DT->changeImmediateDominator(*DI, PredDTN);
Owen Andersonc0623812008-07-17 00:01:40 +0000172
Chandler Carruthb5c11532015-01-18 02:11:23 +0000173 DT->eraseNode(BB);
Owen Andersonc0623812008-07-17 00:01:40 +0000174 }
Chandler Carruthb5c11532015-01-18 02:11:23 +0000175
176 if (LI)
177 LI->removeBlock(BB);
178
179 if (MemDep)
180 MemDep->invalidateCachedPredecessors();
Jakub Staszak190db2f2013-01-14 23:16:36 +0000181
Owen Andersonc0623812008-07-17 00:01:40 +0000182 BB->eraseFromParent();
Dan Gohman2d02ff82009-10-31 17:33:01 +0000183 return true;
Owen Andersonc0623812008-07-17 00:01:40 +0000184}
185
Chris Lattner7ceb0812005-04-21 16:04:49 +0000186/// ReplaceInstWithValue - Replace all uses of an instruction (specified by BI)
187/// with a value, then remove and delete the original instruction.
188///
Chris Lattnerdf3c3422004-01-09 06:12:26 +0000189void llvm::ReplaceInstWithValue(BasicBlock::InstListType &BIL,
190 BasicBlock::iterator &BI, Value *V) {
Chris Lattnerfda72b12002-06-25 16:12:52 +0000191 Instruction &I = *BI;
Chris Lattner28537df2002-05-07 18:07:59 +0000192 // Replaces all of the uses of the instruction with uses of the value
Chris Lattnerfda72b12002-06-25 16:12:52 +0000193 I.replaceAllUsesWith(V);
Chris Lattner28537df2002-05-07 18:07:59 +0000194
Chris Lattner8dd4cae2007-02-11 01:37:51 +0000195 // Make sure to propagate a name if there is one already.
196 if (I.hasName() && !V->hasName())
197 V->takeName(&I);
Misha Brukmanb1c93172005-04-21 23:48:37 +0000198
Misha Brukman7eb05a12003-08-18 14:43:39 +0000199 // Delete the unnecessary instruction now...
Chris Lattnerfda72b12002-06-25 16:12:52 +0000200 BI = BIL.erase(BI);
Chris Lattner28537df2002-05-07 18:07:59 +0000201}
202
203
Chris Lattner7ceb0812005-04-21 16:04:49 +0000204/// ReplaceInstWithInst - Replace the instruction specified by BI with the
205/// instruction specified by I. The original instruction is deleted and BI is
206/// updated to point to the new instruction.
207///
Chris Lattnerdf3c3422004-01-09 06:12:26 +0000208void llvm::ReplaceInstWithInst(BasicBlock::InstListType &BIL,
209 BasicBlock::iterator &BI, Instruction *I) {
Craig Toppere73658d2014-04-28 04:05:08 +0000210 assert(I->getParent() == nullptr &&
Chris Lattner28537df2002-05-07 18:07:59 +0000211 "ReplaceInstWithInst: Instruction already inserted into basic block!");
212
Alexey Samsonov19ffcb92015-06-23 21:00:08 +0000213 // Copy debug location to newly added instruction, if it wasn't already set
214 // by the caller.
215 if (!I->getDebugLoc())
216 I->setDebugLoc(BI->getDebugLoc());
217
Chris Lattner28537df2002-05-07 18:07:59 +0000218 // Insert the new instruction into the basic block...
Chris Lattnerfda72b12002-06-25 16:12:52 +0000219 BasicBlock::iterator New = BIL.insert(BI, I);
Chris Lattner28537df2002-05-07 18:07:59 +0000220
221 // Replace all uses of the old instruction, and delete it.
222 ReplaceInstWithValue(BIL, BI, I);
223
224 // Move BI back to point to the newly inserted instruction
Chris Lattnerfda72b12002-06-25 16:12:52 +0000225 BI = New;
Chris Lattner28537df2002-05-07 18:07:59 +0000226}
227
Chris Lattner7ceb0812005-04-21 16:04:49 +0000228/// ReplaceInstWithInst - Replace the instruction specified by From with the
229/// instruction specified by To.
230///
Chris Lattnerdf3c3422004-01-09 06:12:26 +0000231void llvm::ReplaceInstWithInst(Instruction *From, Instruction *To) {
Chris Lattnerfda72b12002-06-25 16:12:52 +0000232 BasicBlock::iterator BI(From);
233 ReplaceInstWithInst(From->getParent()->getInstList(), BI, To);
Chris Lattner28537df2002-05-07 18:07:59 +0000234}
Chris Lattnerb17274e2002-07-29 22:32:08 +0000235
Jakub Staszak190db2f2013-01-14 23:16:36 +0000236/// SplitEdge - Split the edge connecting specified block. Pass P must
237/// not be NULL.
Chandler Carruthd4500562015-01-19 12:36:53 +0000238BasicBlock *llvm::SplitEdge(BasicBlock *BB, BasicBlock *Succ, DominatorTree *DT,
239 LoopInfo *LI) {
Bob Wilsonaff96b22010-02-16 21:06:42 +0000240 unsigned SuccNum = GetSuccessorNumber(BB, Succ);
Jakub Staszak190db2f2013-01-14 23:16:36 +0000241
Chandler Carruth37df2cf2015-01-19 12:09:11 +0000242 // If this is a critical edge, let SplitCriticalEdge do it.
243 TerminatorInst *LatchTerm = BB->getTerminator();
Chandler Carruthd4500562015-01-19 12:36:53 +0000244 if (SplitCriticalEdge(LatchTerm, SuccNum, CriticalEdgeSplittingOptions(DT, LI)
245 .setPreserveLCSSA()))
Chandler Carruth37df2cf2015-01-19 12:09:11 +0000246 return LatchTerm->getSuccessor(SuccNum);
Chandler Carruth32c52c72015-01-18 02:39:37 +0000247
Devang Pateld7767cc2007-07-06 21:39:20 +0000248 // If the edge isn't critical, then BB has a single successor or Succ has a
249 // single pred. Split the block.
Devang Pateld7767cc2007-07-06 21:39:20 +0000250 if (BasicBlock *SP = Succ->getSinglePredecessor()) {
251 // If the successor only has a single pred, split the top of the successor
252 // block.
253 assert(SP == BB && "CFG broken");
Craig Topperf40110f2014-04-25 05:29:35 +0000254 SP = nullptr;
Chandler Carruth32c52c72015-01-18 02:39:37 +0000255 return SplitBlock(Succ, Succ->begin(), DT, LI);
Devang Pateld7767cc2007-07-06 21:39:20 +0000256 }
Jakub Staszak190db2f2013-01-14 23:16:36 +0000257
Chris Lattner30d95f92011-01-08 18:47:43 +0000258 // Otherwise, if BB has a single successor, split it at the bottom of the
259 // block.
260 assert(BB->getTerminator()->getNumSuccessors() == 1 &&
Jakub Staszak190db2f2013-01-14 23:16:36 +0000261 "Should have a single succ!");
Chandler Carruth32c52c72015-01-18 02:39:37 +0000262 return SplitBlock(BB, BB->getTerminator(), DT, LI);
Devang Pateld7767cc2007-07-06 21:39:20 +0000263}
264
Chandler Carruth37df2cf2015-01-19 12:09:11 +0000265unsigned
266llvm::SplitAllCriticalEdges(Function &F,
267 const CriticalEdgeSplittingOptions &Options) {
Kostya Serebryanye5ea4242014-11-19 00:17:31 +0000268 unsigned NumBroken = 0;
269 for (Function::iterator I = F.begin(), E = F.end(); I != E; ++I) {
270 TerminatorInst *TI = I->getTerminator();
271 if (TI->getNumSuccessors() > 1 && !isa<IndirectBrInst>(TI))
272 for (unsigned i = 0, e = TI->getNumSuccessors(); i != e; ++i)
Chandler Carruth37df2cf2015-01-19 12:09:11 +0000273 if (SplitCriticalEdge(TI, i, Options))
Kostya Serebryanye5ea4242014-11-19 00:17:31 +0000274 ++NumBroken;
275 }
276 return NumBroken;
277}
278
Devang Pateld7767cc2007-07-06 21:39:20 +0000279/// SplitBlock - Split the specified block at the specified instruction - every
280/// thing before SplitPt stays in Old and everything starting with SplitPt moves
281/// to a new block. The two blocks are joined by an unconditional branch and
282/// the loop info is updated.
283///
Chandler Carruth32c52c72015-01-18 02:39:37 +0000284BasicBlock *llvm::SplitBlock(BasicBlock *Old, Instruction *SplitPt,
285 DominatorTree *DT, LoopInfo *LI) {
Devang Pateld7767cc2007-07-06 21:39:20 +0000286 BasicBlock::iterator SplitIt = SplitPt;
David Majnemer654e1302015-07-31 17:58:14 +0000287 while (isa<PHINode>(SplitIt) || SplitIt->isEHPad())
Devang Pateld7767cc2007-07-06 21:39:20 +0000288 ++SplitIt;
289 BasicBlock *New = Old->splitBasicBlock(SplitIt, Old->getName()+".split");
290
Dan Gohman3ddbc242009-09-08 15:45:00 +0000291 // The new block lives in whichever loop the old one did. This preserves
292 // LCSSA as well, because we force the split point to be after any PHI nodes.
Chandler Carruth32c52c72015-01-18 02:39:37 +0000293 if (LI)
294 if (Loop *L = LI->getLoopFor(Old))
295 L->addBasicBlockToLoop(New, *LI);
Devang Pateld7767cc2007-07-06 21:39:20 +0000296
Chandler Carruth32c52c72015-01-18 02:39:37 +0000297 if (DT)
Gabor Greif2f5f6962010-09-10 22:25:58 +0000298 // Old dominates New. New node dominates all other nodes dominated by Old.
Chandler Carruth32c52c72015-01-18 02:39:37 +0000299 if (DomTreeNode *OldNode = DT->getNode(Old)) {
Rafael Espindolad3e65e72011-08-24 18:07:01 +0000300 std::vector<DomTreeNode *> Children;
301 for (DomTreeNode::iterator I = OldNode->begin(), E = OldNode->end();
Jakub Staszak190db2f2013-01-14 23:16:36 +0000302 I != E; ++I)
Rafael Espindolad3e65e72011-08-24 18:07:01 +0000303 Children.push_back(*I);
Devang Patel186e0d82007-07-19 02:29:24 +0000304
Chandler Carruth32c52c72015-01-18 02:39:37 +0000305 DomTreeNode *NewNode = DT->addNewBlock(New, Old);
Devang Patel186e0d82007-07-19 02:29:24 +0000306 for (std::vector<DomTreeNode *>::iterator I = Children.begin(),
Jakub Staszak190db2f2013-01-14 23:16:36 +0000307 E = Children.end(); I != E; ++I)
Chandler Carruth32c52c72015-01-18 02:39:37 +0000308 DT->changeImmediateDominator(*I, NewNode);
Rafael Espindolad3e65e72011-08-24 18:07:01 +0000309 }
Devang Pateld7767cc2007-07-06 21:39:20 +0000310
Devang Pateld7767cc2007-07-06 21:39:20 +0000311 return New;
312}
Chris Lattnera5b11702008-04-21 01:28:02 +0000313
Bill Wendling0a693f42011-08-18 05:25:23 +0000314/// UpdateAnalysisInformation - Update DominatorTree, LoopInfo, and LCCSA
315/// analysis information.
Bill Wendling60291352011-08-18 17:57:57 +0000316static void UpdateAnalysisInformation(BasicBlock *OldBB, BasicBlock *NewBB,
Bill Wendlingec3823d2011-08-18 20:39:32 +0000317 ArrayRef<BasicBlock *> Preds,
Chandler Carruthb5797b62015-01-18 09:21:15 +0000318 DominatorTree *DT, LoopInfo *LI,
319 bool PreserveLCSSA, bool &HasLoopExit) {
320 // Update dominator tree if available.
321 if (DT)
322 DT->splitBlock(NewBB);
Bill Wendling0a693f42011-08-18 05:25:23 +0000323
Chandler Carruthb5797b62015-01-18 09:21:15 +0000324 // The rest of the logic is only relevant for updating the loop structures.
325 if (!LI)
326 return;
327
328 Loop *L = LI->getLoopFor(OldBB);
Bill Wendling0a693f42011-08-18 05:25:23 +0000329
330 // If we need to preserve loop analyses, collect some information about how
331 // this split will affect loops.
332 bool IsLoopEntry = !!L;
333 bool SplitMakesNewLoopHeader = false;
Chandler Carruthb5797b62015-01-18 09:21:15 +0000334 for (ArrayRef<BasicBlock *>::iterator i = Preds.begin(), e = Preds.end();
335 i != e; ++i) {
336 BasicBlock *Pred = *i;
Bill Wendlingca7d3092011-08-19 00:05:40 +0000337
Chandler Carruthb5797b62015-01-18 09:21:15 +0000338 // If we need to preserve LCSSA, determine if any of the preds is a loop
339 // exit.
340 if (PreserveLCSSA)
341 if (Loop *PL = LI->getLoopFor(Pred))
342 if (!PL->contains(OldBB))
343 HasLoopExit = true;
Bill Wendling0a693f42011-08-18 05:25:23 +0000344
Chandler Carruthb5797b62015-01-18 09:21:15 +0000345 // If we need to preserve LoopInfo, note whether any of the preds crosses
346 // an interesting loop boundary.
347 if (!L)
348 continue;
349 if (L->contains(Pred))
350 IsLoopEntry = false;
351 else
352 SplitMakesNewLoopHeader = true;
Bill Wendling0a693f42011-08-18 05:25:23 +0000353 }
354
Chandler Carruthb5797b62015-01-18 09:21:15 +0000355 // Unless we have a loop for OldBB, nothing else to do here.
356 if (!L)
357 return;
Bill Wendling0a693f42011-08-18 05:25:23 +0000358
359 if (IsLoopEntry) {
360 // Add the new block to the nearest enclosing loop (and not an adjacent
361 // loop). To find this, examine each of the predecessors and determine which
362 // loops enclose them, and select the most-nested loop which contains the
363 // loop containing the block being split.
Craig Topperf40110f2014-04-25 05:29:35 +0000364 Loop *InnermostPredLoop = nullptr;
Bill Wendlingec3823d2011-08-18 20:39:32 +0000365 for (ArrayRef<BasicBlock*>::iterator
366 i = Preds.begin(), e = Preds.end(); i != e; ++i) {
367 BasicBlock *Pred = *i;
368 if (Loop *PredLoop = LI->getLoopFor(Pred)) {
Bill Wendling0a693f42011-08-18 05:25:23 +0000369 // Seek a loop which actually contains the block being split (to avoid
370 // adjacent loops).
371 while (PredLoop && !PredLoop->contains(OldBB))
372 PredLoop = PredLoop->getParentLoop();
373
374 // Select the most-nested of these loops which contains the block.
375 if (PredLoop && PredLoop->contains(OldBB) &&
376 (!InnermostPredLoop ||
377 InnermostPredLoop->getLoopDepth() < PredLoop->getLoopDepth()))
378 InnermostPredLoop = PredLoop;
379 }
Bill Wendlingec3823d2011-08-18 20:39:32 +0000380 }
Bill Wendling0a693f42011-08-18 05:25:23 +0000381
382 if (InnermostPredLoop)
Chandler Carruth691addc2015-01-18 01:25:51 +0000383 InnermostPredLoop->addBasicBlockToLoop(NewBB, *LI);
Bill Wendling0a693f42011-08-18 05:25:23 +0000384 } else {
Chandler Carruth691addc2015-01-18 01:25:51 +0000385 L->addBasicBlockToLoop(NewBB, *LI);
Bill Wendling0a693f42011-08-18 05:25:23 +0000386 if (SplitMakesNewLoopHeader)
387 L->moveToHeader(NewBB);
388 }
389}
390
Bill Wendlingb267e2a2011-08-18 20:51:04 +0000391/// UpdatePHINodes - Update the PHI nodes in OrigBB to include the values coming
392/// from NewBB. This also updates AliasAnalysis, if available.
393static void UpdatePHINodes(BasicBlock *OrigBB, BasicBlock *NewBB,
Chandler Carruthb5797b62015-01-18 09:21:15 +0000394 ArrayRef<BasicBlock *> Preds, BranchInst *BI,
Chandler Carruth96ada252015-07-22 09:52:54 +0000395 bool HasLoopExit) {
Bill Wendlingb267e2a2011-08-18 20:51:04 +0000396 // Otherwise, create a new PHI node in NewBB for each PHI node in OrigBB.
Chandler Carruth5bdf72c2014-04-28 10:37:30 +0000397 SmallPtrSet<BasicBlock *, 16> PredSet(Preds.begin(), Preds.end());
Bill Wendlingb267e2a2011-08-18 20:51:04 +0000398 for (BasicBlock::iterator I = OrigBB->begin(); isa<PHINode>(I); ) {
399 PHINode *PN = cast<PHINode>(I++);
400
401 // Check to see if all of the values coming in are the same. If so, we
402 // don't need to create a new PHI node, unless it's needed for LCSSA.
Craig Topperf40110f2014-04-25 05:29:35 +0000403 Value *InVal = nullptr;
Bill Wendlingb267e2a2011-08-18 20:51:04 +0000404 if (!HasLoopExit) {
405 InVal = PN->getIncomingValueForBlock(Preds[0]);
Chandler Carruth5bdf72c2014-04-28 10:37:30 +0000406 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) {
407 if (!PredSet.count(PN->getIncomingBlock(i)))
408 continue;
409 if (!InVal)
410 InVal = PN->getIncomingValue(i);
411 else if (InVal != PN->getIncomingValue(i)) {
Craig Topperf40110f2014-04-25 05:29:35 +0000412 InVal = nullptr;
Bill Wendlingb267e2a2011-08-18 20:51:04 +0000413 break;
414 }
Chandler Carruth5bdf72c2014-04-28 10:37:30 +0000415 }
Bill Wendlingb267e2a2011-08-18 20:51:04 +0000416 }
417
418 if (InVal) {
419 // If all incoming values for the new PHI would be the same, just don't
420 // make a new PHI. Instead, just remove the incoming values from the old
421 // PHI.
Jakub Staszak190db2f2013-01-14 23:16:36 +0000422
Chandler Carruth5bdf72c2014-04-28 10:37:30 +0000423 // NOTE! This loop walks backwards for a reason! First off, this minimizes
424 // the cost of removal if we end up removing a large number of values, and
425 // second off, this ensures that the indices for the incoming values
426 // aren't invalidated when we remove one.
427 for (int64_t i = PN->getNumIncomingValues() - 1; i >= 0; --i)
428 if (PredSet.count(PN->getIncomingBlock(i)))
429 PN->removeIncomingValue(i, false);
Bill Wendlingb267e2a2011-08-18 20:51:04 +0000430
Chandler Carruth5bdf72c2014-04-28 10:37:30 +0000431 // Add an incoming value to the PHI node in the loop for the preheader
432 // edge.
433 PN->addIncoming(InVal, NewBB);
434 continue;
Bill Wendlingb267e2a2011-08-18 20:51:04 +0000435 }
436
Chandler Carruth5bdf72c2014-04-28 10:37:30 +0000437 // If the values coming into the block are not the same, we need a new
438 // PHI.
439 // Create the new PHI node, insert it into NewBB at the end of the block
440 PHINode *NewPHI =
441 PHINode::Create(PN->getType(), Preds.size(), PN->getName() + ".ph", BI);
Chandler Carruth5bdf72c2014-04-28 10:37:30 +0000442
443 // NOTE! This loop walks backwards for a reason! First off, this minimizes
444 // the cost of removal if we end up removing a large number of values, and
445 // second off, this ensures that the indices for the incoming values aren't
446 // invalidated when we remove one.
447 for (int64_t i = PN->getNumIncomingValues() - 1; i >= 0; --i) {
448 BasicBlock *IncomingBB = PN->getIncomingBlock(i);
449 if (PredSet.count(IncomingBB)) {
450 Value *V = PN->removeIncomingValue(i, false);
451 NewPHI->addIncoming(V, IncomingBB);
452 }
453 }
454
455 PN->addIncoming(NewPHI, NewBB);
Bill Wendlingb267e2a2011-08-18 20:51:04 +0000456 }
457}
458
Philip Reames9198b332015-01-28 23:06:47 +0000459/// SplitBlockPredecessors - This method introduces at least one new basic block
460/// into the function and moves some of the predecessors of BB to be
461/// predecessors of the new block. The new predecessors are indicated by the
462/// Preds array. The new block is given a suffix of 'Suffix'. Returns new basic
463/// block to which predecessors from Preds are now pointing.
464///
465/// If BB is a landingpad block then additional basicblock might be introduced.
466/// It will have suffix of 'Suffix'+".split_lp".
467/// See SplitLandingPadPredecessors for more details on this case.
Chris Lattnera5b11702008-04-21 01:28:02 +0000468///
Dan Gohman3ddbc242009-09-08 15:45:00 +0000469/// This currently updates the LLVM IR, AliasAnalysis, DominatorTree,
Cameron Zwarichb7036542011-01-18 04:11:31 +0000470/// LoopInfo, and LCCSA but no other analyses. In particular, it does not
471/// preserve LoopSimplify (because it's complicated to handle the case where one
472/// of the edges being split is an exit of a loop with other exits).
Dan Gohman3ddbc242009-09-08 15:45:00 +0000473///
Jakub Staszak190db2f2013-01-14 23:16:36 +0000474BasicBlock *llvm::SplitBlockPredecessors(BasicBlock *BB,
Chandler Carruthb5797b62015-01-18 09:21:15 +0000475 ArrayRef<BasicBlock *> Preds,
Chandler Carruth96ada252015-07-22 09:52:54 +0000476 const char *Suffix, DominatorTree *DT,
477 LoopInfo *LI, bool PreserveLCSSA) {
David Majnemer654e1302015-07-31 17:58:14 +0000478 // Do not attempt to split that which cannot be split.
479 if (!BB->canSplitPredecessors())
480 return nullptr;
481
Philip Reames9198b332015-01-28 23:06:47 +0000482 // For the landingpads we need to act a bit differently.
483 // Delegate this work to the SplitLandingPadPredecessors.
484 if (BB->isLandingPad()) {
485 SmallVector<BasicBlock*, 2> NewBBs;
486 std::string NewName = std::string(Suffix) + ".split-lp";
487
Chandler Carruth96ada252015-07-22 09:52:54 +0000488 SplitLandingPadPredecessors(BB, Preds, Suffix, NewName.c_str(), NewBBs, DT,
489 LI, PreserveLCSSA);
Philip Reames9198b332015-01-28 23:06:47 +0000490 return NewBBs[0];
491 }
492
Chris Lattnera5b11702008-04-21 01:28:02 +0000493 // Create new basic block, insert right before the original block.
Alexey Samsonovb7f02d32015-06-09 22:10:29 +0000494 BasicBlock *NewBB = BasicBlock::Create(
495 BB->getContext(), BB->getName() + Suffix, BB->getParent(), BB);
Jakub Staszak190db2f2013-01-14 23:16:36 +0000496
Chris Lattnera5b11702008-04-21 01:28:02 +0000497 // The new block unconditionally branches to the old block.
498 BranchInst *BI = BranchInst::Create(BB, NewBB);
Alexey Samsonovb7f02d32015-06-09 22:10:29 +0000499 BI->setDebugLoc(BB->getFirstNonPHI()->getDebugLoc());
Jakub Staszak190db2f2013-01-14 23:16:36 +0000500
Chris Lattnera5b11702008-04-21 01:28:02 +0000501 // Move the edges from Preds to point to NewBB instead of BB.
Jakub Staszakf5b32e52011-12-09 21:19:53 +0000502 for (unsigned i = 0, e = Preds.size(); i != e; ++i) {
Dan Gohman00c79382009-11-05 18:25:44 +0000503 // This is slightly more strict than necessary; the minimum requirement
504 // is that there be no more than one indirectbr branching to BB. And
505 // all BlockAddress uses would need to be updated.
506 assert(!isa<IndirectBrInst>(Preds[i]->getTerminator()) &&
507 "Cannot split an edge from an IndirectBrInst");
Chris Lattnera5b11702008-04-21 01:28:02 +0000508 Preds[i]->getTerminator()->replaceUsesOfWith(BB, NewBB);
Dan Gohman3ddbc242009-09-08 15:45:00 +0000509 }
510
Chris Lattnera5b11702008-04-21 01:28:02 +0000511 // Insert a new PHI node into NewBB for every PHI node in BB and that new PHI
512 // node becomes an incoming value for BB's phi node. However, if the Preds
513 // list is empty, we need to insert dummy entries into the PHI nodes in BB to
514 // account for the newly created predecessor.
Jakub Staszakf5b32e52011-12-09 21:19:53 +0000515 if (Preds.size() == 0) {
Chris Lattnera5b11702008-04-21 01:28:02 +0000516 // Insert dummy values as the incoming value.
517 for (BasicBlock::iterator I = BB->begin(); isa<PHINode>(I); ++I)
Owen Andersonb292b8c2009-07-30 23:03:37 +0000518 cast<PHINode>(I)->addIncoming(UndefValue::get(I->getType()), NewBB);
Chris Lattnera5b11702008-04-21 01:28:02 +0000519 return NewBB;
520 }
Dan Gohman3ddbc242009-09-08 15:45:00 +0000521
Bill Wendling0a693f42011-08-18 05:25:23 +0000522 // Update DominatorTree, LoopInfo, and LCCSA analysis information.
523 bool HasLoopExit = false;
Chandler Carruthb5797b62015-01-18 09:21:15 +0000524 UpdateAnalysisInformation(BB, NewBB, Preds, DT, LI, PreserveLCSSA,
525 HasLoopExit);
Dan Gohman3ddbc242009-09-08 15:45:00 +0000526
Bill Wendlingb267e2a2011-08-18 20:51:04 +0000527 // Update the PHI nodes in BB with the values coming from NewBB.
Chandler Carruth96ada252015-07-22 09:52:54 +0000528 UpdatePHINodes(BB, NewBB, Preds, BI, HasLoopExit);
Chris Lattnera5b11702008-04-21 01:28:02 +0000529 return NewBB;
530}
Chris Lattner72f16e72008-11-27 08:10:05 +0000531
Bill Wendlingca7d3092011-08-19 00:05:40 +0000532/// SplitLandingPadPredecessors - This method transforms the landing pad,
533/// OrigBB, by introducing two new basic blocks into the function. One of those
534/// new basic blocks gets the predecessors listed in Preds. The other basic
535/// block gets the remaining predecessors of OrigBB. The landingpad instruction
536/// OrigBB is clone into both of the new basic blocks. The new blocks are given
537/// the suffixes 'Suffix1' and 'Suffix2', and are returned in the NewBBs vector.
Jakub Staszak190db2f2013-01-14 23:16:36 +0000538///
Bill Wendlingca7d3092011-08-19 00:05:40 +0000539/// This currently updates the LLVM IR, AliasAnalysis, DominatorTree,
540/// DominanceFrontier, LoopInfo, and LCCSA but no other analyses. In particular,
541/// it does not preserve LoopSimplify (because it's complicated to handle the
542/// case where one of the edges being split is an exit of a loop with other
543/// exits).
Jakub Staszak190db2f2013-01-14 23:16:36 +0000544///
Bill Wendlingca7d3092011-08-19 00:05:40 +0000545void llvm::SplitLandingPadPredecessors(BasicBlock *OrigBB,
Chandler Carruth0eae1122015-01-19 03:03:39 +0000546 ArrayRef<BasicBlock *> Preds,
Bill Wendlingca7d3092011-08-19 00:05:40 +0000547 const char *Suffix1, const char *Suffix2,
Chandler Carruth0eae1122015-01-19 03:03:39 +0000548 SmallVectorImpl<BasicBlock *> &NewBBs,
Chandler Carruth96ada252015-07-22 09:52:54 +0000549 DominatorTree *DT, LoopInfo *LI,
550 bool PreserveLCSSA) {
Bill Wendlingca7d3092011-08-19 00:05:40 +0000551 assert(OrigBB->isLandingPad() && "Trying to split a non-landing pad!");
552
553 // Create a new basic block for OrigBB's predecessors listed in Preds. Insert
554 // it right before the original block.
555 BasicBlock *NewBB1 = BasicBlock::Create(OrigBB->getContext(),
556 OrigBB->getName() + Suffix1,
557 OrigBB->getParent(), OrigBB);
558 NewBBs.push_back(NewBB1);
559
560 // The new block unconditionally branches to the old block.
561 BranchInst *BI1 = BranchInst::Create(OrigBB, NewBB1);
Alexey Samsonovb7f02d32015-06-09 22:10:29 +0000562 BI1->setDebugLoc(OrigBB->getFirstNonPHI()->getDebugLoc());
Bill Wendlingca7d3092011-08-19 00:05:40 +0000563
564 // Move the edges from Preds to point to NewBB1 instead of OrigBB.
565 for (unsigned i = 0, e = Preds.size(); i != e; ++i) {
566 // This is slightly more strict than necessary; the minimum requirement
567 // is that there be no more than one indirectbr branching to BB. And
568 // all BlockAddress uses would need to be updated.
569 assert(!isa<IndirectBrInst>(Preds[i]->getTerminator()) &&
570 "Cannot split an edge from an IndirectBrInst");
571 Preds[i]->getTerminator()->replaceUsesOfWith(OrigBB, NewBB1);
572 }
573
Bill Wendlingca7d3092011-08-19 00:05:40 +0000574 bool HasLoopExit = false;
Chandler Carruthb5797b62015-01-18 09:21:15 +0000575 UpdateAnalysisInformation(OrigBB, NewBB1, Preds, DT, LI, PreserveLCSSA,
576 HasLoopExit);
Bill Wendlingca7d3092011-08-19 00:05:40 +0000577
578 // Update the PHI nodes in OrigBB with the values coming from NewBB1.
Chandler Carruth96ada252015-07-22 09:52:54 +0000579 UpdatePHINodes(OrigBB, NewBB1, Preds, BI1, HasLoopExit);
Bill Wendlingca7d3092011-08-19 00:05:40 +0000580
Bill Wendlingca7d3092011-08-19 00:05:40 +0000581 // Move the remaining edges from OrigBB to point to NewBB2.
582 SmallVector<BasicBlock*, 8> NewBB2Preds;
Duncan P. N. Exon Smith6c990152014-07-21 17:06:51 +0000583 for (pred_iterator i = pred_begin(OrigBB), e = pred_end(OrigBB);
584 i != e; ) {
585 BasicBlock *Pred = *i++;
Bill Wendling38d81302011-08-19 23:46:30 +0000586 if (Pred == NewBB1) continue;
Bill Wendlingca7d3092011-08-19 00:05:40 +0000587 assert(!isa<IndirectBrInst>(Pred->getTerminator()) &&
588 "Cannot split an edge from an IndirectBrInst");
Bill Wendlingca7d3092011-08-19 00:05:40 +0000589 NewBB2Preds.push_back(Pred);
Duncan P. N. Exon Smith6c990152014-07-21 17:06:51 +0000590 e = pred_end(OrigBB);
Bill Wendlingca7d3092011-08-19 00:05:40 +0000591 }
592
Craig Topperf40110f2014-04-25 05:29:35 +0000593 BasicBlock *NewBB2 = nullptr;
Bill Wendling38d81302011-08-19 23:46:30 +0000594 if (!NewBB2Preds.empty()) {
595 // Create another basic block for the rest of OrigBB's predecessors.
596 NewBB2 = BasicBlock::Create(OrigBB->getContext(),
597 OrigBB->getName() + Suffix2,
598 OrigBB->getParent(), OrigBB);
599 NewBBs.push_back(NewBB2);
Bill Wendlingca7d3092011-08-19 00:05:40 +0000600
Bill Wendling38d81302011-08-19 23:46:30 +0000601 // The new block unconditionally branches to the old block.
602 BranchInst *BI2 = BranchInst::Create(OrigBB, NewBB2);
Alexey Samsonovb7f02d32015-06-09 22:10:29 +0000603 BI2->setDebugLoc(OrigBB->getFirstNonPHI()->getDebugLoc());
Bill Wendling38d81302011-08-19 23:46:30 +0000604
605 // Move the remaining edges from OrigBB to point to NewBB2.
606 for (SmallVectorImpl<BasicBlock*>::iterator
607 i = NewBB2Preds.begin(), e = NewBB2Preds.end(); i != e; ++i)
608 (*i)->getTerminator()->replaceUsesOfWith(OrigBB, NewBB2);
609
610 // Update DominatorTree, LoopInfo, and LCCSA analysis information.
611 HasLoopExit = false;
Chandler Carruthb5797b62015-01-18 09:21:15 +0000612 UpdateAnalysisInformation(OrigBB, NewBB2, NewBB2Preds, DT, LI,
613 PreserveLCSSA, HasLoopExit);
Bill Wendling38d81302011-08-19 23:46:30 +0000614
615 // Update the PHI nodes in OrigBB with the values coming from NewBB2.
Chandler Carruth96ada252015-07-22 09:52:54 +0000616 UpdatePHINodes(OrigBB, NewBB2, NewBB2Preds, BI2, HasLoopExit);
Bill Wendling38d81302011-08-19 23:46:30 +0000617 }
Bill Wendlingca7d3092011-08-19 00:05:40 +0000618
619 LandingPadInst *LPad = OrigBB->getLandingPadInst();
620 Instruction *Clone1 = LPad->clone();
621 Clone1->setName(Twine("lpad") + Suffix1);
622 NewBB1->getInstList().insert(NewBB1->getFirstInsertionPt(), Clone1);
623
Bill Wendling38d81302011-08-19 23:46:30 +0000624 if (NewBB2) {
625 Instruction *Clone2 = LPad->clone();
626 Clone2->setName(Twine("lpad") + Suffix2);
627 NewBB2->getInstList().insert(NewBB2->getFirstInsertionPt(), Clone2);
Bill Wendlingca7d3092011-08-19 00:05:40 +0000628
Bill Wendling38d81302011-08-19 23:46:30 +0000629 // Create a PHI node for the two cloned landingpad instructions.
630 PHINode *PN = PHINode::Create(LPad->getType(), 2, "lpad.phi", LPad);
631 PN->addIncoming(Clone1, NewBB1);
632 PN->addIncoming(Clone2, NewBB2);
633 LPad->replaceAllUsesWith(PN);
634 LPad->eraseFromParent();
635 } else {
636 // There is no second clone. Just replace the landing pad with the first
637 // clone.
638 LPad->replaceAllUsesWith(Clone1);
639 LPad->eraseFromParent();
640 }
Bill Wendlingca7d3092011-08-19 00:05:40 +0000641}
642
Evan Chengd983eba2011-01-29 04:46:23 +0000643/// FoldReturnIntoUncondBranch - This method duplicates the specified return
644/// instruction into a predecessor which ends in an unconditional branch. If
645/// the return instruction returns a value defined by a PHI, propagate the
646/// right value into the return. It returns the new return instruction in the
647/// predecessor.
648ReturnInst *llvm::FoldReturnIntoUncondBranch(ReturnInst *RI, BasicBlock *BB,
649 BasicBlock *Pred) {
650 Instruction *UncondBranch = Pred->getTerminator();
651 // Clone the return and add it to the end of the predecessor.
652 Instruction *NewRet = RI->clone();
653 Pred->getInstList().push_back(NewRet);
Jakub Staszak190db2f2013-01-14 23:16:36 +0000654
Evan Chengd983eba2011-01-29 04:46:23 +0000655 // If the return instruction returns a value, and if the value was a
656 // PHI node in "BB", propagate the right value into the return.
657 for (User::op_iterator i = NewRet->op_begin(), e = NewRet->op_end();
Evan Cheng249716e2012-07-27 21:21:26 +0000658 i != e; ++i) {
659 Value *V = *i;
Craig Topperf40110f2014-04-25 05:29:35 +0000660 Instruction *NewBC = nullptr;
Evan Cheng249716e2012-07-27 21:21:26 +0000661 if (BitCastInst *BCI = dyn_cast<BitCastInst>(V)) {
662 // Return value might be bitcasted. Clone and insert it before the
663 // return instruction.
664 V = BCI->getOperand(0);
665 NewBC = BCI->clone();
666 Pred->getInstList().insert(NewRet, NewBC);
667 *i = NewBC;
668 }
669 if (PHINode *PN = dyn_cast<PHINode>(V)) {
670 if (PN->getParent() == BB) {
671 if (NewBC)
672 NewBC->setOperand(0, PN->getIncomingValueForBlock(Pred));
673 else
674 *i = PN->getIncomingValueForBlock(Pred);
675 }
676 }
677 }
Jakub Staszak190db2f2013-01-14 23:16:36 +0000678
Evan Chengd983eba2011-01-29 04:46:23 +0000679 // Update any PHI nodes in the returning block to realize that we no
680 // longer branch to them.
681 BB->removePredecessor(Pred);
682 UncondBranch->eraseFromParent();
683 return cast<ReturnInst>(NewRet);
Chris Lattner351134b2009-05-04 02:25:58 +0000684}
Devang Patela8e74112011-04-29 22:28:59 +0000685
Evgeniy Stepanov8eb77d82012-10-19 10:48:31 +0000686/// SplitBlockAndInsertIfThen - Split the containing block at the
Evgeniy Stepanova9164e92013-12-19 13:29:56 +0000687/// specified instruction - everything before and including SplitBefore stays
688/// in the old basic block, and everything after SplitBefore is moved to a
Evgeniy Stepanov8eb77d82012-10-19 10:48:31 +0000689/// new block. The two blocks are connected by a conditional branch
690/// (with value of Cmp being the condition).
691/// Before:
692/// Head
Evgeniy Stepanova9164e92013-12-19 13:29:56 +0000693/// SplitBefore
Evgeniy Stepanov8eb77d82012-10-19 10:48:31 +0000694/// Tail
695/// After:
696/// Head
Evgeniy Stepanova9164e92013-12-19 13:29:56 +0000697/// if (Cond)
Evgeniy Stepanov8eb77d82012-10-19 10:48:31 +0000698/// ThenBlock
Evgeniy Stepanova9164e92013-12-19 13:29:56 +0000699/// SplitBefore
Evgeniy Stepanov8eb77d82012-10-19 10:48:31 +0000700/// Tail
701///
702/// If Unreachable is true, then ThenBlock ends with
703/// UnreachableInst, otherwise it branches to Tail.
704/// Returns the NewBasicBlock's terminator.
705
Evgeniy Stepanova9164e92013-12-19 13:29:56 +0000706TerminatorInst *llvm::SplitBlockAndInsertIfThen(Value *Cond,
707 Instruction *SplitBefore,
708 bool Unreachable,
Peter Collingbourne818f5c42014-07-15 04:40:27 +0000709 MDNode *BranchWeights,
710 DominatorTree *DT) {
Evgeniy Stepanov8eb77d82012-10-19 10:48:31 +0000711 BasicBlock *Head = SplitBefore->getParent();
712 BasicBlock *Tail = Head->splitBasicBlock(SplitBefore);
713 TerminatorInst *HeadOldTerm = Head->getTerminator();
714 LLVMContext &C = Head->getContext();
715 BasicBlock *ThenBlock = BasicBlock::Create(C, "", Head->getParent(), Tail);
716 TerminatorInst *CheckTerm;
717 if (Unreachable)
718 CheckTerm = new UnreachableInst(C, ThenBlock);
719 else
720 CheckTerm = BranchInst::Create(Tail, ThenBlock);
Evgeniy Stepanov2275a012014-03-19 12:56:38 +0000721 CheckTerm->setDebugLoc(SplitBefore->getDebugLoc());
Evgeniy Stepanov8eb77d82012-10-19 10:48:31 +0000722 BranchInst *HeadNewTerm =
Evgeniy Stepanova9164e92013-12-19 13:29:56 +0000723 BranchInst::Create(/*ifTrue*/ThenBlock, /*ifFalse*/Tail, Cond);
Evgeniy Stepanov8eb77d82012-10-19 10:48:31 +0000724 HeadNewTerm->setMetadata(LLVMContext::MD_prof, BranchWeights);
725 ReplaceInstWithInst(HeadOldTerm, HeadNewTerm);
Peter Collingbourne818f5c42014-07-15 04:40:27 +0000726
727 if (DT) {
728 if (DomTreeNode *OldNode = DT->getNode(Head)) {
729 std::vector<DomTreeNode *> Children(OldNode->begin(), OldNode->end());
730
731 DomTreeNode *NewNode = DT->addNewBlock(Tail, Head);
732 for (auto Child : Children)
733 DT->changeImmediateDominator(Child, NewNode);
734
735 // Head dominates ThenBlock.
736 DT->addNewBlock(ThenBlock, Head);
737 }
738 }
739
Evgeniy Stepanov8eb77d82012-10-19 10:48:31 +0000740 return CheckTerm;
741}
Tom Stellardaa664d92013-08-06 02:43:45 +0000742
Kostya Serebryany530e2072013-12-23 14:15:08 +0000743/// SplitBlockAndInsertIfThenElse is similar to SplitBlockAndInsertIfThen,
744/// but also creates the ElseBlock.
745/// Before:
746/// Head
747/// SplitBefore
748/// Tail
749/// After:
750/// Head
751/// if (Cond)
752/// ThenBlock
753/// else
754/// ElseBlock
755/// SplitBefore
756/// Tail
757void llvm::SplitBlockAndInsertIfThenElse(Value *Cond, Instruction *SplitBefore,
758 TerminatorInst **ThenTerm,
759 TerminatorInst **ElseTerm,
760 MDNode *BranchWeights) {
761 BasicBlock *Head = SplitBefore->getParent();
762 BasicBlock *Tail = Head->splitBasicBlock(SplitBefore);
763 TerminatorInst *HeadOldTerm = Head->getTerminator();
764 LLVMContext &C = Head->getContext();
765 BasicBlock *ThenBlock = BasicBlock::Create(C, "", Head->getParent(), Tail);
766 BasicBlock *ElseBlock = BasicBlock::Create(C, "", Head->getParent(), Tail);
767 *ThenTerm = BranchInst::Create(Tail, ThenBlock);
Evgeniy Stepanov2275a012014-03-19 12:56:38 +0000768 (*ThenTerm)->setDebugLoc(SplitBefore->getDebugLoc());
Kostya Serebryany530e2072013-12-23 14:15:08 +0000769 *ElseTerm = BranchInst::Create(Tail, ElseBlock);
Evgeniy Stepanov2275a012014-03-19 12:56:38 +0000770 (*ElseTerm)->setDebugLoc(SplitBefore->getDebugLoc());
Kostya Serebryany530e2072013-12-23 14:15:08 +0000771 BranchInst *HeadNewTerm =
772 BranchInst::Create(/*ifTrue*/ThenBlock, /*ifFalse*/ElseBlock, Cond);
773 HeadNewTerm->setMetadata(LLVMContext::MD_prof, BranchWeights);
774 ReplaceInstWithInst(HeadOldTerm, HeadNewTerm);
775}
776
777
Tom Stellardaa664d92013-08-06 02:43:45 +0000778/// GetIfCondition - Given a basic block (BB) with two predecessors,
779/// check to see if the merge at this block is due
780/// to an "if condition". If so, return the boolean condition that determines
781/// which entry into BB will be taken. Also, return by references the block
782/// that will be entered from if the condition is true, and the block that will
783/// be entered if the condition is false.
784///
785/// This does no checking to see if the true/false blocks have large or unsavory
786/// instructions in them.
787Value *llvm::GetIfCondition(BasicBlock *BB, BasicBlock *&IfTrue,
788 BasicBlock *&IfFalse) {
789 PHINode *SomePHI = dyn_cast<PHINode>(BB->begin());
Craig Topperf40110f2014-04-25 05:29:35 +0000790 BasicBlock *Pred1 = nullptr;
791 BasicBlock *Pred2 = nullptr;
Tom Stellardaa664d92013-08-06 02:43:45 +0000792
793 if (SomePHI) {
794 if (SomePHI->getNumIncomingValues() != 2)
Craig Topperf40110f2014-04-25 05:29:35 +0000795 return nullptr;
Tom Stellardaa664d92013-08-06 02:43:45 +0000796 Pred1 = SomePHI->getIncomingBlock(0);
797 Pred2 = SomePHI->getIncomingBlock(1);
798 } else {
799 pred_iterator PI = pred_begin(BB), PE = pred_end(BB);
800 if (PI == PE) // No predecessor
Craig Topperf40110f2014-04-25 05:29:35 +0000801 return nullptr;
Tom Stellardaa664d92013-08-06 02:43:45 +0000802 Pred1 = *PI++;
803 if (PI == PE) // Only one predecessor
Craig Topperf40110f2014-04-25 05:29:35 +0000804 return nullptr;
Tom Stellardaa664d92013-08-06 02:43:45 +0000805 Pred2 = *PI++;
806 if (PI != PE) // More than two predecessors
Craig Topperf40110f2014-04-25 05:29:35 +0000807 return nullptr;
Tom Stellardaa664d92013-08-06 02:43:45 +0000808 }
809
810 // We can only handle branches. Other control flow will be lowered to
811 // branches if possible anyway.
812 BranchInst *Pred1Br = dyn_cast<BranchInst>(Pred1->getTerminator());
813 BranchInst *Pred2Br = dyn_cast<BranchInst>(Pred2->getTerminator());
Craig Topperf40110f2014-04-25 05:29:35 +0000814 if (!Pred1Br || !Pred2Br)
815 return nullptr;
Tom Stellardaa664d92013-08-06 02:43:45 +0000816
817 // Eliminate code duplication by ensuring that Pred1Br is conditional if
818 // either are.
819 if (Pred2Br->isConditional()) {
820 // If both branches are conditional, we don't have an "if statement". In
821 // reality, we could transform this case, but since the condition will be
822 // required anyway, we stand no chance of eliminating it, so the xform is
823 // probably not profitable.
824 if (Pred1Br->isConditional())
Craig Topperf40110f2014-04-25 05:29:35 +0000825 return nullptr;
Tom Stellardaa664d92013-08-06 02:43:45 +0000826
827 std::swap(Pred1, Pred2);
828 std::swap(Pred1Br, Pred2Br);
829 }
830
831 if (Pred1Br->isConditional()) {
832 // The only thing we have to watch out for here is to make sure that Pred2
833 // doesn't have incoming edges from other blocks. If it does, the condition
834 // doesn't dominate BB.
Craig Topperf40110f2014-04-25 05:29:35 +0000835 if (!Pred2->getSinglePredecessor())
836 return nullptr;
Tom Stellardaa664d92013-08-06 02:43:45 +0000837
838 // If we found a conditional branch predecessor, make sure that it branches
839 // to BB and Pred2Br. If it doesn't, this isn't an "if statement".
840 if (Pred1Br->getSuccessor(0) == BB &&
841 Pred1Br->getSuccessor(1) == Pred2) {
842 IfTrue = Pred1;
843 IfFalse = Pred2;
844 } else if (Pred1Br->getSuccessor(0) == Pred2 &&
845 Pred1Br->getSuccessor(1) == BB) {
846 IfTrue = Pred2;
847 IfFalse = Pred1;
848 } else {
849 // We know that one arm of the conditional goes to BB, so the other must
850 // go somewhere unrelated, and this must not be an "if statement".
Craig Topperf40110f2014-04-25 05:29:35 +0000851 return nullptr;
Tom Stellardaa664d92013-08-06 02:43:45 +0000852 }
853
854 return Pred1Br->getCondition();
855 }
856
857 // Ok, if we got here, both predecessors end with an unconditional branch to
858 // BB. Don't panic! If both blocks only have a single (identical)
859 // predecessor, and THAT is a conditional branch, then we're all ok!
860 BasicBlock *CommonPred = Pred1->getSinglePredecessor();
Craig Topperf40110f2014-04-25 05:29:35 +0000861 if (CommonPred == nullptr || CommonPred != Pred2->getSinglePredecessor())
862 return nullptr;
Tom Stellardaa664d92013-08-06 02:43:45 +0000863
864 // Otherwise, if this is a conditional branch, then we can use it!
865 BranchInst *BI = dyn_cast<BranchInst>(CommonPred->getTerminator());
Craig Topperf40110f2014-04-25 05:29:35 +0000866 if (!BI) return nullptr;
Tom Stellardaa664d92013-08-06 02:43:45 +0000867
868 assert(BI->isConditional() && "Two successors but not conditional?");
869 if (BI->getSuccessor(0) == Pred1) {
870 IfTrue = Pred1;
871 IfFalse = Pred2;
872 } else {
873 IfTrue = Pred2;
874 IfFalse = Pred1;
875 }
876 return BI->getCondition();
877}