blob: 516a785dce1e6b82ac7a90cca3e556ebd34755a2 [file] [log] [blame]
Eugene Zelenko57bd5a02017-10-27 01:09:08 +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"
Eugene Zelenko57bd5a02017-10-27 01:09:08 +000016#include "llvm/ADT/ArrayRef.h"
17#include "llvm/ADT/SmallPtrSet.h"
18#include "llvm/ADT/SmallVector.h"
19#include "llvm/ADT/Twine.h"
Nick Lewycky0b682452013-07-27 01:24:00 +000020#include "llvm/Analysis/CFG.h"
Chris Lattnerf6ae9042011-01-11 08:13:40 +000021#include "llvm/Analysis/LoopInfo.h"
22#include "llvm/Analysis/MemoryDependenceAnalysis.h"
David Blaikie31b98d22018-06-04 21:23:21 +000023#include "llvm/Transforms/Utils/Local.h"
Eugene Zelenko57bd5a02017-10-27 01:09:08 +000024#include "llvm/IR/BasicBlock.h"
25#include "llvm/IR/CFG.h"
26#include "llvm/IR/Constants.h"
Adrian Prantld60f34c2017-11-01 20:43:30 +000027#include "llvm/IR/DebugInfoMetadata.h"
Chandler Carruth5ad5f152014-01-13 09:26:24 +000028#include "llvm/IR/Dominators.h"
Chandler Carruth9fb823b2013-01-02 11:36:10 +000029#include "llvm/IR/Function.h"
Eugene Zelenko57bd5a02017-10-27 01:09:08 +000030#include "llvm/IR/InstrTypes.h"
31#include "llvm/IR/Instruction.h"
Chandler Carruth9fb823b2013-01-02 11:36:10 +000032#include "llvm/IR/Instructions.h"
Adrian Prantld60f34c2017-11-01 20:43:30 +000033#include "llvm/IR/IntrinsicInst.h"
Eugene Zelenko57bd5a02017-10-27 01:09:08 +000034#include "llvm/IR/LLVMContext.h"
Chandler Carruth9fb823b2013-01-02 11:36:10 +000035#include "llvm/IR/Type.h"
Eugene Zelenko57bd5a02017-10-27 01:09:08 +000036#include "llvm/IR/User.h"
37#include "llvm/IR/Value.h"
Chandler Carruth4220e9c2014-03-04 11:17:44 +000038#include "llvm/IR/ValueHandle.h"
Eugene Zelenko57bd5a02017-10-27 01:09:08 +000039#include "llvm/Support/Casting.h"
Eugene Zelenko57bd5a02017-10-27 01:09:08 +000040#include <cassert>
41#include <cstdint>
42#include <string>
43#include <utility>
44#include <vector>
45
Chris Lattnerdf3c3422004-01-09 06:12:26 +000046using namespace llvm;
Brian Gaeke960707c2003-11-11 22:41:34 +000047
Brian M. Rzycki9b7ae232018-01-12 21:06:48 +000048void llvm::DeleteDeadBlock(BasicBlock *BB, DeferredDominance *DDT) {
Chris Lattner37e01362008-12-03 07:45:15 +000049 assert((pred_begin(BB) == pred_end(BB) ||
50 // Can delete self loop.
51 BB->getSinglePredecessor() == BB) && "Block is not dead!");
Chris Lattnerbcc904a2008-12-03 06:37:44 +000052 TerminatorInst *BBTerm = BB->getTerminator();
Brian M. Rzycki9b7ae232018-01-12 21:06:48 +000053 std::vector<DominatorTree::UpdateType> Updates;
Jakub Staszak190db2f2013-01-14 23:16:36 +000054
Chris Lattnerbcc904a2008-12-03 06:37:44 +000055 // Loop through all of our successors and make sure they know that one
56 // of their predecessors is going away.
Brian M. Rzycki9b7ae232018-01-12 21:06:48 +000057 if (DDT)
58 Updates.reserve(BBTerm->getNumSuccessors());
59 for (BasicBlock *Succ : BBTerm->successors()) {
Pete Cooperebcd7482015-08-06 20:22:46 +000060 Succ->removePredecessor(BB);
Brian M. Rzycki9b7ae232018-01-12 21:06:48 +000061 if (DDT)
62 Updates.push_back({DominatorTree::Delete, BB, Succ});
63 }
Jakub Staszak190db2f2013-01-14 23:16:36 +000064
Chris Lattnerbcc904a2008-12-03 06:37:44 +000065 // Zap all the instructions in the block.
66 while (!BB->empty()) {
67 Instruction &I = BB->back();
68 // If this instruction is used, replace uses with an arbitrary value.
69 // Because control flow can't get here, we don't care what we replace the
70 // value with. Note that since this block is unreachable, and all values
71 // contained within it must dominate their uses, that all uses will
72 // eventually be removed (they are themselves dead).
73 if (!I.use_empty())
Owen Andersonb292b8c2009-07-30 23:03:37 +000074 I.replaceAllUsesWith(UndefValue::get(I.getType()));
Chris Lattnerbcc904a2008-12-03 06:37:44 +000075 BB->getInstList().pop_back();
76 }
Jakub Staszak190db2f2013-01-14 23:16:36 +000077
Brian M. Rzycki9b7ae232018-01-12 21:06:48 +000078 if (DDT) {
79 DDT->applyUpdates(Updates);
80 DDT->deleteBB(BB); // Deferred deletion of BB.
81 } else {
82 BB->eraseFromParent(); // Zap the block!
83 }
Chris Lattnerbcc904a2008-12-03 06:37:44 +000084}
85
Chandler Carruth96ada252015-07-22 09:52:54 +000086void llvm::FoldSingleEntryPHINodes(BasicBlock *BB,
Chandler Carruth61440d22016-03-10 00:55:30 +000087 MemoryDependenceResults *MemDep) {
Chris Lattnerf6ae9042011-01-11 08:13:40 +000088 if (!isa<PHINode>(BB->begin())) return;
Jakub Staszak190db2f2013-01-14 23:16:36 +000089
Chris Lattnerdc3f6f22008-12-03 19:44:02 +000090 while (PHINode *PN = dyn_cast<PHINode>(BB->begin())) {
91 if (PN->getIncomingValue(0) != PN)
92 PN->replaceAllUsesWith(PN->getIncomingValue(0));
93 else
Owen Andersonb292b8c2009-07-30 23:03:37 +000094 PN->replaceAllUsesWith(UndefValue::get(PN->getType()));
Jakub Staszak190db2f2013-01-14 23:16:36 +000095
Chris Lattnerf6ae9042011-01-11 08:13:40 +000096 if (MemDep)
97 MemDep->removeInstruction(PN); // Memdep updates AA itself.
Jakub Staszak190db2f2013-01-14 23:16:36 +000098
Chris Lattnerdc3f6f22008-12-03 19:44:02 +000099 PN->eraseFromParent();
100 }
101}
102
Benjamin Kramer8bcc9712012-08-29 15:32:21 +0000103bool llvm::DeleteDeadPHIs(BasicBlock *BB, const TargetLibraryInfo *TLI) {
Dan Gohmanff089952009-05-02 18:29:22 +0000104 // Recursively deleting a PHI may cause multiple PHIs to be deleted
Sanjoy Dase6bca0e2017-05-01 17:07:49 +0000105 // or RAUW'd undef, so use an array of WeakTrackingVH for the PHIs to delete.
106 SmallVector<WeakTrackingVH, 8> PHIs;
Benjamin Kramerc7fc81e2017-12-30 15:27:33 +0000107 for (PHINode &PN : BB->phis())
108 PHIs.push_back(&PN);
Dan Gohmanff089952009-05-02 18:29:22 +0000109
Dan Gohmancb99fe92010-01-05 15:45:31 +0000110 bool Changed = false;
Dan Gohmanff089952009-05-02 18:29:22 +0000111 for (unsigned i = 0, e = PHIs.size(); i != e; ++i)
112 if (PHINode *PN = dyn_cast_or_null<PHINode>(PHIs[i].operator Value*()))
Benjamin Kramer8bcc9712012-08-29 15:32:21 +0000113 Changed |= RecursivelyDeleteDeadPHINode(PN, TLI);
Dan Gohmancb99fe92010-01-05 15:45:31 +0000114
115 return Changed;
Dan Gohmanff089952009-05-02 18:29:22 +0000116}
117
Chandler Carruthb5c11532015-01-18 02:11:23 +0000118bool llvm::MergeBlockIntoPredecessor(BasicBlock *BB, DominatorTree *DT,
Chandler Carruth96ada252015-07-22 09:52:54 +0000119 LoopInfo *LI,
Alina Sbirleadfd14ad2018-06-20 22:01:04 +0000120 MemoryDependenceResults *MemDep,
121 DeferredDominance *DDT) {
122 assert(!(DT && DDT) && "Cannot call with both DT and DDT.");
123
124 if (BB->hasAddressTaken())
125 return false;
Jakub Staszak190db2f2013-01-14 23:16:36 +0000126
Dan Gohman941020e2010-08-17 17:07:02 +0000127 // Can't merge if there are multiple predecessors, or no predecessors.
128 BasicBlock *PredBB = BB->getUniquePredecessor();
Dan Gohman2d02ff82009-10-31 17:33:01 +0000129 if (!PredBB) return false;
Dan Gohman941020e2010-08-17 17:07:02 +0000130
Dan Gohman2d02ff82009-10-31 17:33:01 +0000131 // Don't break self-loops.
132 if (PredBB == BB) return false;
David Majnemer654e1302015-07-31 17:58:14 +0000133 // Don't break unwinding instructions.
134 if (PredBB->getTerminator()->isExceptional())
135 return false;
Jakub Staszak190db2f2013-01-14 23:16:36 +0000136
Alina Sbirleadfd14ad2018-06-20 22:01:04 +0000137 // Can't merge if there are multiple distinct successors.
138 if (PredBB->getUniqueSuccessor() != BB)
139 return false;
Devang Patel0f7a3502008-09-09 01:06:56 +0000140
Dan Gohman2d02ff82009-10-31 17:33:01 +0000141 // Can't merge if there is PHI loop.
Benjamin Kramerc7fc81e2017-12-30 15:27:33 +0000142 for (PHINode &PN : BB->phis())
143 for (Value *IncValue : PN.incoming_values())
144 if (IncValue == &PN)
145 return false;
Dan Gohman2d02ff82009-10-31 17:33:01 +0000146
147 // Begin by getting rid of unneeded PHIs.
Davide Italiano48283ba2018-05-08 23:28:15 +0000148 SmallVector<AssertingVH<Value>, 4> IncomingValues;
Adrian Prantld60f34c2017-11-01 20:43:30 +0000149 if (isa<PHINode>(BB->front())) {
Benjamin Kramerc7fc81e2017-12-30 15:27:33 +0000150 for (PHINode &PN : BB->phis())
Davide Italiano48283ba2018-05-08 23:28:15 +0000151 if (!isa<PHINode>(PN.getIncomingValue(0)) ||
152 cast<PHINode>(PN.getIncomingValue(0))->getParent() != BB)
Benjamin Kramerc7fc81e2017-12-30 15:27:33 +0000153 IncomingValues.push_back(PN.getIncomingValue(0));
Chandler Carruth96ada252015-07-22 09:52:54 +0000154 FoldSingleEntryPHINodes(BB, MemDep);
Adrian Prantld60f34c2017-11-01 20:43:30 +0000155 }
Jakub Staszak190db2f2013-01-14 23:16:36 +0000156
Alina Sbirleadfd14ad2018-06-20 22:01:04 +0000157 // Deferred DT update: Collect all the edges that exit BB. These
158 // dominator edges will be redirected from Pred.
159 std::vector<DominatorTree::UpdateType> Updates;
160 if (DDT) {
161 Updates.reserve(1 + (2 * succ_size(BB)));
162 Updates.push_back({DominatorTree::Delete, PredBB, BB});
163 for (auto I = succ_begin(BB), E = succ_end(BB); I != E; ++I) {
164 Updates.push_back({DominatorTree::Delete, BB, *I});
165 Updates.push_back({DominatorTree::Insert, PredBB, *I});
166 }
167 }
168
Owen Andersonc0623812008-07-17 00:01:40 +0000169 // Delete the unconditional branch from the predecessor...
170 PredBB->getInstList().pop_back();
Jakub Staszak190db2f2013-01-14 23:16:36 +0000171
Owen Andersonc0623812008-07-17 00:01:40 +0000172 // Make all PHI nodes that referred to BB now refer to Pred as their
173 // source...
174 BB->replaceAllUsesWith(PredBB);
Jakub Staszak190db2f2013-01-14 23:16:36 +0000175
Jay Foad61ea0e42011-06-23 09:09:15 +0000176 // Move all definitions in the successor to the predecessor...
177 PredBB->getInstList().splice(PredBB->end(), BB->getInstList());
Jakub Staszak190db2f2013-01-14 23:16:36 +0000178
Adrian Prantld60f34c2017-11-01 20:43:30 +0000179 // Eliminate duplicate dbg.values describing the entry PHI node post-splice.
Davide Italiano48283ba2018-05-08 23:28:15 +0000180 for (auto Incoming : IncomingValues) {
181 if (isa<Instruction>(*Incoming)) {
Adrian Prantld60f34c2017-11-01 20:43:30 +0000182 SmallVector<DbgValueInst *, 2> DbgValues;
183 SmallDenseSet<std::pair<DILocalVariable *, DIExpression *>, 2>
184 DbgValueSet;
185 llvm::findDbgValues(DbgValues, Incoming);
186 for (auto &DVI : DbgValues) {
187 auto R = DbgValueSet.insert({DVI->getVariable(), DVI->getExpression()});
188 if (!R.second)
189 DVI->eraseFromParent();
190 }
191 }
192 }
193
Dan Gohman2d02ff82009-10-31 17:33:01 +0000194 // Inherit predecessors name if it exists.
Owen Anderson27405ef2008-07-17 19:42:29 +0000195 if (!PredBB->hasName())
196 PredBB->takeName(BB);
Jakub Staszak190db2f2013-01-14 23:16:36 +0000197
Owen Andersonc0623812008-07-17 00:01:40 +0000198 // Finally, erase the old block and update dominator info.
Chandler Carruthb5c11532015-01-18 02:11:23 +0000199 if (DT)
200 if (DomTreeNode *DTN = DT->getNode(BB)) {
201 DomTreeNode *PredDTN = DT->getNode(PredBB);
202 SmallVector<DomTreeNode *, 8> Children(DTN->begin(), DTN->end());
Benjamin Kramer135f7352016-06-26 12:28:59 +0000203 for (DomTreeNode *DI : Children)
204 DT->changeImmediateDominator(DI, PredDTN);
Owen Andersonc0623812008-07-17 00:01:40 +0000205
Chandler Carruthb5c11532015-01-18 02:11:23 +0000206 DT->eraseNode(BB);
Owen Andersonc0623812008-07-17 00:01:40 +0000207 }
Chandler Carruthb5c11532015-01-18 02:11:23 +0000208
209 if (LI)
210 LI->removeBlock(BB);
211
212 if (MemDep)
213 MemDep->invalidateCachedPredecessors();
Jakub Staszak190db2f2013-01-14 23:16:36 +0000214
Alina Sbirleadfd14ad2018-06-20 22:01:04 +0000215 if (DDT) {
216 DDT->deleteBB(BB); // Deferred deletion of BB.
217 DDT->applyUpdates(Updates);
218 } else {
219 BB->eraseFromParent(); // Nuke BB.
220 }
Dan Gohman2d02ff82009-10-31 17:33:01 +0000221 return true;
Owen Andersonc0623812008-07-17 00:01:40 +0000222}
223
Chris Lattnerdf3c3422004-01-09 06:12:26 +0000224void llvm::ReplaceInstWithValue(BasicBlock::InstListType &BIL,
225 BasicBlock::iterator &BI, Value *V) {
Chris Lattnerfda72b12002-06-25 16:12:52 +0000226 Instruction &I = *BI;
Chris Lattner28537df2002-05-07 18:07:59 +0000227 // Replaces all of the uses of the instruction with uses of the value
Chris Lattnerfda72b12002-06-25 16:12:52 +0000228 I.replaceAllUsesWith(V);
Chris Lattner28537df2002-05-07 18:07:59 +0000229
Chris Lattner8dd4cae2007-02-11 01:37:51 +0000230 // Make sure to propagate a name if there is one already.
231 if (I.hasName() && !V->hasName())
232 V->takeName(&I);
Misha Brukmanb1c93172005-04-21 23:48:37 +0000233
Misha Brukman7eb05a12003-08-18 14:43:39 +0000234 // Delete the unnecessary instruction now...
Chris Lattnerfda72b12002-06-25 16:12:52 +0000235 BI = BIL.erase(BI);
Chris Lattner28537df2002-05-07 18:07:59 +0000236}
237
Chris Lattnerdf3c3422004-01-09 06:12:26 +0000238void llvm::ReplaceInstWithInst(BasicBlock::InstListType &BIL,
239 BasicBlock::iterator &BI, Instruction *I) {
Craig Toppere73658d2014-04-28 04:05:08 +0000240 assert(I->getParent() == nullptr &&
Chris Lattner28537df2002-05-07 18:07:59 +0000241 "ReplaceInstWithInst: Instruction already inserted into basic block!");
242
Alexey Samsonov19ffcb92015-06-23 21:00:08 +0000243 // Copy debug location to newly added instruction, if it wasn't already set
244 // by the caller.
245 if (!I->getDebugLoc())
246 I->setDebugLoc(BI->getDebugLoc());
247
Chris Lattner28537df2002-05-07 18:07:59 +0000248 // Insert the new instruction into the basic block...
Chris Lattnerfda72b12002-06-25 16:12:52 +0000249 BasicBlock::iterator New = BIL.insert(BI, I);
Chris Lattner28537df2002-05-07 18:07:59 +0000250
251 // Replace all uses of the old instruction, and delete it.
252 ReplaceInstWithValue(BIL, BI, I);
253
254 // Move BI back to point to the newly inserted instruction
Chris Lattnerfda72b12002-06-25 16:12:52 +0000255 BI = New;
Chris Lattner28537df2002-05-07 18:07:59 +0000256}
257
Chris Lattnerdf3c3422004-01-09 06:12:26 +0000258void llvm::ReplaceInstWithInst(Instruction *From, Instruction *To) {
Chris Lattnerfda72b12002-06-25 16:12:52 +0000259 BasicBlock::iterator BI(From);
260 ReplaceInstWithInst(From->getParent()->getInstList(), BI, To);
Chris Lattner28537df2002-05-07 18:07:59 +0000261}
Chris Lattnerb17274e2002-07-29 22:32:08 +0000262
Chandler Carruthd4500562015-01-19 12:36:53 +0000263BasicBlock *llvm::SplitEdge(BasicBlock *BB, BasicBlock *Succ, DominatorTree *DT,
264 LoopInfo *LI) {
Bob Wilsonaff96b22010-02-16 21:06:42 +0000265 unsigned SuccNum = GetSuccessorNumber(BB, Succ);
Jakub Staszak190db2f2013-01-14 23:16:36 +0000266
Chandler Carruth37df2cf2015-01-19 12:09:11 +0000267 // If this is a critical edge, let SplitCriticalEdge do it.
268 TerminatorInst *LatchTerm = BB->getTerminator();
Chandler Carruthd4500562015-01-19 12:36:53 +0000269 if (SplitCriticalEdge(LatchTerm, SuccNum, CriticalEdgeSplittingOptions(DT, LI)
270 .setPreserveLCSSA()))
Chandler Carruth37df2cf2015-01-19 12:09:11 +0000271 return LatchTerm->getSuccessor(SuccNum);
Chandler Carruth32c52c72015-01-18 02:39:37 +0000272
Devang Pateld7767cc2007-07-06 21:39:20 +0000273 // If the edge isn't critical, then BB has a single successor or Succ has a
274 // single pred. Split the block.
Devang Pateld7767cc2007-07-06 21:39:20 +0000275 if (BasicBlock *SP = Succ->getSinglePredecessor()) {
276 // If the successor only has a single pred, split the top of the successor
277 // block.
278 assert(SP == BB && "CFG broken");
Craig Topperf40110f2014-04-25 05:29:35 +0000279 SP = nullptr;
Duncan P. N. Exon Smith5b4c8372015-10-13 02:39:05 +0000280 return SplitBlock(Succ, &Succ->front(), DT, LI);
Devang Pateld7767cc2007-07-06 21:39:20 +0000281 }
Jakub Staszak190db2f2013-01-14 23:16:36 +0000282
Chris Lattner30d95f92011-01-08 18:47:43 +0000283 // Otherwise, if BB has a single successor, split it at the bottom of the
284 // block.
285 assert(BB->getTerminator()->getNumSuccessors() == 1 &&
Jakub Staszak190db2f2013-01-14 23:16:36 +0000286 "Should have a single succ!");
Chandler Carruth32c52c72015-01-18 02:39:37 +0000287 return SplitBlock(BB, BB->getTerminator(), DT, LI);
Devang Pateld7767cc2007-07-06 21:39:20 +0000288}
289
Chandler Carruth37df2cf2015-01-19 12:09:11 +0000290unsigned
291llvm::SplitAllCriticalEdges(Function &F,
292 const CriticalEdgeSplittingOptions &Options) {
Kostya Serebryanye5ea4242014-11-19 00:17:31 +0000293 unsigned NumBroken = 0;
Benjamin Kramer135f7352016-06-26 12:28:59 +0000294 for (BasicBlock &BB : F) {
295 TerminatorInst *TI = BB.getTerminator();
Kostya Serebryanye5ea4242014-11-19 00:17:31 +0000296 if (TI->getNumSuccessors() > 1 && !isa<IndirectBrInst>(TI))
297 for (unsigned i = 0, e = TI->getNumSuccessors(); i != e; ++i)
Chandler Carruth37df2cf2015-01-19 12:09:11 +0000298 if (SplitCriticalEdge(TI, i, Options))
Kostya Serebryanye5ea4242014-11-19 00:17:31 +0000299 ++NumBroken;
300 }
301 return NumBroken;
302}
303
Chandler Carruth32c52c72015-01-18 02:39:37 +0000304BasicBlock *llvm::SplitBlock(BasicBlock *Old, Instruction *SplitPt,
305 DominatorTree *DT, LoopInfo *LI) {
Duncan P. N. Exon Smith5b4c8372015-10-13 02:39:05 +0000306 BasicBlock::iterator SplitIt = SplitPt->getIterator();
David Majnemer654e1302015-07-31 17:58:14 +0000307 while (isa<PHINode>(SplitIt) || SplitIt->isEHPad())
Devang Pateld7767cc2007-07-06 21:39:20 +0000308 ++SplitIt;
309 BasicBlock *New = Old->splitBasicBlock(SplitIt, Old->getName()+".split");
310
Dan Gohman3ddbc242009-09-08 15:45:00 +0000311 // The new block lives in whichever loop the old one did. This preserves
312 // LCSSA as well, because we force the split point to be after any PHI nodes.
Chandler Carruth32c52c72015-01-18 02:39:37 +0000313 if (LI)
314 if (Loop *L = LI->getLoopFor(Old))
315 L->addBasicBlockToLoop(New, *LI);
Devang Pateld7767cc2007-07-06 21:39:20 +0000316
Chandler Carruth32c52c72015-01-18 02:39:37 +0000317 if (DT)
Gabor Greif2f5f6962010-09-10 22:25:58 +0000318 // Old dominates New. New node dominates all other nodes dominated by Old.
Chandler Carruth32c52c72015-01-18 02:39:37 +0000319 if (DomTreeNode *OldNode = DT->getNode(Old)) {
Benjamin Kramer135f7352016-06-26 12:28:59 +0000320 std::vector<DomTreeNode *> Children(OldNode->begin(), OldNode->end());
Devang Patel186e0d82007-07-19 02:29:24 +0000321
Chandler Carruth32c52c72015-01-18 02:39:37 +0000322 DomTreeNode *NewNode = DT->addNewBlock(New, Old);
Benjamin Kramer135f7352016-06-26 12:28:59 +0000323 for (DomTreeNode *I : Children)
324 DT->changeImmediateDominator(I, NewNode);
Rafael Espindolad3e65e72011-08-24 18:07:01 +0000325 }
Devang Pateld7767cc2007-07-06 21:39:20 +0000326
Devang Pateld7767cc2007-07-06 21:39:20 +0000327 return New;
328}
Chris Lattnera5b11702008-04-21 01:28:02 +0000329
Sanjay Patel85ce0f12016-04-23 16:31:48 +0000330/// Update DominatorTree, LoopInfo, and LCCSA analysis information.
Bill Wendling60291352011-08-18 17:57:57 +0000331static void UpdateAnalysisInformation(BasicBlock *OldBB, BasicBlock *NewBB,
Bill Wendlingec3823d2011-08-18 20:39:32 +0000332 ArrayRef<BasicBlock *> Preds,
Chandler Carruthb5797b62015-01-18 09:21:15 +0000333 DominatorTree *DT, LoopInfo *LI,
334 bool PreserveLCSSA, bool &HasLoopExit) {
335 // Update dominator tree if available.
Matt Arsenault06dfbb52018-01-31 22:54:37 +0000336 if (DT) {
337 if (OldBB == DT->getRootNode()->getBlock()) {
338 assert(NewBB == &NewBB->getParent()->getEntryBlock());
339 DT->setNewRoot(NewBB);
340 } else {
341 // Split block expects NewBB to have a non-empty set of predecessors.
342 DT->splitBlock(NewBB);
343 }
344 }
Bill Wendling0a693f42011-08-18 05:25:23 +0000345
Chandler Carruthb5797b62015-01-18 09:21:15 +0000346 // The rest of the logic is only relevant for updating the loop structures.
347 if (!LI)
348 return;
349
Anna Thomas9fca5832018-01-04 17:21:15 +0000350 assert(DT && "DT should be available to update LoopInfo!");
Chandler Carruthb5797b62015-01-18 09:21:15 +0000351 Loop *L = LI->getLoopFor(OldBB);
Bill Wendling0a693f42011-08-18 05:25:23 +0000352
353 // If we need to preserve loop analyses, collect some information about how
354 // this split will affect loops.
355 bool IsLoopEntry = !!L;
356 bool SplitMakesNewLoopHeader = false;
Benjamin Kramer135f7352016-06-26 12:28:59 +0000357 for (BasicBlock *Pred : Preds) {
Anna Thomasbdb94302018-01-02 16:25:50 +0000358 // Preds that are not reachable from entry should not be used to identify if
359 // OldBB is a loop entry or if SplitMakesNewLoopHeader. Unreachable blocks
360 // are not within any loops, so we incorrectly mark SplitMakesNewLoopHeader
361 // as true and make the NewBB the header of some loop. This breaks LI.
362 if (!DT->isReachableFromEntry(Pred))
363 continue;
Chandler Carruthb5797b62015-01-18 09:21:15 +0000364 // If we need to preserve LCSSA, determine if any of the preds is a loop
365 // exit.
366 if (PreserveLCSSA)
367 if (Loop *PL = LI->getLoopFor(Pred))
368 if (!PL->contains(OldBB))
369 HasLoopExit = true;
Bill Wendling0a693f42011-08-18 05:25:23 +0000370
Chandler Carruthb5797b62015-01-18 09:21:15 +0000371 // If we need to preserve LoopInfo, note whether any of the preds crosses
372 // an interesting loop boundary.
373 if (!L)
374 continue;
375 if (L->contains(Pred))
376 IsLoopEntry = false;
377 else
378 SplitMakesNewLoopHeader = true;
Bill Wendling0a693f42011-08-18 05:25:23 +0000379 }
380
Chandler Carruthb5797b62015-01-18 09:21:15 +0000381 // Unless we have a loop for OldBB, nothing else to do here.
382 if (!L)
383 return;
Bill Wendling0a693f42011-08-18 05:25:23 +0000384
385 if (IsLoopEntry) {
386 // Add the new block to the nearest enclosing loop (and not an adjacent
387 // loop). To find this, examine each of the predecessors and determine which
388 // loops enclose them, and select the most-nested loop which contains the
389 // loop containing the block being split.
Craig Topperf40110f2014-04-25 05:29:35 +0000390 Loop *InnermostPredLoop = nullptr;
Benjamin Kramer135f7352016-06-26 12:28:59 +0000391 for (BasicBlock *Pred : Preds) {
Bill Wendlingec3823d2011-08-18 20:39:32 +0000392 if (Loop *PredLoop = LI->getLoopFor(Pred)) {
Bill Wendling0a693f42011-08-18 05:25:23 +0000393 // Seek a loop which actually contains the block being split (to avoid
394 // adjacent loops).
395 while (PredLoop && !PredLoop->contains(OldBB))
396 PredLoop = PredLoop->getParentLoop();
397
398 // Select the most-nested of these loops which contains the block.
399 if (PredLoop && PredLoop->contains(OldBB) &&
400 (!InnermostPredLoop ||
401 InnermostPredLoop->getLoopDepth() < PredLoop->getLoopDepth()))
402 InnermostPredLoop = PredLoop;
403 }
Bill Wendlingec3823d2011-08-18 20:39:32 +0000404 }
Bill Wendling0a693f42011-08-18 05:25:23 +0000405
406 if (InnermostPredLoop)
Chandler Carruth691addc2015-01-18 01:25:51 +0000407 InnermostPredLoop->addBasicBlockToLoop(NewBB, *LI);
Bill Wendling0a693f42011-08-18 05:25:23 +0000408 } else {
Chandler Carruth691addc2015-01-18 01:25:51 +0000409 L->addBasicBlockToLoop(NewBB, *LI);
Bill Wendling0a693f42011-08-18 05:25:23 +0000410 if (SplitMakesNewLoopHeader)
411 L->moveToHeader(NewBB);
412 }
413}
414
Sanjay Patel85ce0f12016-04-23 16:31:48 +0000415/// Update the PHI nodes in OrigBB to include the values coming from NewBB.
416/// This also updates AliasAnalysis, if available.
Bill Wendlingb267e2a2011-08-18 20:51:04 +0000417static void UpdatePHINodes(BasicBlock *OrigBB, BasicBlock *NewBB,
Chandler Carruthb5797b62015-01-18 09:21:15 +0000418 ArrayRef<BasicBlock *> Preds, BranchInst *BI,
Chandler Carruth96ada252015-07-22 09:52:54 +0000419 bool HasLoopExit) {
Bill Wendlingb267e2a2011-08-18 20:51:04 +0000420 // Otherwise, create a new PHI node in NewBB for each PHI node in OrigBB.
Chandler Carruth5bdf72c2014-04-28 10:37:30 +0000421 SmallPtrSet<BasicBlock *, 16> PredSet(Preds.begin(), Preds.end());
Bill Wendlingb267e2a2011-08-18 20:51:04 +0000422 for (BasicBlock::iterator I = OrigBB->begin(); isa<PHINode>(I); ) {
423 PHINode *PN = cast<PHINode>(I++);
424
425 // Check to see if all of the values coming in are the same. If so, we
426 // don't need to create a new PHI node, unless it's needed for LCSSA.
Craig Topperf40110f2014-04-25 05:29:35 +0000427 Value *InVal = nullptr;
Bill Wendlingb267e2a2011-08-18 20:51:04 +0000428 if (!HasLoopExit) {
429 InVal = PN->getIncomingValueForBlock(Preds[0]);
Chandler Carruth5bdf72c2014-04-28 10:37:30 +0000430 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) {
431 if (!PredSet.count(PN->getIncomingBlock(i)))
432 continue;
433 if (!InVal)
434 InVal = PN->getIncomingValue(i);
435 else if (InVal != PN->getIncomingValue(i)) {
Craig Topperf40110f2014-04-25 05:29:35 +0000436 InVal = nullptr;
Bill Wendlingb267e2a2011-08-18 20:51:04 +0000437 break;
438 }
Chandler Carruth5bdf72c2014-04-28 10:37:30 +0000439 }
Bill Wendlingb267e2a2011-08-18 20:51:04 +0000440 }
441
442 if (InVal) {
443 // If all incoming values for the new PHI would be the same, just don't
444 // make a new PHI. Instead, just remove the incoming values from the old
445 // PHI.
Jakub Staszak190db2f2013-01-14 23:16:36 +0000446
Chandler Carruth5bdf72c2014-04-28 10:37:30 +0000447 // NOTE! This loop walks backwards for a reason! First off, this minimizes
448 // the cost of removal if we end up removing a large number of values, and
449 // second off, this ensures that the indices for the incoming values
450 // aren't invalidated when we remove one.
451 for (int64_t i = PN->getNumIncomingValues() - 1; i >= 0; --i)
452 if (PredSet.count(PN->getIncomingBlock(i)))
453 PN->removeIncomingValue(i, false);
Bill Wendlingb267e2a2011-08-18 20:51:04 +0000454
Chandler Carruth5bdf72c2014-04-28 10:37:30 +0000455 // Add an incoming value to the PHI node in the loop for the preheader
456 // edge.
457 PN->addIncoming(InVal, NewBB);
458 continue;
Bill Wendlingb267e2a2011-08-18 20:51:04 +0000459 }
460
Chandler Carruth5bdf72c2014-04-28 10:37:30 +0000461 // If the values coming into the block are not the same, we need a new
462 // PHI.
463 // Create the new PHI node, insert it into NewBB at the end of the block
464 PHINode *NewPHI =
465 PHINode::Create(PN->getType(), Preds.size(), PN->getName() + ".ph", BI);
Chandler Carruth5bdf72c2014-04-28 10:37:30 +0000466
467 // NOTE! This loop walks backwards for a reason! First off, this minimizes
468 // the cost of removal if we end up removing a large number of values, and
469 // second off, this ensures that the indices for the incoming values aren't
470 // invalidated when we remove one.
471 for (int64_t i = PN->getNumIncomingValues() - 1; i >= 0; --i) {
472 BasicBlock *IncomingBB = PN->getIncomingBlock(i);
473 if (PredSet.count(IncomingBB)) {
474 Value *V = PN->removeIncomingValue(i, false);
475 NewPHI->addIncoming(V, IncomingBB);
476 }
477 }
478
479 PN->addIncoming(NewPHI, NewBB);
Bill Wendlingb267e2a2011-08-18 20:51:04 +0000480 }
481}
482
Jakub Staszak190db2f2013-01-14 23:16:36 +0000483BasicBlock *llvm::SplitBlockPredecessors(BasicBlock *BB,
Chandler Carruthb5797b62015-01-18 09:21:15 +0000484 ArrayRef<BasicBlock *> Preds,
Chandler Carruth96ada252015-07-22 09:52:54 +0000485 const char *Suffix, DominatorTree *DT,
486 LoopInfo *LI, bool PreserveLCSSA) {
David Majnemer654e1302015-07-31 17:58:14 +0000487 // Do not attempt to split that which cannot be split.
488 if (!BB->canSplitPredecessors())
489 return nullptr;
490
Philip Reames9198b332015-01-28 23:06:47 +0000491 // For the landingpads we need to act a bit differently.
492 // Delegate this work to the SplitLandingPadPredecessors.
493 if (BB->isLandingPad()) {
494 SmallVector<BasicBlock*, 2> NewBBs;
495 std::string NewName = std::string(Suffix) + ".split-lp";
496
Chandler Carruth96ada252015-07-22 09:52:54 +0000497 SplitLandingPadPredecessors(BB, Preds, Suffix, NewName.c_str(), NewBBs, DT,
498 LI, PreserveLCSSA);
Philip Reames9198b332015-01-28 23:06:47 +0000499 return NewBBs[0];
500 }
501
Chris Lattnera5b11702008-04-21 01:28:02 +0000502 // Create new basic block, insert right before the original block.
Alexey Samsonovb7f02d32015-06-09 22:10:29 +0000503 BasicBlock *NewBB = BasicBlock::Create(
504 BB->getContext(), BB->getName() + Suffix, BB->getParent(), BB);
Jakub Staszak190db2f2013-01-14 23:16:36 +0000505
Chris Lattnera5b11702008-04-21 01:28:02 +0000506 // The new block unconditionally branches to the old block.
507 BranchInst *BI = BranchInst::Create(BB, NewBB);
Taewook Oh2e945eb2017-02-14 21:10:40 +0000508 BI->setDebugLoc(BB->getFirstNonPHIOrDbg()->getDebugLoc());
Jakub Staszak190db2f2013-01-14 23:16:36 +0000509
Chris Lattnera5b11702008-04-21 01:28:02 +0000510 // Move the edges from Preds to point to NewBB instead of BB.
Jakub Staszakf5b32e52011-12-09 21:19:53 +0000511 for (unsigned i = 0, e = Preds.size(); i != e; ++i) {
Dan Gohman00c79382009-11-05 18:25:44 +0000512 // This is slightly more strict than necessary; the minimum requirement
513 // is that there be no more than one indirectbr branching to BB. And
514 // all BlockAddress uses would need to be updated.
515 assert(!isa<IndirectBrInst>(Preds[i]->getTerminator()) &&
516 "Cannot split an edge from an IndirectBrInst");
Chris Lattnera5b11702008-04-21 01:28:02 +0000517 Preds[i]->getTerminator()->replaceUsesOfWith(BB, NewBB);
Dan Gohman3ddbc242009-09-08 15:45:00 +0000518 }
519
Chris Lattnera5b11702008-04-21 01:28:02 +0000520 // Insert a new PHI node into NewBB for every PHI node in BB and that new PHI
521 // node becomes an incoming value for BB's phi node. However, if the Preds
522 // list is empty, we need to insert dummy entries into the PHI nodes in BB to
523 // account for the newly created predecessor.
Eugene Zelenko57bd5a02017-10-27 01:09:08 +0000524 if (Preds.empty()) {
Chris Lattnera5b11702008-04-21 01:28:02 +0000525 // Insert dummy values as the incoming value.
526 for (BasicBlock::iterator I = BB->begin(); isa<PHINode>(I); ++I)
Owen Andersonb292b8c2009-07-30 23:03:37 +0000527 cast<PHINode>(I)->addIncoming(UndefValue::get(I->getType()), NewBB);
Chris Lattnera5b11702008-04-21 01:28:02 +0000528 }
Dan Gohman3ddbc242009-09-08 15:45:00 +0000529
Bill Wendling0a693f42011-08-18 05:25:23 +0000530 // Update DominatorTree, LoopInfo, and LCCSA analysis information.
531 bool HasLoopExit = false;
Chandler Carruthb5797b62015-01-18 09:21:15 +0000532 UpdateAnalysisInformation(BB, NewBB, Preds, DT, LI, PreserveLCSSA,
533 HasLoopExit);
Dan Gohman3ddbc242009-09-08 15:45:00 +0000534
Matt Arsenault06dfbb52018-01-31 22:54:37 +0000535 if (!Preds.empty()) {
536 // Update the PHI nodes in BB with the values coming from NewBB.
537 UpdatePHINodes(BB, NewBB, Preds, BI, HasLoopExit);
538 }
539
Chris Lattnera5b11702008-04-21 01:28:02 +0000540 return NewBB;
541}
Chris Lattner72f16e72008-11-27 08:10:05 +0000542
Bill Wendlingca7d3092011-08-19 00:05:40 +0000543void llvm::SplitLandingPadPredecessors(BasicBlock *OrigBB,
Chandler Carruth0eae1122015-01-19 03:03:39 +0000544 ArrayRef<BasicBlock *> Preds,
Bill Wendlingca7d3092011-08-19 00:05:40 +0000545 const char *Suffix1, const char *Suffix2,
Chandler Carruth0eae1122015-01-19 03:03:39 +0000546 SmallVectorImpl<BasicBlock *> &NewBBs,
Chandler Carruth96ada252015-07-22 09:52:54 +0000547 DominatorTree *DT, LoopInfo *LI,
548 bool PreserveLCSSA) {
Bill Wendlingca7d3092011-08-19 00:05:40 +0000549 assert(OrigBB->isLandingPad() && "Trying to split a non-landing pad!");
550
551 // Create a new basic block for OrigBB's predecessors listed in Preds. Insert
552 // it right before the original block.
553 BasicBlock *NewBB1 = BasicBlock::Create(OrigBB->getContext(),
554 OrigBB->getName() + Suffix1,
555 OrigBB->getParent(), OrigBB);
556 NewBBs.push_back(NewBB1);
557
558 // The new block unconditionally branches to the old block.
559 BranchInst *BI1 = BranchInst::Create(OrigBB, NewBB1);
Alexey Samsonovb7f02d32015-06-09 22:10:29 +0000560 BI1->setDebugLoc(OrigBB->getFirstNonPHI()->getDebugLoc());
Bill Wendlingca7d3092011-08-19 00:05:40 +0000561
562 // Move the edges from Preds to point to NewBB1 instead of OrigBB.
563 for (unsigned i = 0, e = Preds.size(); i != e; ++i) {
564 // This is slightly more strict than necessary; the minimum requirement
565 // is that there be no more than one indirectbr branching to BB. And
566 // all BlockAddress uses would need to be updated.
567 assert(!isa<IndirectBrInst>(Preds[i]->getTerminator()) &&
568 "Cannot split an edge from an IndirectBrInst");
569 Preds[i]->getTerminator()->replaceUsesOfWith(OrigBB, NewBB1);
570 }
571
Bill Wendlingca7d3092011-08-19 00:05:40 +0000572 bool HasLoopExit = false;
Chandler Carruthb5797b62015-01-18 09:21:15 +0000573 UpdateAnalysisInformation(OrigBB, NewBB1, Preds, DT, LI, PreserveLCSSA,
574 HasLoopExit);
Bill Wendlingca7d3092011-08-19 00:05:40 +0000575
576 // Update the PHI nodes in OrigBB with the values coming from NewBB1.
Chandler Carruth96ada252015-07-22 09:52:54 +0000577 UpdatePHINodes(OrigBB, NewBB1, Preds, BI1, HasLoopExit);
Bill Wendlingca7d3092011-08-19 00:05:40 +0000578
Bill Wendlingca7d3092011-08-19 00:05:40 +0000579 // Move the remaining edges from OrigBB to point to NewBB2.
580 SmallVector<BasicBlock*, 8> NewBB2Preds;
Duncan P. N. Exon Smith6c990152014-07-21 17:06:51 +0000581 for (pred_iterator i = pred_begin(OrigBB), e = pred_end(OrigBB);
582 i != e; ) {
583 BasicBlock *Pred = *i++;
Bill Wendling38d81302011-08-19 23:46:30 +0000584 if (Pred == NewBB1) continue;
Bill Wendlingca7d3092011-08-19 00:05:40 +0000585 assert(!isa<IndirectBrInst>(Pred->getTerminator()) &&
586 "Cannot split an edge from an IndirectBrInst");
Bill Wendlingca7d3092011-08-19 00:05:40 +0000587 NewBB2Preds.push_back(Pred);
Duncan P. N. Exon Smith6c990152014-07-21 17:06:51 +0000588 e = pred_end(OrigBB);
Bill Wendlingca7d3092011-08-19 00:05:40 +0000589 }
590
Craig Topperf40110f2014-04-25 05:29:35 +0000591 BasicBlock *NewBB2 = nullptr;
Bill Wendling38d81302011-08-19 23:46:30 +0000592 if (!NewBB2Preds.empty()) {
593 // Create another basic block for the rest of OrigBB's predecessors.
594 NewBB2 = BasicBlock::Create(OrigBB->getContext(),
595 OrigBB->getName() + Suffix2,
596 OrigBB->getParent(), OrigBB);
597 NewBBs.push_back(NewBB2);
Bill Wendlingca7d3092011-08-19 00:05:40 +0000598
Bill Wendling38d81302011-08-19 23:46:30 +0000599 // The new block unconditionally branches to the old block.
600 BranchInst *BI2 = BranchInst::Create(OrigBB, NewBB2);
Alexey Samsonovb7f02d32015-06-09 22:10:29 +0000601 BI2->setDebugLoc(OrigBB->getFirstNonPHI()->getDebugLoc());
Bill Wendling38d81302011-08-19 23:46:30 +0000602
603 // Move the remaining edges from OrigBB to point to NewBB2.
Benjamin Kramer135f7352016-06-26 12:28:59 +0000604 for (BasicBlock *NewBB2Pred : NewBB2Preds)
605 NewBB2Pred->getTerminator()->replaceUsesOfWith(OrigBB, NewBB2);
Bill Wendling38d81302011-08-19 23:46:30 +0000606
607 // Update DominatorTree, LoopInfo, and LCCSA analysis information.
608 HasLoopExit = false;
Chandler Carruthb5797b62015-01-18 09:21:15 +0000609 UpdateAnalysisInformation(OrigBB, NewBB2, NewBB2Preds, DT, LI,
610 PreserveLCSSA, HasLoopExit);
Bill Wendling38d81302011-08-19 23:46:30 +0000611
612 // Update the PHI nodes in OrigBB with the values coming from NewBB2.
Chandler Carruth96ada252015-07-22 09:52:54 +0000613 UpdatePHINodes(OrigBB, NewBB2, NewBB2Preds, BI2, HasLoopExit);
Bill Wendling38d81302011-08-19 23:46:30 +0000614 }
Bill Wendlingca7d3092011-08-19 00:05:40 +0000615
616 LandingPadInst *LPad = OrigBB->getLandingPadInst();
617 Instruction *Clone1 = LPad->clone();
618 Clone1->setName(Twine("lpad") + Suffix1);
619 NewBB1->getInstList().insert(NewBB1->getFirstInsertionPt(), Clone1);
620
Bill Wendling38d81302011-08-19 23:46:30 +0000621 if (NewBB2) {
622 Instruction *Clone2 = LPad->clone();
623 Clone2->setName(Twine("lpad") + Suffix2);
624 NewBB2->getInstList().insert(NewBB2->getFirstInsertionPt(), Clone2);
Bill Wendlingca7d3092011-08-19 00:05:40 +0000625
Chen Li78bde832016-01-06 20:32:05 +0000626 // Create a PHI node for the two cloned landingpad instructions only
627 // if the original landingpad instruction has some uses.
628 if (!LPad->use_empty()) {
629 assert(!LPad->getType()->isTokenTy() &&
630 "Split cannot be applied if LPad is token type. Otherwise an "
631 "invalid PHINode of token type would be created.");
632 PHINode *PN = PHINode::Create(LPad->getType(), 2, "lpad.phi", LPad);
633 PN->addIncoming(Clone1, NewBB1);
634 PN->addIncoming(Clone2, NewBB2);
635 LPad->replaceAllUsesWith(PN);
636 }
Bill Wendling38d81302011-08-19 23:46:30 +0000637 LPad->eraseFromParent();
638 } else {
639 // There is no second clone. Just replace the landing pad with the first
640 // clone.
641 LPad->replaceAllUsesWith(Clone1);
642 LPad->eraseFromParent();
643 }
Bill Wendlingca7d3092011-08-19 00:05:40 +0000644}
645
Evan Chengd983eba2011-01-29 04:46:23 +0000646ReturnInst *llvm::FoldReturnIntoUncondBranch(ReturnInst *RI, BasicBlock *BB,
647 BasicBlock *Pred) {
648 Instruction *UncondBranch = Pred->getTerminator();
649 // Clone the return and add it to the end of the predecessor.
650 Instruction *NewRet = RI->clone();
651 Pred->getInstList().push_back(NewRet);
Jakub Staszak190db2f2013-01-14 23:16:36 +0000652
Evan Chengd983eba2011-01-29 04:46:23 +0000653 // If the return instruction returns a value, and if the value was a
654 // PHI node in "BB", propagate the right value into the return.
655 for (User::op_iterator i = NewRet->op_begin(), e = NewRet->op_end();
Evan Cheng249716e2012-07-27 21:21:26 +0000656 i != e; ++i) {
657 Value *V = *i;
Craig Topperf40110f2014-04-25 05:29:35 +0000658 Instruction *NewBC = nullptr;
Evan Cheng249716e2012-07-27 21:21:26 +0000659 if (BitCastInst *BCI = dyn_cast<BitCastInst>(V)) {
660 // Return value might be bitcasted. Clone and insert it before the
661 // return instruction.
662 V = BCI->getOperand(0);
663 NewBC = BCI->clone();
Duncan P. N. Exon Smith5b4c8372015-10-13 02:39:05 +0000664 Pred->getInstList().insert(NewRet->getIterator(), NewBC);
Evan Cheng249716e2012-07-27 21:21:26 +0000665 *i = NewBC;
666 }
667 if (PHINode *PN = dyn_cast<PHINode>(V)) {
668 if (PN->getParent() == BB) {
669 if (NewBC)
670 NewBC->setOperand(0, PN->getIncomingValueForBlock(Pred));
671 else
672 *i = PN->getIncomingValueForBlock(Pred);
673 }
674 }
675 }
Jakub Staszak190db2f2013-01-14 23:16:36 +0000676
Evan Chengd983eba2011-01-29 04:46:23 +0000677 // Update any PHI nodes in the returning block to realize that we no
678 // longer branch to them.
679 BB->removePredecessor(Pred);
680 UncondBranch->eraseFromParent();
681 return cast<ReturnInst>(NewRet);
Chris Lattner351134b2009-05-04 02:25:58 +0000682}
Devang Patela8e74112011-04-29 22:28:59 +0000683
Adam Nemetfdb20592016-03-15 18:06:20 +0000684TerminatorInst *
685llvm::SplitBlockAndInsertIfThen(Value *Cond, Instruction *SplitBefore,
686 bool Unreachable, MDNode *BranchWeights,
687 DominatorTree *DT, LoopInfo *LI) {
Evgeniy Stepanov8eb77d82012-10-19 10:48:31 +0000688 BasicBlock *Head = SplitBefore->getParent();
Duncan P. N. Exon Smith5b4c8372015-10-13 02:39:05 +0000689 BasicBlock *Tail = Head->splitBasicBlock(SplitBefore->getIterator());
Evgeniy Stepanov8eb77d82012-10-19 10:48:31 +0000690 TerminatorInst *HeadOldTerm = Head->getTerminator();
691 LLVMContext &C = Head->getContext();
692 BasicBlock *ThenBlock = BasicBlock::Create(C, "", Head->getParent(), Tail);
693 TerminatorInst *CheckTerm;
694 if (Unreachable)
695 CheckTerm = new UnreachableInst(C, ThenBlock);
696 else
697 CheckTerm = BranchInst::Create(Tail, ThenBlock);
Evgeniy Stepanov2275a012014-03-19 12:56:38 +0000698 CheckTerm->setDebugLoc(SplitBefore->getDebugLoc());
Evgeniy Stepanov8eb77d82012-10-19 10:48:31 +0000699 BranchInst *HeadNewTerm =
Evgeniy Stepanova9164e92013-12-19 13:29:56 +0000700 BranchInst::Create(/*ifTrue*/ThenBlock, /*ifFalse*/Tail, Cond);
Evgeniy Stepanov8eb77d82012-10-19 10:48:31 +0000701 HeadNewTerm->setMetadata(LLVMContext::MD_prof, BranchWeights);
702 ReplaceInstWithInst(HeadOldTerm, HeadNewTerm);
Peter Collingbourne818f5c42014-07-15 04:40:27 +0000703
704 if (DT) {
705 if (DomTreeNode *OldNode = DT->getNode(Head)) {
706 std::vector<DomTreeNode *> Children(OldNode->begin(), OldNode->end());
707
708 DomTreeNode *NewNode = DT->addNewBlock(Tail, Head);
Benjamin Kramer135f7352016-06-26 12:28:59 +0000709 for (DomTreeNode *Child : Children)
Peter Collingbourne818f5c42014-07-15 04:40:27 +0000710 DT->changeImmediateDominator(Child, NewNode);
711
712 // Head dominates ThenBlock.
713 DT->addNewBlock(ThenBlock, Head);
714 }
715 }
716
Adam Nemetfdb20592016-03-15 18:06:20 +0000717 if (LI) {
Michael Kruse811de8a2017-03-06 15:33:05 +0000718 if (Loop *L = LI->getLoopFor(Head)) {
719 L->addBasicBlockToLoop(ThenBlock, *LI);
720 L->addBasicBlockToLoop(Tail, *LI);
721 }
Adam Nemetfdb20592016-03-15 18:06:20 +0000722 }
723
Evgeniy Stepanov8eb77d82012-10-19 10:48:31 +0000724 return CheckTerm;
725}
Tom Stellardaa664d92013-08-06 02:43:45 +0000726
Kostya Serebryany530e2072013-12-23 14:15:08 +0000727void llvm::SplitBlockAndInsertIfThenElse(Value *Cond, Instruction *SplitBefore,
728 TerminatorInst **ThenTerm,
729 TerminatorInst **ElseTerm,
730 MDNode *BranchWeights) {
731 BasicBlock *Head = SplitBefore->getParent();
Duncan P. N. Exon Smith5b4c8372015-10-13 02:39:05 +0000732 BasicBlock *Tail = Head->splitBasicBlock(SplitBefore->getIterator());
Kostya Serebryany530e2072013-12-23 14:15:08 +0000733 TerminatorInst *HeadOldTerm = Head->getTerminator();
734 LLVMContext &C = Head->getContext();
735 BasicBlock *ThenBlock = BasicBlock::Create(C, "", Head->getParent(), Tail);
736 BasicBlock *ElseBlock = BasicBlock::Create(C, "", Head->getParent(), Tail);
737 *ThenTerm = BranchInst::Create(Tail, ThenBlock);
Evgeniy Stepanov2275a012014-03-19 12:56:38 +0000738 (*ThenTerm)->setDebugLoc(SplitBefore->getDebugLoc());
Kostya Serebryany530e2072013-12-23 14:15:08 +0000739 *ElseTerm = BranchInst::Create(Tail, ElseBlock);
Evgeniy Stepanov2275a012014-03-19 12:56:38 +0000740 (*ElseTerm)->setDebugLoc(SplitBefore->getDebugLoc());
Kostya Serebryany530e2072013-12-23 14:15:08 +0000741 BranchInst *HeadNewTerm =
742 BranchInst::Create(/*ifTrue*/ThenBlock, /*ifFalse*/ElseBlock, Cond);
743 HeadNewTerm->setMetadata(LLVMContext::MD_prof, BranchWeights);
744 ReplaceInstWithInst(HeadOldTerm, HeadNewTerm);
745}
746
Tom Stellardaa664d92013-08-06 02:43:45 +0000747Value *llvm::GetIfCondition(BasicBlock *BB, BasicBlock *&IfTrue,
748 BasicBlock *&IfFalse) {
749 PHINode *SomePHI = dyn_cast<PHINode>(BB->begin());
Craig Topperf40110f2014-04-25 05:29:35 +0000750 BasicBlock *Pred1 = nullptr;
751 BasicBlock *Pred2 = nullptr;
Tom Stellardaa664d92013-08-06 02:43:45 +0000752
753 if (SomePHI) {
754 if (SomePHI->getNumIncomingValues() != 2)
Craig Topperf40110f2014-04-25 05:29:35 +0000755 return nullptr;
Tom Stellardaa664d92013-08-06 02:43:45 +0000756 Pred1 = SomePHI->getIncomingBlock(0);
757 Pred2 = SomePHI->getIncomingBlock(1);
758 } else {
759 pred_iterator PI = pred_begin(BB), PE = pred_end(BB);
760 if (PI == PE) // No predecessor
Craig Topperf40110f2014-04-25 05:29:35 +0000761 return nullptr;
Tom Stellardaa664d92013-08-06 02:43:45 +0000762 Pred1 = *PI++;
763 if (PI == PE) // Only one predecessor
Craig Topperf40110f2014-04-25 05:29:35 +0000764 return nullptr;
Tom Stellardaa664d92013-08-06 02:43:45 +0000765 Pred2 = *PI++;
766 if (PI != PE) // More than two predecessors
Craig Topperf40110f2014-04-25 05:29:35 +0000767 return nullptr;
Tom Stellardaa664d92013-08-06 02:43:45 +0000768 }
769
770 // We can only handle branches. Other control flow will be lowered to
771 // branches if possible anyway.
772 BranchInst *Pred1Br = dyn_cast<BranchInst>(Pred1->getTerminator());
773 BranchInst *Pred2Br = dyn_cast<BranchInst>(Pred2->getTerminator());
Craig Topperf40110f2014-04-25 05:29:35 +0000774 if (!Pred1Br || !Pred2Br)
775 return nullptr;
Tom Stellardaa664d92013-08-06 02:43:45 +0000776
777 // Eliminate code duplication by ensuring that Pred1Br is conditional if
778 // either are.
779 if (Pred2Br->isConditional()) {
780 // If both branches are conditional, we don't have an "if statement". In
781 // reality, we could transform this case, but since the condition will be
782 // required anyway, we stand no chance of eliminating it, so the xform is
783 // probably not profitable.
784 if (Pred1Br->isConditional())
Craig Topperf40110f2014-04-25 05:29:35 +0000785 return nullptr;
Tom Stellardaa664d92013-08-06 02:43:45 +0000786
787 std::swap(Pred1, Pred2);
788 std::swap(Pred1Br, Pred2Br);
789 }
790
791 if (Pred1Br->isConditional()) {
792 // The only thing we have to watch out for here is to make sure that Pred2
793 // doesn't have incoming edges from other blocks. If it does, the condition
794 // doesn't dominate BB.
Craig Topperf40110f2014-04-25 05:29:35 +0000795 if (!Pred2->getSinglePredecessor())
796 return nullptr;
Tom Stellardaa664d92013-08-06 02:43:45 +0000797
798 // If we found a conditional branch predecessor, make sure that it branches
799 // to BB and Pred2Br. If it doesn't, this isn't an "if statement".
800 if (Pred1Br->getSuccessor(0) == BB &&
801 Pred1Br->getSuccessor(1) == Pred2) {
802 IfTrue = Pred1;
803 IfFalse = Pred2;
804 } else if (Pred1Br->getSuccessor(0) == Pred2 &&
805 Pred1Br->getSuccessor(1) == BB) {
806 IfTrue = Pred2;
807 IfFalse = Pred1;
808 } else {
809 // We know that one arm of the conditional goes to BB, so the other must
810 // go somewhere unrelated, and this must not be an "if statement".
Craig Topperf40110f2014-04-25 05:29:35 +0000811 return nullptr;
Tom Stellardaa664d92013-08-06 02:43:45 +0000812 }
813
814 return Pred1Br->getCondition();
815 }
816
817 // Ok, if we got here, both predecessors end with an unconditional branch to
818 // BB. Don't panic! If both blocks only have a single (identical)
819 // predecessor, and THAT is a conditional branch, then we're all ok!
820 BasicBlock *CommonPred = Pred1->getSinglePredecessor();
Craig Topperf40110f2014-04-25 05:29:35 +0000821 if (CommonPred == nullptr || CommonPred != Pred2->getSinglePredecessor())
822 return nullptr;
Tom Stellardaa664d92013-08-06 02:43:45 +0000823
824 // Otherwise, if this is a conditional branch, then we can use it!
825 BranchInst *BI = dyn_cast<BranchInst>(CommonPred->getTerminator());
Craig Topperf40110f2014-04-25 05:29:35 +0000826 if (!BI) return nullptr;
Tom Stellardaa664d92013-08-06 02:43:45 +0000827
828 assert(BI->isConditional() && "Two successors but not conditional?");
829 if (BI->getSuccessor(0) == Pred1) {
830 IfTrue = Pred1;
831 IfFalse = Pred2;
832 } else {
833 IfTrue = Pred2;
834 IfFalse = Pred1;
835 }
836 return BI->getCondition();
837}