blob: 6a237c4d1e1a47467a19fbb16a0f1825f56de30a [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 +000034void llvm::DeleteDeadBlock(BasicBlock *BB) {
Chris Lattner37e01362008-12-03 07:45:15 +000035 assert((pred_begin(BB) == pred_end(BB) ||
36 // Can delete self loop.
37 BB->getSinglePredecessor() == BB) && "Block is not dead!");
Chris Lattnerbcc904a2008-12-03 06:37:44 +000038 TerminatorInst *BBTerm = BB->getTerminator();
Jakub Staszak190db2f2013-01-14 23:16:36 +000039
Chris Lattnerbcc904a2008-12-03 06:37:44 +000040 // Loop through all of our successors and make sure they know that one
41 // of their predecessors is going away.
Pete Cooperebcd7482015-08-06 20:22:46 +000042 for (BasicBlock *Succ : BBTerm->successors())
43 Succ->removePredecessor(BB);
Jakub Staszak190db2f2013-01-14 23:16:36 +000044
Chris Lattnerbcc904a2008-12-03 06:37:44 +000045 // Zap all the instructions in the block.
46 while (!BB->empty()) {
47 Instruction &I = BB->back();
48 // If this instruction is used, replace uses with an arbitrary value.
49 // Because control flow can't get here, we don't care what we replace the
50 // value with. Note that since this block is unreachable, and all values
51 // contained within it must dominate their uses, that all uses will
52 // eventually be removed (they are themselves dead).
53 if (!I.use_empty())
Owen Andersonb292b8c2009-07-30 23:03:37 +000054 I.replaceAllUsesWith(UndefValue::get(I.getType()));
Chris Lattnerbcc904a2008-12-03 06:37:44 +000055 BB->getInstList().pop_back();
56 }
Jakub Staszak190db2f2013-01-14 23:16:36 +000057
Chris Lattnerbcc904a2008-12-03 06:37:44 +000058 // Zap the block!
59 BB->eraseFromParent();
Chris Lattnerbcc904a2008-12-03 06:37:44 +000060}
61
Chandler Carruth96ada252015-07-22 09:52:54 +000062void llvm::FoldSingleEntryPHINodes(BasicBlock *BB,
Chandler Carruth61440d22016-03-10 00:55:30 +000063 MemoryDependenceResults *MemDep) {
Chris Lattnerf6ae9042011-01-11 08:13:40 +000064 if (!isa<PHINode>(BB->begin())) return;
Jakub Staszak190db2f2013-01-14 23:16:36 +000065
Chris Lattnerdc3f6f22008-12-03 19:44:02 +000066 while (PHINode *PN = dyn_cast<PHINode>(BB->begin())) {
67 if (PN->getIncomingValue(0) != PN)
68 PN->replaceAllUsesWith(PN->getIncomingValue(0));
69 else
Owen Andersonb292b8c2009-07-30 23:03:37 +000070 PN->replaceAllUsesWith(UndefValue::get(PN->getType()));
Jakub Staszak190db2f2013-01-14 23:16:36 +000071
Chris Lattnerf6ae9042011-01-11 08:13:40 +000072 if (MemDep)
73 MemDep->removeInstruction(PN); // Memdep updates AA itself.
Jakub Staszak190db2f2013-01-14 23:16:36 +000074
Chris Lattnerdc3f6f22008-12-03 19:44:02 +000075 PN->eraseFromParent();
76 }
77}
78
Benjamin Kramer8bcc9712012-08-29 15:32:21 +000079bool llvm::DeleteDeadPHIs(BasicBlock *BB, const TargetLibraryInfo *TLI) {
Dan Gohmanff089952009-05-02 18:29:22 +000080 // Recursively deleting a PHI may cause multiple PHIs to be deleted
81 // or RAUW'd undef, so use an array of WeakVH for the PHIs to delete.
82 SmallVector<WeakVH, 8> PHIs;
83 for (BasicBlock::iterator I = BB->begin();
84 PHINode *PN = dyn_cast<PHINode>(I); ++I)
85 PHIs.push_back(PN);
86
Dan Gohmancb99fe92010-01-05 15:45:31 +000087 bool Changed = false;
Dan Gohmanff089952009-05-02 18:29:22 +000088 for (unsigned i = 0, e = PHIs.size(); i != e; ++i)
89 if (PHINode *PN = dyn_cast_or_null<PHINode>(PHIs[i].operator Value*()))
Benjamin Kramer8bcc9712012-08-29 15:32:21 +000090 Changed |= RecursivelyDeleteDeadPHINode(PN, TLI);
Dan Gohmancb99fe92010-01-05 15:45:31 +000091
92 return Changed;
Dan Gohmanff089952009-05-02 18:29:22 +000093}
94
Chandler Carruthb5c11532015-01-18 02:11:23 +000095bool llvm::MergeBlockIntoPredecessor(BasicBlock *BB, DominatorTree *DT,
Chandler Carruth96ada252015-07-22 09:52:54 +000096 LoopInfo *LI,
Chandler Carruth61440d22016-03-10 00:55:30 +000097 MemoryDependenceResults *MemDep) {
Dan Gohman941020e2010-08-17 17:07:02 +000098 // Don't merge away blocks who have their address taken.
99 if (BB->hasAddressTaken()) return false;
Jakub Staszak190db2f2013-01-14 23:16:36 +0000100
Dan Gohman941020e2010-08-17 17:07:02 +0000101 // Can't merge if there are multiple predecessors, or no predecessors.
102 BasicBlock *PredBB = BB->getUniquePredecessor();
Dan Gohman2d02ff82009-10-31 17:33:01 +0000103 if (!PredBB) return false;
Dan Gohman941020e2010-08-17 17:07:02 +0000104
Dan Gohman2d02ff82009-10-31 17:33:01 +0000105 // Don't break self-loops.
106 if (PredBB == BB) return false;
David Majnemer654e1302015-07-31 17:58:14 +0000107 // Don't break unwinding instructions.
108 if (PredBB->getTerminator()->isExceptional())
109 return false;
Jakub Staszak190db2f2013-01-14 23:16:36 +0000110
Dan Gohman2d02ff82009-10-31 17:33:01 +0000111 succ_iterator SI(succ_begin(PredBB)), SE(succ_end(PredBB));
Chris Lattner930b7162011-01-08 19:08:40 +0000112 BasicBlock *OnlySucc = BB;
Dan Gohman2d02ff82009-10-31 17:33:01 +0000113 for (; SI != SE; ++SI)
114 if (*SI != OnlySucc) {
Craig Topperf40110f2014-04-25 05:29:35 +0000115 OnlySucc = nullptr; // There are multiple distinct successors!
Dan Gohman2d02ff82009-10-31 17:33:01 +0000116 break;
117 }
Jakub Staszak190db2f2013-01-14 23:16:36 +0000118
Dan Gohman2d02ff82009-10-31 17:33:01 +0000119 // Can't merge if there are multiple successors.
120 if (!OnlySucc) return false;
Devang Patel0f7a3502008-09-09 01:06:56 +0000121
Dan Gohman2d02ff82009-10-31 17:33:01 +0000122 // Can't merge if there is PHI loop.
123 for (BasicBlock::iterator BI = BB->begin(), BE = BB->end(); BI != BE; ++BI) {
124 if (PHINode *PN = dyn_cast<PHINode>(BI)) {
Pete Cooper833f34d2015-05-12 20:05:31 +0000125 for (Value *IncValue : PN->incoming_values())
126 if (IncValue == PN)
Dan Gohman2d02ff82009-10-31 17:33:01 +0000127 return false;
128 } else
129 break;
130 }
131
132 // Begin by getting rid of unneeded PHIs.
Chandler Carruthb5c11532015-01-18 02:11:23 +0000133 if (isa<PHINode>(BB->front()))
Chandler Carruth96ada252015-07-22 09:52:54 +0000134 FoldSingleEntryPHINodes(BB, MemDep);
Jakub Staszak190db2f2013-01-14 23:16:36 +0000135
Owen Andersonc0623812008-07-17 00:01:40 +0000136 // Delete the unconditional branch from the predecessor...
137 PredBB->getInstList().pop_back();
Jakub Staszak190db2f2013-01-14 23:16:36 +0000138
Owen Andersonc0623812008-07-17 00:01:40 +0000139 // Make all PHI nodes that referred to BB now refer to Pred as their
140 // source...
141 BB->replaceAllUsesWith(PredBB);
Jakub Staszak190db2f2013-01-14 23:16:36 +0000142
Jay Foad61ea0e42011-06-23 09:09:15 +0000143 // Move all definitions in the successor to the predecessor...
144 PredBB->getInstList().splice(PredBB->end(), BB->getInstList());
Jakub Staszak190db2f2013-01-14 23:16:36 +0000145
Dan Gohman2d02ff82009-10-31 17:33:01 +0000146 // Inherit predecessors name if it exists.
Owen Anderson27405ef2008-07-17 19:42:29 +0000147 if (!PredBB->hasName())
148 PredBB->takeName(BB);
Jakub Staszak190db2f2013-01-14 23:16:36 +0000149
Owen Andersonc0623812008-07-17 00:01:40 +0000150 // Finally, erase the old block and update dominator info.
Chandler Carruthb5c11532015-01-18 02:11:23 +0000151 if (DT)
152 if (DomTreeNode *DTN = DT->getNode(BB)) {
153 DomTreeNode *PredDTN = DT->getNode(PredBB);
154 SmallVector<DomTreeNode *, 8> Children(DTN->begin(), DTN->end());
Benjamin Kramer135f7352016-06-26 12:28:59 +0000155 for (DomTreeNode *DI : Children)
156 DT->changeImmediateDominator(DI, PredDTN);
Owen Andersonc0623812008-07-17 00:01:40 +0000157
Chandler Carruthb5c11532015-01-18 02:11:23 +0000158 DT->eraseNode(BB);
Owen Andersonc0623812008-07-17 00:01:40 +0000159 }
Chandler Carruthb5c11532015-01-18 02:11:23 +0000160
161 if (LI)
162 LI->removeBlock(BB);
163
164 if (MemDep)
165 MemDep->invalidateCachedPredecessors();
Jakub Staszak190db2f2013-01-14 23:16:36 +0000166
Owen Andersonc0623812008-07-17 00:01:40 +0000167 BB->eraseFromParent();
Dan Gohman2d02ff82009-10-31 17:33:01 +0000168 return true;
Owen Andersonc0623812008-07-17 00:01:40 +0000169}
170
Chris Lattnerdf3c3422004-01-09 06:12:26 +0000171void llvm::ReplaceInstWithValue(BasicBlock::InstListType &BIL,
172 BasicBlock::iterator &BI, Value *V) {
Chris Lattnerfda72b12002-06-25 16:12:52 +0000173 Instruction &I = *BI;
Chris Lattner28537df2002-05-07 18:07:59 +0000174 // Replaces all of the uses of the instruction with uses of the value
Chris Lattnerfda72b12002-06-25 16:12:52 +0000175 I.replaceAllUsesWith(V);
Chris Lattner28537df2002-05-07 18:07:59 +0000176
Chris Lattner8dd4cae2007-02-11 01:37:51 +0000177 // Make sure to propagate a name if there is one already.
178 if (I.hasName() && !V->hasName())
179 V->takeName(&I);
Misha Brukmanb1c93172005-04-21 23:48:37 +0000180
Misha Brukman7eb05a12003-08-18 14:43:39 +0000181 // Delete the unnecessary instruction now...
Chris Lattnerfda72b12002-06-25 16:12:52 +0000182 BI = BIL.erase(BI);
Chris Lattner28537df2002-05-07 18:07:59 +0000183}
184
Chris Lattnerdf3c3422004-01-09 06:12:26 +0000185void llvm::ReplaceInstWithInst(BasicBlock::InstListType &BIL,
186 BasicBlock::iterator &BI, Instruction *I) {
Craig Toppere73658d2014-04-28 04:05:08 +0000187 assert(I->getParent() == nullptr &&
Chris Lattner28537df2002-05-07 18:07:59 +0000188 "ReplaceInstWithInst: Instruction already inserted into basic block!");
189
Alexey Samsonov19ffcb92015-06-23 21:00:08 +0000190 // Copy debug location to newly added instruction, if it wasn't already set
191 // by the caller.
192 if (!I->getDebugLoc())
193 I->setDebugLoc(BI->getDebugLoc());
194
Chris Lattner28537df2002-05-07 18:07:59 +0000195 // Insert the new instruction into the basic block...
Chris Lattnerfda72b12002-06-25 16:12:52 +0000196 BasicBlock::iterator New = BIL.insert(BI, I);
Chris Lattner28537df2002-05-07 18:07:59 +0000197
198 // Replace all uses of the old instruction, and delete it.
199 ReplaceInstWithValue(BIL, BI, I);
200
201 // Move BI back to point to the newly inserted instruction
Chris Lattnerfda72b12002-06-25 16:12:52 +0000202 BI = New;
Chris Lattner28537df2002-05-07 18:07:59 +0000203}
204
Chris Lattnerdf3c3422004-01-09 06:12:26 +0000205void llvm::ReplaceInstWithInst(Instruction *From, Instruction *To) {
Chris Lattnerfda72b12002-06-25 16:12:52 +0000206 BasicBlock::iterator BI(From);
207 ReplaceInstWithInst(From->getParent()->getInstList(), BI, To);
Chris Lattner28537df2002-05-07 18:07:59 +0000208}
Chris Lattnerb17274e2002-07-29 22:32:08 +0000209
Chandler Carruthd4500562015-01-19 12:36:53 +0000210BasicBlock *llvm::SplitEdge(BasicBlock *BB, BasicBlock *Succ, DominatorTree *DT,
211 LoopInfo *LI) {
Bob Wilsonaff96b22010-02-16 21:06:42 +0000212 unsigned SuccNum = GetSuccessorNumber(BB, Succ);
Jakub Staszak190db2f2013-01-14 23:16:36 +0000213
Chandler Carruth37df2cf2015-01-19 12:09:11 +0000214 // If this is a critical edge, let SplitCriticalEdge do it.
215 TerminatorInst *LatchTerm = BB->getTerminator();
Chandler Carruthd4500562015-01-19 12:36:53 +0000216 if (SplitCriticalEdge(LatchTerm, SuccNum, CriticalEdgeSplittingOptions(DT, LI)
217 .setPreserveLCSSA()))
Chandler Carruth37df2cf2015-01-19 12:09:11 +0000218 return LatchTerm->getSuccessor(SuccNum);
Chandler Carruth32c52c72015-01-18 02:39:37 +0000219
Devang Pateld7767cc2007-07-06 21:39:20 +0000220 // If the edge isn't critical, then BB has a single successor or Succ has a
221 // single pred. Split the block.
Devang Pateld7767cc2007-07-06 21:39:20 +0000222 if (BasicBlock *SP = Succ->getSinglePredecessor()) {
223 // If the successor only has a single pred, split the top of the successor
224 // block.
225 assert(SP == BB && "CFG broken");
Craig Topperf40110f2014-04-25 05:29:35 +0000226 SP = nullptr;
Duncan P. N. Exon Smith5b4c8372015-10-13 02:39:05 +0000227 return SplitBlock(Succ, &Succ->front(), DT, LI);
Devang Pateld7767cc2007-07-06 21:39:20 +0000228 }
Jakub Staszak190db2f2013-01-14 23:16:36 +0000229
Chris Lattner30d95f92011-01-08 18:47:43 +0000230 // Otherwise, if BB has a single successor, split it at the bottom of the
231 // block.
232 assert(BB->getTerminator()->getNumSuccessors() == 1 &&
Jakub Staszak190db2f2013-01-14 23:16:36 +0000233 "Should have a single succ!");
Chandler Carruth32c52c72015-01-18 02:39:37 +0000234 return SplitBlock(BB, BB->getTerminator(), DT, LI);
Devang Pateld7767cc2007-07-06 21:39:20 +0000235}
236
Chandler Carruth37df2cf2015-01-19 12:09:11 +0000237unsigned
238llvm::SplitAllCriticalEdges(Function &F,
239 const CriticalEdgeSplittingOptions &Options) {
Kostya Serebryanye5ea4242014-11-19 00:17:31 +0000240 unsigned NumBroken = 0;
Benjamin Kramer135f7352016-06-26 12:28:59 +0000241 for (BasicBlock &BB : F) {
242 TerminatorInst *TI = BB.getTerminator();
Kostya Serebryanye5ea4242014-11-19 00:17:31 +0000243 if (TI->getNumSuccessors() > 1 && !isa<IndirectBrInst>(TI))
244 for (unsigned i = 0, e = TI->getNumSuccessors(); i != e; ++i)
Chandler Carruth37df2cf2015-01-19 12:09:11 +0000245 if (SplitCriticalEdge(TI, i, Options))
Kostya Serebryanye5ea4242014-11-19 00:17:31 +0000246 ++NumBroken;
247 }
248 return NumBroken;
249}
250
Chandler Carruth32c52c72015-01-18 02:39:37 +0000251BasicBlock *llvm::SplitBlock(BasicBlock *Old, Instruction *SplitPt,
252 DominatorTree *DT, LoopInfo *LI) {
Duncan P. N. Exon Smith5b4c8372015-10-13 02:39:05 +0000253 BasicBlock::iterator SplitIt = SplitPt->getIterator();
David Majnemer654e1302015-07-31 17:58:14 +0000254 while (isa<PHINode>(SplitIt) || SplitIt->isEHPad())
Devang Pateld7767cc2007-07-06 21:39:20 +0000255 ++SplitIt;
256 BasicBlock *New = Old->splitBasicBlock(SplitIt, Old->getName()+".split");
257
Dan Gohman3ddbc242009-09-08 15:45:00 +0000258 // The new block lives in whichever loop the old one did. This preserves
259 // LCSSA as well, because we force the split point to be after any PHI nodes.
Chandler Carruth32c52c72015-01-18 02:39:37 +0000260 if (LI)
261 if (Loop *L = LI->getLoopFor(Old))
262 L->addBasicBlockToLoop(New, *LI);
Devang Pateld7767cc2007-07-06 21:39:20 +0000263
Chandler Carruth32c52c72015-01-18 02:39:37 +0000264 if (DT)
Gabor Greif2f5f6962010-09-10 22:25:58 +0000265 // Old dominates New. New node dominates all other nodes dominated by Old.
Chandler Carruth32c52c72015-01-18 02:39:37 +0000266 if (DomTreeNode *OldNode = DT->getNode(Old)) {
Benjamin Kramer135f7352016-06-26 12:28:59 +0000267 std::vector<DomTreeNode *> Children(OldNode->begin(), OldNode->end());
Devang Patel186e0d82007-07-19 02:29:24 +0000268
Chandler Carruth32c52c72015-01-18 02:39:37 +0000269 DomTreeNode *NewNode = DT->addNewBlock(New, Old);
Benjamin Kramer135f7352016-06-26 12:28:59 +0000270 for (DomTreeNode *I : Children)
271 DT->changeImmediateDominator(I, NewNode);
Rafael Espindolad3e65e72011-08-24 18:07:01 +0000272 }
Devang Pateld7767cc2007-07-06 21:39:20 +0000273
Devang Pateld7767cc2007-07-06 21:39:20 +0000274 return New;
275}
Chris Lattnera5b11702008-04-21 01:28:02 +0000276
Sanjay Patel85ce0f12016-04-23 16:31:48 +0000277/// Update DominatorTree, LoopInfo, and LCCSA analysis information.
Bill Wendling60291352011-08-18 17:57:57 +0000278static void UpdateAnalysisInformation(BasicBlock *OldBB, BasicBlock *NewBB,
Bill Wendlingec3823d2011-08-18 20:39:32 +0000279 ArrayRef<BasicBlock *> Preds,
Chandler Carruthb5797b62015-01-18 09:21:15 +0000280 DominatorTree *DT, LoopInfo *LI,
281 bool PreserveLCSSA, bool &HasLoopExit) {
282 // Update dominator tree if available.
283 if (DT)
284 DT->splitBlock(NewBB);
Bill Wendling0a693f42011-08-18 05:25:23 +0000285
Chandler Carruthb5797b62015-01-18 09:21:15 +0000286 // The rest of the logic is only relevant for updating the loop structures.
287 if (!LI)
288 return;
289
290 Loop *L = LI->getLoopFor(OldBB);
Bill Wendling0a693f42011-08-18 05:25:23 +0000291
292 // If we need to preserve loop analyses, collect some information about how
293 // this split will affect loops.
294 bool IsLoopEntry = !!L;
295 bool SplitMakesNewLoopHeader = false;
Benjamin Kramer135f7352016-06-26 12:28:59 +0000296 for (BasicBlock *Pred : Preds) {
Chandler Carruthb5797b62015-01-18 09:21:15 +0000297 // If we need to preserve LCSSA, determine if any of the preds is a loop
298 // exit.
299 if (PreserveLCSSA)
300 if (Loop *PL = LI->getLoopFor(Pred))
301 if (!PL->contains(OldBB))
302 HasLoopExit = true;
Bill Wendling0a693f42011-08-18 05:25:23 +0000303
Chandler Carruthb5797b62015-01-18 09:21:15 +0000304 // If we need to preserve LoopInfo, note whether any of the preds crosses
305 // an interesting loop boundary.
306 if (!L)
307 continue;
308 if (L->contains(Pred))
309 IsLoopEntry = false;
310 else
311 SplitMakesNewLoopHeader = true;
Bill Wendling0a693f42011-08-18 05:25:23 +0000312 }
313
Chandler Carruthb5797b62015-01-18 09:21:15 +0000314 // Unless we have a loop for OldBB, nothing else to do here.
315 if (!L)
316 return;
Bill Wendling0a693f42011-08-18 05:25:23 +0000317
318 if (IsLoopEntry) {
319 // Add the new block to the nearest enclosing loop (and not an adjacent
320 // loop). To find this, examine each of the predecessors and determine which
321 // loops enclose them, and select the most-nested loop which contains the
322 // loop containing the block being split.
Craig Topperf40110f2014-04-25 05:29:35 +0000323 Loop *InnermostPredLoop = nullptr;
Benjamin Kramer135f7352016-06-26 12:28:59 +0000324 for (BasicBlock *Pred : Preds) {
Bill Wendlingec3823d2011-08-18 20:39:32 +0000325 if (Loop *PredLoop = LI->getLoopFor(Pred)) {
Bill Wendling0a693f42011-08-18 05:25:23 +0000326 // Seek a loop which actually contains the block being split (to avoid
327 // adjacent loops).
328 while (PredLoop && !PredLoop->contains(OldBB))
329 PredLoop = PredLoop->getParentLoop();
330
331 // Select the most-nested of these loops which contains the block.
332 if (PredLoop && PredLoop->contains(OldBB) &&
333 (!InnermostPredLoop ||
334 InnermostPredLoop->getLoopDepth() < PredLoop->getLoopDepth()))
335 InnermostPredLoop = PredLoop;
336 }
Bill Wendlingec3823d2011-08-18 20:39:32 +0000337 }
Bill Wendling0a693f42011-08-18 05:25:23 +0000338
339 if (InnermostPredLoop)
Chandler Carruth691addc2015-01-18 01:25:51 +0000340 InnermostPredLoop->addBasicBlockToLoop(NewBB, *LI);
Bill Wendling0a693f42011-08-18 05:25:23 +0000341 } else {
Chandler Carruth691addc2015-01-18 01:25:51 +0000342 L->addBasicBlockToLoop(NewBB, *LI);
Bill Wendling0a693f42011-08-18 05:25:23 +0000343 if (SplitMakesNewLoopHeader)
344 L->moveToHeader(NewBB);
345 }
346}
347
Sanjay Patel85ce0f12016-04-23 16:31:48 +0000348/// Update the PHI nodes in OrigBB to include the values coming from NewBB.
349/// This also updates AliasAnalysis, if available.
Bill Wendlingb267e2a2011-08-18 20:51:04 +0000350static void UpdatePHINodes(BasicBlock *OrigBB, BasicBlock *NewBB,
Chandler Carruthb5797b62015-01-18 09:21:15 +0000351 ArrayRef<BasicBlock *> Preds, BranchInst *BI,
Chandler Carruth96ada252015-07-22 09:52:54 +0000352 bool HasLoopExit) {
Bill Wendlingb267e2a2011-08-18 20:51:04 +0000353 // Otherwise, create a new PHI node in NewBB for each PHI node in OrigBB.
Chandler Carruth5bdf72c2014-04-28 10:37:30 +0000354 SmallPtrSet<BasicBlock *, 16> PredSet(Preds.begin(), Preds.end());
Bill Wendlingb267e2a2011-08-18 20:51:04 +0000355 for (BasicBlock::iterator I = OrigBB->begin(); isa<PHINode>(I); ) {
356 PHINode *PN = cast<PHINode>(I++);
357
358 // Check to see if all of the values coming in are the same. If so, we
359 // don't need to create a new PHI node, unless it's needed for LCSSA.
Craig Topperf40110f2014-04-25 05:29:35 +0000360 Value *InVal = nullptr;
Bill Wendlingb267e2a2011-08-18 20:51:04 +0000361 if (!HasLoopExit) {
362 InVal = PN->getIncomingValueForBlock(Preds[0]);
Chandler Carruth5bdf72c2014-04-28 10:37:30 +0000363 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) {
364 if (!PredSet.count(PN->getIncomingBlock(i)))
365 continue;
366 if (!InVal)
367 InVal = PN->getIncomingValue(i);
368 else if (InVal != PN->getIncomingValue(i)) {
Craig Topperf40110f2014-04-25 05:29:35 +0000369 InVal = nullptr;
Bill Wendlingb267e2a2011-08-18 20:51:04 +0000370 break;
371 }
Chandler Carruth5bdf72c2014-04-28 10:37:30 +0000372 }
Bill Wendlingb267e2a2011-08-18 20:51:04 +0000373 }
374
375 if (InVal) {
376 // If all incoming values for the new PHI would be the same, just don't
377 // make a new PHI. Instead, just remove the incoming values from the old
378 // PHI.
Jakub Staszak190db2f2013-01-14 23:16:36 +0000379
Chandler Carruth5bdf72c2014-04-28 10:37:30 +0000380 // NOTE! This loop walks backwards for a reason! First off, this minimizes
381 // the cost of removal if we end up removing a large number of values, and
382 // second off, this ensures that the indices for the incoming values
383 // aren't invalidated when we remove one.
384 for (int64_t i = PN->getNumIncomingValues() - 1; i >= 0; --i)
385 if (PredSet.count(PN->getIncomingBlock(i)))
386 PN->removeIncomingValue(i, false);
Bill Wendlingb267e2a2011-08-18 20:51:04 +0000387
Chandler Carruth5bdf72c2014-04-28 10:37:30 +0000388 // Add an incoming value to the PHI node in the loop for the preheader
389 // edge.
390 PN->addIncoming(InVal, NewBB);
391 continue;
Bill Wendlingb267e2a2011-08-18 20:51:04 +0000392 }
393
Chandler Carruth5bdf72c2014-04-28 10:37:30 +0000394 // If the values coming into the block are not the same, we need a new
395 // PHI.
396 // Create the new PHI node, insert it into NewBB at the end of the block
397 PHINode *NewPHI =
398 PHINode::Create(PN->getType(), Preds.size(), PN->getName() + ".ph", BI);
Chandler Carruth5bdf72c2014-04-28 10:37:30 +0000399
400 // NOTE! This loop walks backwards for a reason! First off, this minimizes
401 // the cost of removal if we end up removing a large number of values, and
402 // second off, this ensures that the indices for the incoming values aren't
403 // invalidated when we remove one.
404 for (int64_t i = PN->getNumIncomingValues() - 1; i >= 0; --i) {
405 BasicBlock *IncomingBB = PN->getIncomingBlock(i);
406 if (PredSet.count(IncomingBB)) {
407 Value *V = PN->removeIncomingValue(i, false);
408 NewPHI->addIncoming(V, IncomingBB);
409 }
410 }
411
412 PN->addIncoming(NewPHI, NewBB);
Bill Wendlingb267e2a2011-08-18 20:51:04 +0000413 }
414}
415
Jakub Staszak190db2f2013-01-14 23:16:36 +0000416BasicBlock *llvm::SplitBlockPredecessors(BasicBlock *BB,
Chandler Carruthb5797b62015-01-18 09:21:15 +0000417 ArrayRef<BasicBlock *> Preds,
Chandler Carruth96ada252015-07-22 09:52:54 +0000418 const char *Suffix, DominatorTree *DT,
419 LoopInfo *LI, bool PreserveLCSSA) {
David Majnemer654e1302015-07-31 17:58:14 +0000420 // Do not attempt to split that which cannot be split.
421 if (!BB->canSplitPredecessors())
422 return nullptr;
423
Philip Reames9198b332015-01-28 23:06:47 +0000424 // For the landingpads we need to act a bit differently.
425 // Delegate this work to the SplitLandingPadPredecessors.
426 if (BB->isLandingPad()) {
427 SmallVector<BasicBlock*, 2> NewBBs;
428 std::string NewName = std::string(Suffix) + ".split-lp";
429
Chandler Carruth96ada252015-07-22 09:52:54 +0000430 SplitLandingPadPredecessors(BB, Preds, Suffix, NewName.c_str(), NewBBs, DT,
431 LI, PreserveLCSSA);
Philip Reames9198b332015-01-28 23:06:47 +0000432 return NewBBs[0];
433 }
434
Chris Lattnera5b11702008-04-21 01:28:02 +0000435 // Create new basic block, insert right before the original block.
Alexey Samsonovb7f02d32015-06-09 22:10:29 +0000436 BasicBlock *NewBB = BasicBlock::Create(
437 BB->getContext(), BB->getName() + Suffix, BB->getParent(), BB);
Jakub Staszak190db2f2013-01-14 23:16:36 +0000438
Chris Lattnera5b11702008-04-21 01:28:02 +0000439 // The new block unconditionally branches to the old block.
440 BranchInst *BI = BranchInst::Create(BB, NewBB);
Taewook Oh2e945eb2017-02-14 21:10:40 +0000441 BI->setDebugLoc(BB->getFirstNonPHIOrDbg()->getDebugLoc());
Jakub Staszak190db2f2013-01-14 23:16:36 +0000442
Chris Lattnera5b11702008-04-21 01:28:02 +0000443 // Move the edges from Preds to point to NewBB instead of BB.
Jakub Staszakf5b32e52011-12-09 21:19:53 +0000444 for (unsigned i = 0, e = Preds.size(); i != e; ++i) {
Dan Gohman00c79382009-11-05 18:25:44 +0000445 // This is slightly more strict than necessary; the minimum requirement
446 // is that there be no more than one indirectbr branching to BB. And
447 // all BlockAddress uses would need to be updated.
448 assert(!isa<IndirectBrInst>(Preds[i]->getTerminator()) &&
449 "Cannot split an edge from an IndirectBrInst");
Chris Lattnera5b11702008-04-21 01:28:02 +0000450 Preds[i]->getTerminator()->replaceUsesOfWith(BB, NewBB);
Dan Gohman3ddbc242009-09-08 15:45:00 +0000451 }
452
Chris Lattnera5b11702008-04-21 01:28:02 +0000453 // Insert a new PHI node into NewBB for every PHI node in BB and that new PHI
454 // node becomes an incoming value for BB's phi node. However, if the Preds
455 // list is empty, we need to insert dummy entries into the PHI nodes in BB to
456 // account for the newly created predecessor.
Jakub Staszakf5b32e52011-12-09 21:19:53 +0000457 if (Preds.size() == 0) {
Chris Lattnera5b11702008-04-21 01:28:02 +0000458 // Insert dummy values as the incoming value.
459 for (BasicBlock::iterator I = BB->begin(); isa<PHINode>(I); ++I)
Owen Andersonb292b8c2009-07-30 23:03:37 +0000460 cast<PHINode>(I)->addIncoming(UndefValue::get(I->getType()), NewBB);
Chris Lattnera5b11702008-04-21 01:28:02 +0000461 return NewBB;
462 }
Dan Gohman3ddbc242009-09-08 15:45:00 +0000463
Bill Wendling0a693f42011-08-18 05:25:23 +0000464 // Update DominatorTree, LoopInfo, and LCCSA analysis information.
465 bool HasLoopExit = false;
Chandler Carruthb5797b62015-01-18 09:21:15 +0000466 UpdateAnalysisInformation(BB, NewBB, Preds, DT, LI, PreserveLCSSA,
467 HasLoopExit);
Dan Gohman3ddbc242009-09-08 15:45:00 +0000468
Bill Wendlingb267e2a2011-08-18 20:51:04 +0000469 // Update the PHI nodes in BB with the values coming from NewBB.
Chandler Carruth96ada252015-07-22 09:52:54 +0000470 UpdatePHINodes(BB, NewBB, Preds, BI, HasLoopExit);
Chris Lattnera5b11702008-04-21 01:28:02 +0000471 return NewBB;
472}
Chris Lattner72f16e72008-11-27 08:10:05 +0000473
Bill Wendlingca7d3092011-08-19 00:05:40 +0000474void llvm::SplitLandingPadPredecessors(BasicBlock *OrigBB,
Chandler Carruth0eae1122015-01-19 03:03:39 +0000475 ArrayRef<BasicBlock *> Preds,
Bill Wendlingca7d3092011-08-19 00:05:40 +0000476 const char *Suffix1, const char *Suffix2,
Chandler Carruth0eae1122015-01-19 03:03:39 +0000477 SmallVectorImpl<BasicBlock *> &NewBBs,
Chandler Carruth96ada252015-07-22 09:52:54 +0000478 DominatorTree *DT, LoopInfo *LI,
479 bool PreserveLCSSA) {
Bill Wendlingca7d3092011-08-19 00:05:40 +0000480 assert(OrigBB->isLandingPad() && "Trying to split a non-landing pad!");
481
482 // Create a new basic block for OrigBB's predecessors listed in Preds. Insert
483 // it right before the original block.
484 BasicBlock *NewBB1 = BasicBlock::Create(OrigBB->getContext(),
485 OrigBB->getName() + Suffix1,
486 OrigBB->getParent(), OrigBB);
487 NewBBs.push_back(NewBB1);
488
489 // The new block unconditionally branches to the old block.
490 BranchInst *BI1 = BranchInst::Create(OrigBB, NewBB1);
Alexey Samsonovb7f02d32015-06-09 22:10:29 +0000491 BI1->setDebugLoc(OrigBB->getFirstNonPHI()->getDebugLoc());
Bill Wendlingca7d3092011-08-19 00:05:40 +0000492
493 // Move the edges from Preds to point to NewBB1 instead of OrigBB.
494 for (unsigned i = 0, e = Preds.size(); i != e; ++i) {
495 // This is slightly more strict than necessary; the minimum requirement
496 // is that there be no more than one indirectbr branching to BB. And
497 // all BlockAddress uses would need to be updated.
498 assert(!isa<IndirectBrInst>(Preds[i]->getTerminator()) &&
499 "Cannot split an edge from an IndirectBrInst");
500 Preds[i]->getTerminator()->replaceUsesOfWith(OrigBB, NewBB1);
501 }
502
Bill Wendlingca7d3092011-08-19 00:05:40 +0000503 bool HasLoopExit = false;
Chandler Carruthb5797b62015-01-18 09:21:15 +0000504 UpdateAnalysisInformation(OrigBB, NewBB1, Preds, DT, LI, PreserveLCSSA,
505 HasLoopExit);
Bill Wendlingca7d3092011-08-19 00:05:40 +0000506
507 // Update the PHI nodes in OrigBB with the values coming from NewBB1.
Chandler Carruth96ada252015-07-22 09:52:54 +0000508 UpdatePHINodes(OrigBB, NewBB1, Preds, BI1, HasLoopExit);
Bill Wendlingca7d3092011-08-19 00:05:40 +0000509
Bill Wendlingca7d3092011-08-19 00:05:40 +0000510 // Move the remaining edges from OrigBB to point to NewBB2.
511 SmallVector<BasicBlock*, 8> NewBB2Preds;
Duncan P. N. Exon Smith6c990152014-07-21 17:06:51 +0000512 for (pred_iterator i = pred_begin(OrigBB), e = pred_end(OrigBB);
513 i != e; ) {
514 BasicBlock *Pred = *i++;
Bill Wendling38d81302011-08-19 23:46:30 +0000515 if (Pred == NewBB1) continue;
Bill Wendlingca7d3092011-08-19 00:05:40 +0000516 assert(!isa<IndirectBrInst>(Pred->getTerminator()) &&
517 "Cannot split an edge from an IndirectBrInst");
Bill Wendlingca7d3092011-08-19 00:05:40 +0000518 NewBB2Preds.push_back(Pred);
Duncan P. N. Exon Smith6c990152014-07-21 17:06:51 +0000519 e = pred_end(OrigBB);
Bill Wendlingca7d3092011-08-19 00:05:40 +0000520 }
521
Craig Topperf40110f2014-04-25 05:29:35 +0000522 BasicBlock *NewBB2 = nullptr;
Bill Wendling38d81302011-08-19 23:46:30 +0000523 if (!NewBB2Preds.empty()) {
524 // Create another basic block for the rest of OrigBB's predecessors.
525 NewBB2 = BasicBlock::Create(OrigBB->getContext(),
526 OrigBB->getName() + Suffix2,
527 OrigBB->getParent(), OrigBB);
528 NewBBs.push_back(NewBB2);
Bill Wendlingca7d3092011-08-19 00:05:40 +0000529
Bill Wendling38d81302011-08-19 23:46:30 +0000530 // The new block unconditionally branches to the old block.
531 BranchInst *BI2 = BranchInst::Create(OrigBB, NewBB2);
Alexey Samsonovb7f02d32015-06-09 22:10:29 +0000532 BI2->setDebugLoc(OrigBB->getFirstNonPHI()->getDebugLoc());
Bill Wendling38d81302011-08-19 23:46:30 +0000533
534 // Move the remaining edges from OrigBB to point to NewBB2.
Benjamin Kramer135f7352016-06-26 12:28:59 +0000535 for (BasicBlock *NewBB2Pred : NewBB2Preds)
536 NewBB2Pred->getTerminator()->replaceUsesOfWith(OrigBB, NewBB2);
Bill Wendling38d81302011-08-19 23:46:30 +0000537
538 // Update DominatorTree, LoopInfo, and LCCSA analysis information.
539 HasLoopExit = false;
Chandler Carruthb5797b62015-01-18 09:21:15 +0000540 UpdateAnalysisInformation(OrigBB, NewBB2, NewBB2Preds, DT, LI,
541 PreserveLCSSA, HasLoopExit);
Bill Wendling38d81302011-08-19 23:46:30 +0000542
543 // Update the PHI nodes in OrigBB with the values coming from NewBB2.
Chandler Carruth96ada252015-07-22 09:52:54 +0000544 UpdatePHINodes(OrigBB, NewBB2, NewBB2Preds, BI2, HasLoopExit);
Bill Wendling38d81302011-08-19 23:46:30 +0000545 }
Bill Wendlingca7d3092011-08-19 00:05:40 +0000546
547 LandingPadInst *LPad = OrigBB->getLandingPadInst();
548 Instruction *Clone1 = LPad->clone();
549 Clone1->setName(Twine("lpad") + Suffix1);
550 NewBB1->getInstList().insert(NewBB1->getFirstInsertionPt(), Clone1);
551
Bill Wendling38d81302011-08-19 23:46:30 +0000552 if (NewBB2) {
553 Instruction *Clone2 = LPad->clone();
554 Clone2->setName(Twine("lpad") + Suffix2);
555 NewBB2->getInstList().insert(NewBB2->getFirstInsertionPt(), Clone2);
Bill Wendlingca7d3092011-08-19 00:05:40 +0000556
Chen Li78bde832016-01-06 20:32:05 +0000557 // Create a PHI node for the two cloned landingpad instructions only
558 // if the original landingpad instruction has some uses.
559 if (!LPad->use_empty()) {
560 assert(!LPad->getType()->isTokenTy() &&
561 "Split cannot be applied if LPad is token type. Otherwise an "
562 "invalid PHINode of token type would be created.");
563 PHINode *PN = PHINode::Create(LPad->getType(), 2, "lpad.phi", LPad);
564 PN->addIncoming(Clone1, NewBB1);
565 PN->addIncoming(Clone2, NewBB2);
566 LPad->replaceAllUsesWith(PN);
567 }
Bill Wendling38d81302011-08-19 23:46:30 +0000568 LPad->eraseFromParent();
569 } else {
570 // There is no second clone. Just replace the landing pad with the first
571 // clone.
572 LPad->replaceAllUsesWith(Clone1);
573 LPad->eraseFromParent();
574 }
Bill Wendlingca7d3092011-08-19 00:05:40 +0000575}
576
Evan Chengd983eba2011-01-29 04:46:23 +0000577ReturnInst *llvm::FoldReturnIntoUncondBranch(ReturnInst *RI, BasicBlock *BB,
578 BasicBlock *Pred) {
579 Instruction *UncondBranch = Pred->getTerminator();
580 // Clone the return and add it to the end of the predecessor.
581 Instruction *NewRet = RI->clone();
582 Pred->getInstList().push_back(NewRet);
Jakub Staszak190db2f2013-01-14 23:16:36 +0000583
Evan Chengd983eba2011-01-29 04:46:23 +0000584 // If the return instruction returns a value, and if the value was a
585 // PHI node in "BB", propagate the right value into the return.
586 for (User::op_iterator i = NewRet->op_begin(), e = NewRet->op_end();
Evan Cheng249716e2012-07-27 21:21:26 +0000587 i != e; ++i) {
588 Value *V = *i;
Craig Topperf40110f2014-04-25 05:29:35 +0000589 Instruction *NewBC = nullptr;
Evan Cheng249716e2012-07-27 21:21:26 +0000590 if (BitCastInst *BCI = dyn_cast<BitCastInst>(V)) {
591 // Return value might be bitcasted. Clone and insert it before the
592 // return instruction.
593 V = BCI->getOperand(0);
594 NewBC = BCI->clone();
Duncan P. N. Exon Smith5b4c8372015-10-13 02:39:05 +0000595 Pred->getInstList().insert(NewRet->getIterator(), NewBC);
Evan Cheng249716e2012-07-27 21:21:26 +0000596 *i = NewBC;
597 }
598 if (PHINode *PN = dyn_cast<PHINode>(V)) {
599 if (PN->getParent() == BB) {
600 if (NewBC)
601 NewBC->setOperand(0, PN->getIncomingValueForBlock(Pred));
602 else
603 *i = PN->getIncomingValueForBlock(Pred);
604 }
605 }
606 }
Jakub Staszak190db2f2013-01-14 23:16:36 +0000607
Evan Chengd983eba2011-01-29 04:46:23 +0000608 // Update any PHI nodes in the returning block to realize that we no
609 // longer branch to them.
610 BB->removePredecessor(Pred);
611 UncondBranch->eraseFromParent();
612 return cast<ReturnInst>(NewRet);
Chris Lattner351134b2009-05-04 02:25:58 +0000613}
Devang Patela8e74112011-04-29 22:28:59 +0000614
Adam Nemetfdb20592016-03-15 18:06:20 +0000615TerminatorInst *
616llvm::SplitBlockAndInsertIfThen(Value *Cond, Instruction *SplitBefore,
617 bool Unreachable, MDNode *BranchWeights,
618 DominatorTree *DT, LoopInfo *LI) {
Evgeniy Stepanov8eb77d82012-10-19 10:48:31 +0000619 BasicBlock *Head = SplitBefore->getParent();
Duncan P. N. Exon Smith5b4c8372015-10-13 02:39:05 +0000620 BasicBlock *Tail = Head->splitBasicBlock(SplitBefore->getIterator());
Evgeniy Stepanov8eb77d82012-10-19 10:48:31 +0000621 TerminatorInst *HeadOldTerm = Head->getTerminator();
622 LLVMContext &C = Head->getContext();
623 BasicBlock *ThenBlock = BasicBlock::Create(C, "", Head->getParent(), Tail);
624 TerminatorInst *CheckTerm;
625 if (Unreachable)
626 CheckTerm = new UnreachableInst(C, ThenBlock);
627 else
628 CheckTerm = BranchInst::Create(Tail, ThenBlock);
Evgeniy Stepanov2275a012014-03-19 12:56:38 +0000629 CheckTerm->setDebugLoc(SplitBefore->getDebugLoc());
Evgeniy Stepanov8eb77d82012-10-19 10:48:31 +0000630 BranchInst *HeadNewTerm =
Evgeniy Stepanova9164e92013-12-19 13:29:56 +0000631 BranchInst::Create(/*ifTrue*/ThenBlock, /*ifFalse*/Tail, Cond);
Evgeniy Stepanov8eb77d82012-10-19 10:48:31 +0000632 HeadNewTerm->setMetadata(LLVMContext::MD_prof, BranchWeights);
633 ReplaceInstWithInst(HeadOldTerm, HeadNewTerm);
Peter Collingbourne818f5c42014-07-15 04:40:27 +0000634
635 if (DT) {
636 if (DomTreeNode *OldNode = DT->getNode(Head)) {
637 std::vector<DomTreeNode *> Children(OldNode->begin(), OldNode->end());
638
639 DomTreeNode *NewNode = DT->addNewBlock(Tail, Head);
Benjamin Kramer135f7352016-06-26 12:28:59 +0000640 for (DomTreeNode *Child : Children)
Peter Collingbourne818f5c42014-07-15 04:40:27 +0000641 DT->changeImmediateDominator(Child, NewNode);
642
643 // Head dominates ThenBlock.
644 DT->addNewBlock(ThenBlock, Head);
645 }
646 }
647
Adam Nemetfdb20592016-03-15 18:06:20 +0000648 if (LI) {
649 Loop *L = LI->getLoopFor(Head);
650 L->addBasicBlockToLoop(ThenBlock, *LI);
651 L->addBasicBlockToLoop(Tail, *LI);
652 }
653
Evgeniy Stepanov8eb77d82012-10-19 10:48:31 +0000654 return CheckTerm;
655}
Tom Stellardaa664d92013-08-06 02:43:45 +0000656
Kostya Serebryany530e2072013-12-23 14:15:08 +0000657void llvm::SplitBlockAndInsertIfThenElse(Value *Cond, Instruction *SplitBefore,
658 TerminatorInst **ThenTerm,
659 TerminatorInst **ElseTerm,
660 MDNode *BranchWeights) {
661 BasicBlock *Head = SplitBefore->getParent();
Duncan P. N. Exon Smith5b4c8372015-10-13 02:39:05 +0000662 BasicBlock *Tail = Head->splitBasicBlock(SplitBefore->getIterator());
Kostya Serebryany530e2072013-12-23 14:15:08 +0000663 TerminatorInst *HeadOldTerm = Head->getTerminator();
664 LLVMContext &C = Head->getContext();
665 BasicBlock *ThenBlock = BasicBlock::Create(C, "", Head->getParent(), Tail);
666 BasicBlock *ElseBlock = BasicBlock::Create(C, "", Head->getParent(), Tail);
667 *ThenTerm = BranchInst::Create(Tail, ThenBlock);
Evgeniy Stepanov2275a012014-03-19 12:56:38 +0000668 (*ThenTerm)->setDebugLoc(SplitBefore->getDebugLoc());
Kostya Serebryany530e2072013-12-23 14:15:08 +0000669 *ElseTerm = BranchInst::Create(Tail, ElseBlock);
Evgeniy Stepanov2275a012014-03-19 12:56:38 +0000670 (*ElseTerm)->setDebugLoc(SplitBefore->getDebugLoc());
Kostya Serebryany530e2072013-12-23 14:15:08 +0000671 BranchInst *HeadNewTerm =
672 BranchInst::Create(/*ifTrue*/ThenBlock, /*ifFalse*/ElseBlock, Cond);
673 HeadNewTerm->setMetadata(LLVMContext::MD_prof, BranchWeights);
674 ReplaceInstWithInst(HeadOldTerm, HeadNewTerm);
675}
676
677
Tom Stellardaa664d92013-08-06 02:43:45 +0000678Value *llvm::GetIfCondition(BasicBlock *BB, BasicBlock *&IfTrue,
679 BasicBlock *&IfFalse) {
680 PHINode *SomePHI = dyn_cast<PHINode>(BB->begin());
Craig Topperf40110f2014-04-25 05:29:35 +0000681 BasicBlock *Pred1 = nullptr;
682 BasicBlock *Pred2 = nullptr;
Tom Stellardaa664d92013-08-06 02:43:45 +0000683
684 if (SomePHI) {
685 if (SomePHI->getNumIncomingValues() != 2)
Craig Topperf40110f2014-04-25 05:29:35 +0000686 return nullptr;
Tom Stellardaa664d92013-08-06 02:43:45 +0000687 Pred1 = SomePHI->getIncomingBlock(0);
688 Pred2 = SomePHI->getIncomingBlock(1);
689 } else {
690 pred_iterator PI = pred_begin(BB), PE = pred_end(BB);
691 if (PI == PE) // No predecessor
Craig Topperf40110f2014-04-25 05:29:35 +0000692 return nullptr;
Tom Stellardaa664d92013-08-06 02:43:45 +0000693 Pred1 = *PI++;
694 if (PI == PE) // Only one predecessor
Craig Topperf40110f2014-04-25 05:29:35 +0000695 return nullptr;
Tom Stellardaa664d92013-08-06 02:43:45 +0000696 Pred2 = *PI++;
697 if (PI != PE) // More than two predecessors
Craig Topperf40110f2014-04-25 05:29:35 +0000698 return nullptr;
Tom Stellardaa664d92013-08-06 02:43:45 +0000699 }
700
701 // We can only handle branches. Other control flow will be lowered to
702 // branches if possible anyway.
703 BranchInst *Pred1Br = dyn_cast<BranchInst>(Pred1->getTerminator());
704 BranchInst *Pred2Br = dyn_cast<BranchInst>(Pred2->getTerminator());
Craig Topperf40110f2014-04-25 05:29:35 +0000705 if (!Pred1Br || !Pred2Br)
706 return nullptr;
Tom Stellardaa664d92013-08-06 02:43:45 +0000707
708 // Eliminate code duplication by ensuring that Pred1Br is conditional if
709 // either are.
710 if (Pred2Br->isConditional()) {
711 // If both branches are conditional, we don't have an "if statement". In
712 // reality, we could transform this case, but since the condition will be
713 // required anyway, we stand no chance of eliminating it, so the xform is
714 // probably not profitable.
715 if (Pred1Br->isConditional())
Craig Topperf40110f2014-04-25 05:29:35 +0000716 return nullptr;
Tom Stellardaa664d92013-08-06 02:43:45 +0000717
718 std::swap(Pred1, Pred2);
719 std::swap(Pred1Br, Pred2Br);
720 }
721
722 if (Pred1Br->isConditional()) {
723 // The only thing we have to watch out for here is to make sure that Pred2
724 // doesn't have incoming edges from other blocks. If it does, the condition
725 // doesn't dominate BB.
Craig Topperf40110f2014-04-25 05:29:35 +0000726 if (!Pred2->getSinglePredecessor())
727 return nullptr;
Tom Stellardaa664d92013-08-06 02:43:45 +0000728
729 // If we found a conditional branch predecessor, make sure that it branches
730 // to BB and Pred2Br. If it doesn't, this isn't an "if statement".
731 if (Pred1Br->getSuccessor(0) == BB &&
732 Pred1Br->getSuccessor(1) == Pred2) {
733 IfTrue = Pred1;
734 IfFalse = Pred2;
735 } else if (Pred1Br->getSuccessor(0) == Pred2 &&
736 Pred1Br->getSuccessor(1) == BB) {
737 IfTrue = Pred2;
738 IfFalse = Pred1;
739 } else {
740 // We know that one arm of the conditional goes to BB, so the other must
741 // go somewhere unrelated, and this must not be an "if statement".
Craig Topperf40110f2014-04-25 05:29:35 +0000742 return nullptr;
Tom Stellardaa664d92013-08-06 02:43:45 +0000743 }
744
745 return Pred1Br->getCondition();
746 }
747
748 // Ok, if we got here, both predecessors end with an unconditional branch to
749 // BB. Don't panic! If both blocks only have a single (identical)
750 // predecessor, and THAT is a conditional branch, then we're all ok!
751 BasicBlock *CommonPred = Pred1->getSinglePredecessor();
Craig Topperf40110f2014-04-25 05:29:35 +0000752 if (CommonPred == nullptr || CommonPred != Pred2->getSinglePredecessor())
753 return nullptr;
Tom Stellardaa664d92013-08-06 02:43:45 +0000754
755 // Otherwise, if this is a conditional branch, then we can use it!
756 BranchInst *BI = dyn_cast<BranchInst>(CommonPred->getTerminator());
Craig Topperf40110f2014-04-25 05:29:35 +0000757 if (!BI) return nullptr;
Tom Stellardaa664d92013-08-06 02:43:45 +0000758
759 assert(BI->isConditional() && "Two successors but not conditional?");
760 if (BI->getSuccessor(0) == Pred1) {
761 IfTrue = Pred1;
762 IfFalse = Pred2;
763 } else {
764 IfTrue = Pred2;
765 IfFalse = Pred1;
766 }
767 return BI->getCondition();
768}