blob: 9d3593913fae116e69d52129bd68697fa2ae32cb [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"
Eugene Zelenko57bd5a02017-10-27 01:09:08 +000023#include "llvm/IR/BasicBlock.h"
24#include "llvm/IR/CFG.h"
25#include "llvm/IR/Constants.h"
Adrian Prantld60f34c2017-11-01 20:43:30 +000026#include "llvm/IR/DebugInfoMetadata.h"
Chandler Carruth5ad5f152014-01-13 09:26:24 +000027#include "llvm/IR/Dominators.h"
Chandler Carruth9fb823b2013-01-02 11:36:10 +000028#include "llvm/IR/Function.h"
Eugene Zelenko57bd5a02017-10-27 01:09:08 +000029#include "llvm/IR/InstrTypes.h"
30#include "llvm/IR/Instruction.h"
Chandler Carruth9fb823b2013-01-02 11:36:10 +000031#include "llvm/IR/Instructions.h"
Adrian Prantld60f34c2017-11-01 20:43:30 +000032#include "llvm/IR/IntrinsicInst.h"
Eugene Zelenko57bd5a02017-10-27 01:09:08 +000033#include "llvm/IR/LLVMContext.h"
Chandler Carruth9fb823b2013-01-02 11:36:10 +000034#include "llvm/IR/Type.h"
Eugene Zelenko57bd5a02017-10-27 01:09:08 +000035#include "llvm/IR/User.h"
36#include "llvm/IR/Value.h"
Chandler Carruth4220e9c2014-03-04 11:17:44 +000037#include "llvm/IR/ValueHandle.h"
Eugene Zelenko57bd5a02017-10-27 01:09:08 +000038#include "llvm/Support/Casting.h"
Chandler Carruthed0881b2012-12-03 16:50:05 +000039#include "llvm/Transforms/Utils/Local.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,
Chandler Carruth61440d22016-03-10 00:55:30 +0000120 MemoryDependenceResults *MemDep) {
Dan Gohman941020e2010-08-17 17:07:02 +0000121 // Don't merge away blocks who have their address taken.
122 if (BB->hasAddressTaken()) return false;
Jakub Staszak190db2f2013-01-14 23:16:36 +0000123
Dan Gohman941020e2010-08-17 17:07:02 +0000124 // Can't merge if there are multiple predecessors, or no predecessors.
125 BasicBlock *PredBB = BB->getUniquePredecessor();
Dan Gohman2d02ff82009-10-31 17:33:01 +0000126 if (!PredBB) return false;
Dan Gohman941020e2010-08-17 17:07:02 +0000127
Dan Gohman2d02ff82009-10-31 17:33:01 +0000128 // Don't break self-loops.
129 if (PredBB == BB) return false;
David Majnemer654e1302015-07-31 17:58:14 +0000130 // Don't break unwinding instructions.
131 if (PredBB->getTerminator()->isExceptional())
132 return false;
Jakub Staszak190db2f2013-01-14 23:16:36 +0000133
Dan Gohman2d02ff82009-10-31 17:33:01 +0000134 succ_iterator SI(succ_begin(PredBB)), SE(succ_end(PredBB));
Chris Lattner930b7162011-01-08 19:08:40 +0000135 BasicBlock *OnlySucc = BB;
Dan Gohman2d02ff82009-10-31 17:33:01 +0000136 for (; SI != SE; ++SI)
137 if (*SI != OnlySucc) {
Craig Topperf40110f2014-04-25 05:29:35 +0000138 OnlySucc = nullptr; // There are multiple distinct successors!
Dan Gohman2d02ff82009-10-31 17:33:01 +0000139 break;
140 }
Jakub Staszak190db2f2013-01-14 23:16:36 +0000141
Dan Gohman2d02ff82009-10-31 17:33:01 +0000142 // Can't merge if there are multiple successors.
143 if (!OnlySucc) return false;
Devang Patel0f7a3502008-09-09 01:06:56 +0000144
Dan Gohman2d02ff82009-10-31 17:33:01 +0000145 // Can't merge if there is PHI loop.
Benjamin Kramerc7fc81e2017-12-30 15:27:33 +0000146 for (PHINode &PN : BB->phis())
147 for (Value *IncValue : PN.incoming_values())
148 if (IncValue == &PN)
149 return false;
Dan Gohman2d02ff82009-10-31 17:33:01 +0000150
151 // Begin by getting rid of unneeded PHIs.
Adrian Prantld60f34c2017-11-01 20:43:30 +0000152 SmallVector<Value *, 4> IncomingValues;
153 if (isa<PHINode>(BB->front())) {
Benjamin Kramerc7fc81e2017-12-30 15:27:33 +0000154 for (PHINode &PN : BB->phis())
155 if (PN.getIncomingValue(0) != &PN)
156 IncomingValues.push_back(PN.getIncomingValue(0));
Chandler Carruth96ada252015-07-22 09:52:54 +0000157 FoldSingleEntryPHINodes(BB, MemDep);
Adrian Prantld60f34c2017-11-01 20:43:30 +0000158 }
Jakub Staszak190db2f2013-01-14 23:16:36 +0000159
Owen Andersonc0623812008-07-17 00:01:40 +0000160 // Delete the unconditional branch from the predecessor...
161 PredBB->getInstList().pop_back();
Jakub Staszak190db2f2013-01-14 23:16:36 +0000162
Owen Andersonc0623812008-07-17 00:01:40 +0000163 // Make all PHI nodes that referred to BB now refer to Pred as their
164 // source...
165 BB->replaceAllUsesWith(PredBB);
Jakub Staszak190db2f2013-01-14 23:16:36 +0000166
Jay Foad61ea0e42011-06-23 09:09:15 +0000167 // Move all definitions in the successor to the predecessor...
168 PredBB->getInstList().splice(PredBB->end(), BB->getInstList());
Jakub Staszak190db2f2013-01-14 23:16:36 +0000169
Adrian Prantld60f34c2017-11-01 20:43:30 +0000170 // Eliminate duplicate dbg.values describing the entry PHI node post-splice.
171 for (auto *Incoming : IncomingValues) {
172 if (isa<Instruction>(Incoming)) {
173 SmallVector<DbgValueInst *, 2> DbgValues;
174 SmallDenseSet<std::pair<DILocalVariable *, DIExpression *>, 2>
175 DbgValueSet;
176 llvm::findDbgValues(DbgValues, Incoming);
177 for (auto &DVI : DbgValues) {
178 auto R = DbgValueSet.insert({DVI->getVariable(), DVI->getExpression()});
179 if (!R.second)
180 DVI->eraseFromParent();
181 }
182 }
183 }
184
Dan Gohman2d02ff82009-10-31 17:33:01 +0000185 // Inherit predecessors name if it exists.
Owen Anderson27405ef2008-07-17 19:42:29 +0000186 if (!PredBB->hasName())
187 PredBB->takeName(BB);
Jakub Staszak190db2f2013-01-14 23:16:36 +0000188
Owen Andersonc0623812008-07-17 00:01:40 +0000189 // Finally, erase the old block and update dominator info.
Chandler Carruthb5c11532015-01-18 02:11:23 +0000190 if (DT)
191 if (DomTreeNode *DTN = DT->getNode(BB)) {
192 DomTreeNode *PredDTN = DT->getNode(PredBB);
193 SmallVector<DomTreeNode *, 8> Children(DTN->begin(), DTN->end());
Benjamin Kramer135f7352016-06-26 12:28:59 +0000194 for (DomTreeNode *DI : Children)
195 DT->changeImmediateDominator(DI, PredDTN);
Owen Andersonc0623812008-07-17 00:01:40 +0000196
Chandler Carruthb5c11532015-01-18 02:11:23 +0000197 DT->eraseNode(BB);
Owen Andersonc0623812008-07-17 00:01:40 +0000198 }
Chandler Carruthb5c11532015-01-18 02:11:23 +0000199
200 if (LI)
201 LI->removeBlock(BB);
202
203 if (MemDep)
204 MemDep->invalidateCachedPredecessors();
Jakub Staszak190db2f2013-01-14 23:16:36 +0000205
Owen Andersonc0623812008-07-17 00:01:40 +0000206 BB->eraseFromParent();
Dan Gohman2d02ff82009-10-31 17:33:01 +0000207 return true;
Owen Andersonc0623812008-07-17 00:01:40 +0000208}
209
Chris Lattnerdf3c3422004-01-09 06:12:26 +0000210void llvm::ReplaceInstWithValue(BasicBlock::InstListType &BIL,
211 BasicBlock::iterator &BI, Value *V) {
Chris Lattnerfda72b12002-06-25 16:12:52 +0000212 Instruction &I = *BI;
Chris Lattner28537df2002-05-07 18:07:59 +0000213 // Replaces all of the uses of the instruction with uses of the value
Chris Lattnerfda72b12002-06-25 16:12:52 +0000214 I.replaceAllUsesWith(V);
Chris Lattner28537df2002-05-07 18:07:59 +0000215
Chris Lattner8dd4cae2007-02-11 01:37:51 +0000216 // Make sure to propagate a name if there is one already.
217 if (I.hasName() && !V->hasName())
218 V->takeName(&I);
Misha Brukmanb1c93172005-04-21 23:48:37 +0000219
Misha Brukman7eb05a12003-08-18 14:43:39 +0000220 // Delete the unnecessary instruction now...
Chris Lattnerfda72b12002-06-25 16:12:52 +0000221 BI = BIL.erase(BI);
Chris Lattner28537df2002-05-07 18:07:59 +0000222}
223
Chris Lattnerdf3c3422004-01-09 06:12:26 +0000224void llvm::ReplaceInstWithInst(BasicBlock::InstListType &BIL,
225 BasicBlock::iterator &BI, Instruction *I) {
Craig Toppere73658d2014-04-28 04:05:08 +0000226 assert(I->getParent() == nullptr &&
Chris Lattner28537df2002-05-07 18:07:59 +0000227 "ReplaceInstWithInst: Instruction already inserted into basic block!");
228
Alexey Samsonov19ffcb92015-06-23 21:00:08 +0000229 // Copy debug location to newly added instruction, if it wasn't already set
230 // by the caller.
231 if (!I->getDebugLoc())
232 I->setDebugLoc(BI->getDebugLoc());
233
Chris Lattner28537df2002-05-07 18:07:59 +0000234 // Insert the new instruction into the basic block...
Chris Lattnerfda72b12002-06-25 16:12:52 +0000235 BasicBlock::iterator New = BIL.insert(BI, I);
Chris Lattner28537df2002-05-07 18:07:59 +0000236
237 // Replace all uses of the old instruction, and delete it.
238 ReplaceInstWithValue(BIL, BI, I);
239
240 // Move BI back to point to the newly inserted instruction
Chris Lattnerfda72b12002-06-25 16:12:52 +0000241 BI = New;
Chris Lattner28537df2002-05-07 18:07:59 +0000242}
243
Chris Lattnerdf3c3422004-01-09 06:12:26 +0000244void llvm::ReplaceInstWithInst(Instruction *From, Instruction *To) {
Chris Lattnerfda72b12002-06-25 16:12:52 +0000245 BasicBlock::iterator BI(From);
246 ReplaceInstWithInst(From->getParent()->getInstList(), BI, To);
Chris Lattner28537df2002-05-07 18:07:59 +0000247}
Chris Lattnerb17274e2002-07-29 22:32:08 +0000248
Chandler Carruthd4500562015-01-19 12:36:53 +0000249BasicBlock *llvm::SplitEdge(BasicBlock *BB, BasicBlock *Succ, DominatorTree *DT,
250 LoopInfo *LI) {
Bob Wilsonaff96b22010-02-16 21:06:42 +0000251 unsigned SuccNum = GetSuccessorNumber(BB, Succ);
Jakub Staszak190db2f2013-01-14 23:16:36 +0000252
Chandler Carruth37df2cf2015-01-19 12:09:11 +0000253 // If this is a critical edge, let SplitCriticalEdge do it.
254 TerminatorInst *LatchTerm = BB->getTerminator();
Chandler Carruthd4500562015-01-19 12:36:53 +0000255 if (SplitCriticalEdge(LatchTerm, SuccNum, CriticalEdgeSplittingOptions(DT, LI)
256 .setPreserveLCSSA()))
Chandler Carruth37df2cf2015-01-19 12:09:11 +0000257 return LatchTerm->getSuccessor(SuccNum);
Chandler Carruth32c52c72015-01-18 02:39:37 +0000258
Devang Pateld7767cc2007-07-06 21:39:20 +0000259 // If the edge isn't critical, then BB has a single successor or Succ has a
260 // single pred. Split the block.
Devang Pateld7767cc2007-07-06 21:39:20 +0000261 if (BasicBlock *SP = Succ->getSinglePredecessor()) {
262 // If the successor only has a single pred, split the top of the successor
263 // block.
264 assert(SP == BB && "CFG broken");
Craig Topperf40110f2014-04-25 05:29:35 +0000265 SP = nullptr;
Duncan P. N. Exon Smith5b4c8372015-10-13 02:39:05 +0000266 return SplitBlock(Succ, &Succ->front(), DT, LI);
Devang Pateld7767cc2007-07-06 21:39:20 +0000267 }
Jakub Staszak190db2f2013-01-14 23:16:36 +0000268
Chris Lattner30d95f92011-01-08 18:47:43 +0000269 // Otherwise, if BB has a single successor, split it at the bottom of the
270 // block.
271 assert(BB->getTerminator()->getNumSuccessors() == 1 &&
Jakub Staszak190db2f2013-01-14 23:16:36 +0000272 "Should have a single succ!");
Chandler Carruth32c52c72015-01-18 02:39:37 +0000273 return SplitBlock(BB, BB->getTerminator(), DT, LI);
Devang Pateld7767cc2007-07-06 21:39:20 +0000274}
275
Chandler Carruth37df2cf2015-01-19 12:09:11 +0000276unsigned
277llvm::SplitAllCriticalEdges(Function &F,
278 const CriticalEdgeSplittingOptions &Options) {
Kostya Serebryanye5ea4242014-11-19 00:17:31 +0000279 unsigned NumBroken = 0;
Benjamin Kramer135f7352016-06-26 12:28:59 +0000280 for (BasicBlock &BB : F) {
281 TerminatorInst *TI = BB.getTerminator();
Kostya Serebryanye5ea4242014-11-19 00:17:31 +0000282 if (TI->getNumSuccessors() > 1 && !isa<IndirectBrInst>(TI))
283 for (unsigned i = 0, e = TI->getNumSuccessors(); i != e; ++i)
Chandler Carruth37df2cf2015-01-19 12:09:11 +0000284 if (SplitCriticalEdge(TI, i, Options))
Kostya Serebryanye5ea4242014-11-19 00:17:31 +0000285 ++NumBroken;
286 }
287 return NumBroken;
288}
289
Chandler Carruth32c52c72015-01-18 02:39:37 +0000290BasicBlock *llvm::SplitBlock(BasicBlock *Old, Instruction *SplitPt,
291 DominatorTree *DT, LoopInfo *LI) {
Duncan P. N. Exon Smith5b4c8372015-10-13 02:39:05 +0000292 BasicBlock::iterator SplitIt = SplitPt->getIterator();
David Majnemer654e1302015-07-31 17:58:14 +0000293 while (isa<PHINode>(SplitIt) || SplitIt->isEHPad())
Devang Pateld7767cc2007-07-06 21:39:20 +0000294 ++SplitIt;
295 BasicBlock *New = Old->splitBasicBlock(SplitIt, Old->getName()+".split");
296
Dan Gohman3ddbc242009-09-08 15:45:00 +0000297 // The new block lives in whichever loop the old one did. This preserves
298 // LCSSA as well, because we force the split point to be after any PHI nodes.
Chandler Carruth32c52c72015-01-18 02:39:37 +0000299 if (LI)
300 if (Loop *L = LI->getLoopFor(Old))
301 L->addBasicBlockToLoop(New, *LI);
Devang Pateld7767cc2007-07-06 21:39:20 +0000302
Chandler Carruth32c52c72015-01-18 02:39:37 +0000303 if (DT)
Gabor Greif2f5f6962010-09-10 22:25:58 +0000304 // Old dominates New. New node dominates all other nodes dominated by Old.
Chandler Carruth32c52c72015-01-18 02:39:37 +0000305 if (DomTreeNode *OldNode = DT->getNode(Old)) {
Benjamin Kramer135f7352016-06-26 12:28:59 +0000306 std::vector<DomTreeNode *> Children(OldNode->begin(), OldNode->end());
Devang Patel186e0d82007-07-19 02:29:24 +0000307
Chandler Carruth32c52c72015-01-18 02:39:37 +0000308 DomTreeNode *NewNode = DT->addNewBlock(New, Old);
Benjamin Kramer135f7352016-06-26 12:28:59 +0000309 for (DomTreeNode *I : Children)
310 DT->changeImmediateDominator(I, NewNode);
Rafael Espindolad3e65e72011-08-24 18:07:01 +0000311 }
Devang Pateld7767cc2007-07-06 21:39:20 +0000312
Devang Pateld7767cc2007-07-06 21:39:20 +0000313 return New;
314}
Chris Lattnera5b11702008-04-21 01:28:02 +0000315
Sanjay Patel85ce0f12016-04-23 16:31:48 +0000316/// Update DominatorTree, LoopInfo, and LCCSA analysis information.
Bill Wendling60291352011-08-18 17:57:57 +0000317static void UpdateAnalysisInformation(BasicBlock *OldBB, BasicBlock *NewBB,
Bill Wendlingec3823d2011-08-18 20:39:32 +0000318 ArrayRef<BasicBlock *> Preds,
Chandler Carruthb5797b62015-01-18 09:21:15 +0000319 DominatorTree *DT, LoopInfo *LI,
320 bool PreserveLCSSA, bool &HasLoopExit) {
321 // Update dominator tree if available.
322 if (DT)
323 DT->splitBlock(NewBB);
Bill Wendling0a693f42011-08-18 05:25:23 +0000324
Chandler Carruthb5797b62015-01-18 09:21:15 +0000325 // The rest of the logic is only relevant for updating the loop structures.
326 if (!LI)
327 return;
328
Anna Thomas9fca5832018-01-04 17:21:15 +0000329 assert(DT && "DT should be available to update LoopInfo!");
Chandler Carruthb5797b62015-01-18 09:21:15 +0000330 Loop *L = LI->getLoopFor(OldBB);
Bill Wendling0a693f42011-08-18 05:25:23 +0000331
332 // If we need to preserve loop analyses, collect some information about how
333 // this split will affect loops.
334 bool IsLoopEntry = !!L;
335 bool SplitMakesNewLoopHeader = false;
Benjamin Kramer135f7352016-06-26 12:28:59 +0000336 for (BasicBlock *Pred : Preds) {
Anna Thomasbdb94302018-01-02 16:25:50 +0000337 // Preds that are not reachable from entry should not be used to identify if
338 // OldBB is a loop entry or if SplitMakesNewLoopHeader. Unreachable blocks
339 // are not within any loops, so we incorrectly mark SplitMakesNewLoopHeader
340 // as true and make the NewBB the header of some loop. This breaks LI.
341 if (!DT->isReachableFromEntry(Pred))
342 continue;
Chandler Carruthb5797b62015-01-18 09:21:15 +0000343 // If we need to preserve LCSSA, determine if any of the preds is a loop
344 // exit.
345 if (PreserveLCSSA)
346 if (Loop *PL = LI->getLoopFor(Pred))
347 if (!PL->contains(OldBB))
348 HasLoopExit = true;
Bill Wendling0a693f42011-08-18 05:25:23 +0000349
Chandler Carruthb5797b62015-01-18 09:21:15 +0000350 // If we need to preserve LoopInfo, note whether any of the preds crosses
351 // an interesting loop boundary.
352 if (!L)
353 continue;
354 if (L->contains(Pred))
355 IsLoopEntry = false;
356 else
357 SplitMakesNewLoopHeader = true;
Bill Wendling0a693f42011-08-18 05:25:23 +0000358 }
359
Chandler Carruthb5797b62015-01-18 09:21:15 +0000360 // Unless we have a loop for OldBB, nothing else to do here.
361 if (!L)
362 return;
Bill Wendling0a693f42011-08-18 05:25:23 +0000363
364 if (IsLoopEntry) {
365 // Add the new block to the nearest enclosing loop (and not an adjacent
366 // loop). To find this, examine each of the predecessors and determine which
367 // loops enclose them, and select the most-nested loop which contains the
368 // loop containing the block being split.
Craig Topperf40110f2014-04-25 05:29:35 +0000369 Loop *InnermostPredLoop = nullptr;
Benjamin Kramer135f7352016-06-26 12:28:59 +0000370 for (BasicBlock *Pred : Preds) {
Bill Wendlingec3823d2011-08-18 20:39:32 +0000371 if (Loop *PredLoop = LI->getLoopFor(Pred)) {
Bill Wendling0a693f42011-08-18 05:25:23 +0000372 // Seek a loop which actually contains the block being split (to avoid
373 // adjacent loops).
374 while (PredLoop && !PredLoop->contains(OldBB))
375 PredLoop = PredLoop->getParentLoop();
376
377 // Select the most-nested of these loops which contains the block.
378 if (PredLoop && PredLoop->contains(OldBB) &&
379 (!InnermostPredLoop ||
380 InnermostPredLoop->getLoopDepth() < PredLoop->getLoopDepth()))
381 InnermostPredLoop = PredLoop;
382 }
Bill Wendlingec3823d2011-08-18 20:39:32 +0000383 }
Bill Wendling0a693f42011-08-18 05:25:23 +0000384
385 if (InnermostPredLoop)
Chandler Carruth691addc2015-01-18 01:25:51 +0000386 InnermostPredLoop->addBasicBlockToLoop(NewBB, *LI);
Bill Wendling0a693f42011-08-18 05:25:23 +0000387 } else {
Chandler Carruth691addc2015-01-18 01:25:51 +0000388 L->addBasicBlockToLoop(NewBB, *LI);
Bill Wendling0a693f42011-08-18 05:25:23 +0000389 if (SplitMakesNewLoopHeader)
390 L->moveToHeader(NewBB);
391 }
392}
393
Sanjay Patel85ce0f12016-04-23 16:31:48 +0000394/// Update the PHI nodes in OrigBB to include the values coming from NewBB.
395/// This also updates AliasAnalysis, if available.
Bill Wendlingb267e2a2011-08-18 20:51:04 +0000396static void UpdatePHINodes(BasicBlock *OrigBB, BasicBlock *NewBB,
Chandler Carruthb5797b62015-01-18 09:21:15 +0000397 ArrayRef<BasicBlock *> Preds, BranchInst *BI,
Chandler Carruth96ada252015-07-22 09:52:54 +0000398 bool HasLoopExit) {
Bill Wendlingb267e2a2011-08-18 20:51:04 +0000399 // Otherwise, create a new PHI node in NewBB for each PHI node in OrigBB.
Chandler Carruth5bdf72c2014-04-28 10:37:30 +0000400 SmallPtrSet<BasicBlock *, 16> PredSet(Preds.begin(), Preds.end());
Bill Wendlingb267e2a2011-08-18 20:51:04 +0000401 for (BasicBlock::iterator I = OrigBB->begin(); isa<PHINode>(I); ) {
402 PHINode *PN = cast<PHINode>(I++);
403
404 // Check to see if all of the values coming in are the same. If so, we
405 // don't need to create a new PHI node, unless it's needed for LCSSA.
Craig Topperf40110f2014-04-25 05:29:35 +0000406 Value *InVal = nullptr;
Bill Wendlingb267e2a2011-08-18 20:51:04 +0000407 if (!HasLoopExit) {
408 InVal = PN->getIncomingValueForBlock(Preds[0]);
Chandler Carruth5bdf72c2014-04-28 10:37:30 +0000409 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) {
410 if (!PredSet.count(PN->getIncomingBlock(i)))
411 continue;
412 if (!InVal)
413 InVal = PN->getIncomingValue(i);
414 else if (InVal != PN->getIncomingValue(i)) {
Craig Topperf40110f2014-04-25 05:29:35 +0000415 InVal = nullptr;
Bill Wendlingb267e2a2011-08-18 20:51:04 +0000416 break;
417 }
Chandler Carruth5bdf72c2014-04-28 10:37:30 +0000418 }
Bill Wendlingb267e2a2011-08-18 20:51:04 +0000419 }
420
421 if (InVal) {
422 // If all incoming values for the new PHI would be the same, just don't
423 // make a new PHI. Instead, just remove the incoming values from the old
424 // PHI.
Jakub Staszak190db2f2013-01-14 23:16:36 +0000425
Chandler Carruth5bdf72c2014-04-28 10:37:30 +0000426 // NOTE! This loop walks backwards for a reason! First off, this minimizes
427 // the cost of removal if we end up removing a large number of values, and
428 // second off, this ensures that the indices for the incoming values
429 // aren't invalidated when we remove one.
430 for (int64_t i = PN->getNumIncomingValues() - 1; i >= 0; --i)
431 if (PredSet.count(PN->getIncomingBlock(i)))
432 PN->removeIncomingValue(i, false);
Bill Wendlingb267e2a2011-08-18 20:51:04 +0000433
Chandler Carruth5bdf72c2014-04-28 10:37:30 +0000434 // Add an incoming value to the PHI node in the loop for the preheader
435 // edge.
436 PN->addIncoming(InVal, NewBB);
437 continue;
Bill Wendlingb267e2a2011-08-18 20:51:04 +0000438 }
439
Chandler Carruth5bdf72c2014-04-28 10:37:30 +0000440 // If the values coming into the block are not the same, we need a new
441 // PHI.
442 // Create the new PHI node, insert it into NewBB at the end of the block
443 PHINode *NewPHI =
444 PHINode::Create(PN->getType(), Preds.size(), PN->getName() + ".ph", BI);
Chandler Carruth5bdf72c2014-04-28 10:37:30 +0000445
446 // NOTE! This loop walks backwards for a reason! First off, this minimizes
447 // the cost of removal if we end up removing a large number of values, and
448 // second off, this ensures that the indices for the incoming values aren't
449 // invalidated when we remove one.
450 for (int64_t i = PN->getNumIncomingValues() - 1; i >= 0; --i) {
451 BasicBlock *IncomingBB = PN->getIncomingBlock(i);
452 if (PredSet.count(IncomingBB)) {
453 Value *V = PN->removeIncomingValue(i, false);
454 NewPHI->addIncoming(V, IncomingBB);
455 }
456 }
457
458 PN->addIncoming(NewPHI, NewBB);
Bill Wendlingb267e2a2011-08-18 20:51:04 +0000459 }
460}
461
Jakub Staszak190db2f2013-01-14 23:16:36 +0000462BasicBlock *llvm::SplitBlockPredecessors(BasicBlock *BB,
Chandler Carruthb5797b62015-01-18 09:21:15 +0000463 ArrayRef<BasicBlock *> Preds,
Chandler Carruth96ada252015-07-22 09:52:54 +0000464 const char *Suffix, DominatorTree *DT,
465 LoopInfo *LI, bool PreserveLCSSA) {
David Majnemer654e1302015-07-31 17:58:14 +0000466 // Do not attempt to split that which cannot be split.
467 if (!BB->canSplitPredecessors())
468 return nullptr;
469
Philip Reames9198b332015-01-28 23:06:47 +0000470 // For the landingpads we need to act a bit differently.
471 // Delegate this work to the SplitLandingPadPredecessors.
472 if (BB->isLandingPad()) {
473 SmallVector<BasicBlock*, 2> NewBBs;
474 std::string NewName = std::string(Suffix) + ".split-lp";
475
Chandler Carruth96ada252015-07-22 09:52:54 +0000476 SplitLandingPadPredecessors(BB, Preds, Suffix, NewName.c_str(), NewBBs, DT,
477 LI, PreserveLCSSA);
Philip Reames9198b332015-01-28 23:06:47 +0000478 return NewBBs[0];
479 }
480
Chris Lattnera5b11702008-04-21 01:28:02 +0000481 // Create new basic block, insert right before the original block.
Alexey Samsonovb7f02d32015-06-09 22:10:29 +0000482 BasicBlock *NewBB = BasicBlock::Create(
483 BB->getContext(), BB->getName() + Suffix, BB->getParent(), BB);
Jakub Staszak190db2f2013-01-14 23:16:36 +0000484
Chris Lattnera5b11702008-04-21 01:28:02 +0000485 // The new block unconditionally branches to the old block.
486 BranchInst *BI = BranchInst::Create(BB, NewBB);
Taewook Oh2e945eb2017-02-14 21:10:40 +0000487 BI->setDebugLoc(BB->getFirstNonPHIOrDbg()->getDebugLoc());
Jakub Staszak190db2f2013-01-14 23:16:36 +0000488
Chris Lattnera5b11702008-04-21 01:28:02 +0000489 // Move the edges from Preds to point to NewBB instead of BB.
Jakub Staszakf5b32e52011-12-09 21:19:53 +0000490 for (unsigned i = 0, e = Preds.size(); i != e; ++i) {
Dan Gohman00c79382009-11-05 18:25:44 +0000491 // This is slightly more strict than necessary; the minimum requirement
492 // is that there be no more than one indirectbr branching to BB. And
493 // all BlockAddress uses would need to be updated.
494 assert(!isa<IndirectBrInst>(Preds[i]->getTerminator()) &&
495 "Cannot split an edge from an IndirectBrInst");
Chris Lattnera5b11702008-04-21 01:28:02 +0000496 Preds[i]->getTerminator()->replaceUsesOfWith(BB, NewBB);
Dan Gohman3ddbc242009-09-08 15:45:00 +0000497 }
498
Chris Lattnera5b11702008-04-21 01:28:02 +0000499 // Insert a new PHI node into NewBB for every PHI node in BB and that new PHI
500 // node becomes an incoming value for BB's phi node. However, if the Preds
501 // list is empty, we need to insert dummy entries into the PHI nodes in BB to
502 // account for the newly created predecessor.
Eugene Zelenko57bd5a02017-10-27 01:09:08 +0000503 if (Preds.empty()) {
Chris Lattnera5b11702008-04-21 01:28:02 +0000504 // Insert dummy values as the incoming value.
505 for (BasicBlock::iterator I = BB->begin(); isa<PHINode>(I); ++I)
Owen Andersonb292b8c2009-07-30 23:03:37 +0000506 cast<PHINode>(I)->addIncoming(UndefValue::get(I->getType()), NewBB);
Chris Lattnera5b11702008-04-21 01:28:02 +0000507 return NewBB;
508 }
Dan Gohman3ddbc242009-09-08 15:45:00 +0000509
Bill Wendling0a693f42011-08-18 05:25:23 +0000510 // Update DominatorTree, LoopInfo, and LCCSA analysis information.
511 bool HasLoopExit = false;
Chandler Carruthb5797b62015-01-18 09:21:15 +0000512 UpdateAnalysisInformation(BB, NewBB, Preds, DT, LI, PreserveLCSSA,
513 HasLoopExit);
Dan Gohman3ddbc242009-09-08 15:45:00 +0000514
Bill Wendlingb267e2a2011-08-18 20:51:04 +0000515 // Update the PHI nodes in BB with the values coming from NewBB.
Chandler Carruth96ada252015-07-22 09:52:54 +0000516 UpdatePHINodes(BB, NewBB, Preds, BI, HasLoopExit);
Chris Lattnera5b11702008-04-21 01:28:02 +0000517 return NewBB;
518}
Chris Lattner72f16e72008-11-27 08:10:05 +0000519
Bill Wendlingca7d3092011-08-19 00:05:40 +0000520void llvm::SplitLandingPadPredecessors(BasicBlock *OrigBB,
Chandler Carruth0eae1122015-01-19 03:03:39 +0000521 ArrayRef<BasicBlock *> Preds,
Bill Wendlingca7d3092011-08-19 00:05:40 +0000522 const char *Suffix1, const char *Suffix2,
Chandler Carruth0eae1122015-01-19 03:03:39 +0000523 SmallVectorImpl<BasicBlock *> &NewBBs,
Chandler Carruth96ada252015-07-22 09:52:54 +0000524 DominatorTree *DT, LoopInfo *LI,
525 bool PreserveLCSSA) {
Bill Wendlingca7d3092011-08-19 00:05:40 +0000526 assert(OrigBB->isLandingPad() && "Trying to split a non-landing pad!");
527
528 // Create a new basic block for OrigBB's predecessors listed in Preds. Insert
529 // it right before the original block.
530 BasicBlock *NewBB1 = BasicBlock::Create(OrigBB->getContext(),
531 OrigBB->getName() + Suffix1,
532 OrigBB->getParent(), OrigBB);
533 NewBBs.push_back(NewBB1);
534
535 // The new block unconditionally branches to the old block.
536 BranchInst *BI1 = BranchInst::Create(OrigBB, NewBB1);
Alexey Samsonovb7f02d32015-06-09 22:10:29 +0000537 BI1->setDebugLoc(OrigBB->getFirstNonPHI()->getDebugLoc());
Bill Wendlingca7d3092011-08-19 00:05:40 +0000538
539 // Move the edges from Preds to point to NewBB1 instead of OrigBB.
540 for (unsigned i = 0, e = Preds.size(); i != e; ++i) {
541 // This is slightly more strict than necessary; the minimum requirement
542 // is that there be no more than one indirectbr branching to BB. And
543 // all BlockAddress uses would need to be updated.
544 assert(!isa<IndirectBrInst>(Preds[i]->getTerminator()) &&
545 "Cannot split an edge from an IndirectBrInst");
546 Preds[i]->getTerminator()->replaceUsesOfWith(OrigBB, NewBB1);
547 }
548
Bill Wendlingca7d3092011-08-19 00:05:40 +0000549 bool HasLoopExit = false;
Chandler Carruthb5797b62015-01-18 09:21:15 +0000550 UpdateAnalysisInformation(OrigBB, NewBB1, Preds, DT, LI, PreserveLCSSA,
551 HasLoopExit);
Bill Wendlingca7d3092011-08-19 00:05:40 +0000552
553 // Update the PHI nodes in OrigBB with the values coming from NewBB1.
Chandler Carruth96ada252015-07-22 09:52:54 +0000554 UpdatePHINodes(OrigBB, NewBB1, Preds, BI1, HasLoopExit);
Bill Wendlingca7d3092011-08-19 00:05:40 +0000555
Bill Wendlingca7d3092011-08-19 00:05:40 +0000556 // Move the remaining edges from OrigBB to point to NewBB2.
557 SmallVector<BasicBlock*, 8> NewBB2Preds;
Duncan P. N. Exon Smith6c990152014-07-21 17:06:51 +0000558 for (pred_iterator i = pred_begin(OrigBB), e = pred_end(OrigBB);
559 i != e; ) {
560 BasicBlock *Pred = *i++;
Bill Wendling38d81302011-08-19 23:46:30 +0000561 if (Pred == NewBB1) continue;
Bill Wendlingca7d3092011-08-19 00:05:40 +0000562 assert(!isa<IndirectBrInst>(Pred->getTerminator()) &&
563 "Cannot split an edge from an IndirectBrInst");
Bill Wendlingca7d3092011-08-19 00:05:40 +0000564 NewBB2Preds.push_back(Pred);
Duncan P. N. Exon Smith6c990152014-07-21 17:06:51 +0000565 e = pred_end(OrigBB);
Bill Wendlingca7d3092011-08-19 00:05:40 +0000566 }
567
Craig Topperf40110f2014-04-25 05:29:35 +0000568 BasicBlock *NewBB2 = nullptr;
Bill Wendling38d81302011-08-19 23:46:30 +0000569 if (!NewBB2Preds.empty()) {
570 // Create another basic block for the rest of OrigBB's predecessors.
571 NewBB2 = BasicBlock::Create(OrigBB->getContext(),
572 OrigBB->getName() + Suffix2,
573 OrigBB->getParent(), OrigBB);
574 NewBBs.push_back(NewBB2);
Bill Wendlingca7d3092011-08-19 00:05:40 +0000575
Bill Wendling38d81302011-08-19 23:46:30 +0000576 // The new block unconditionally branches to the old block.
577 BranchInst *BI2 = BranchInst::Create(OrigBB, NewBB2);
Alexey Samsonovb7f02d32015-06-09 22:10:29 +0000578 BI2->setDebugLoc(OrigBB->getFirstNonPHI()->getDebugLoc());
Bill Wendling38d81302011-08-19 23:46:30 +0000579
580 // Move the remaining edges from OrigBB to point to NewBB2.
Benjamin Kramer135f7352016-06-26 12:28:59 +0000581 for (BasicBlock *NewBB2Pred : NewBB2Preds)
582 NewBB2Pred->getTerminator()->replaceUsesOfWith(OrigBB, NewBB2);
Bill Wendling38d81302011-08-19 23:46:30 +0000583
584 // Update DominatorTree, LoopInfo, and LCCSA analysis information.
585 HasLoopExit = false;
Chandler Carruthb5797b62015-01-18 09:21:15 +0000586 UpdateAnalysisInformation(OrigBB, NewBB2, NewBB2Preds, DT, LI,
587 PreserveLCSSA, HasLoopExit);
Bill Wendling38d81302011-08-19 23:46:30 +0000588
589 // Update the PHI nodes in OrigBB with the values coming from NewBB2.
Chandler Carruth96ada252015-07-22 09:52:54 +0000590 UpdatePHINodes(OrigBB, NewBB2, NewBB2Preds, BI2, HasLoopExit);
Bill Wendling38d81302011-08-19 23:46:30 +0000591 }
Bill Wendlingca7d3092011-08-19 00:05:40 +0000592
593 LandingPadInst *LPad = OrigBB->getLandingPadInst();
594 Instruction *Clone1 = LPad->clone();
595 Clone1->setName(Twine("lpad") + Suffix1);
596 NewBB1->getInstList().insert(NewBB1->getFirstInsertionPt(), Clone1);
597
Bill Wendling38d81302011-08-19 23:46:30 +0000598 if (NewBB2) {
599 Instruction *Clone2 = LPad->clone();
600 Clone2->setName(Twine("lpad") + Suffix2);
601 NewBB2->getInstList().insert(NewBB2->getFirstInsertionPt(), Clone2);
Bill Wendlingca7d3092011-08-19 00:05:40 +0000602
Chen Li78bde832016-01-06 20:32:05 +0000603 // Create a PHI node for the two cloned landingpad instructions only
604 // if the original landingpad instruction has some uses.
605 if (!LPad->use_empty()) {
606 assert(!LPad->getType()->isTokenTy() &&
607 "Split cannot be applied if LPad is token type. Otherwise an "
608 "invalid PHINode of token type would be created.");
609 PHINode *PN = PHINode::Create(LPad->getType(), 2, "lpad.phi", LPad);
610 PN->addIncoming(Clone1, NewBB1);
611 PN->addIncoming(Clone2, NewBB2);
612 LPad->replaceAllUsesWith(PN);
613 }
Bill Wendling38d81302011-08-19 23:46:30 +0000614 LPad->eraseFromParent();
615 } else {
616 // There is no second clone. Just replace the landing pad with the first
617 // clone.
618 LPad->replaceAllUsesWith(Clone1);
619 LPad->eraseFromParent();
620 }
Bill Wendlingca7d3092011-08-19 00:05:40 +0000621}
622
Evan Chengd983eba2011-01-29 04:46:23 +0000623ReturnInst *llvm::FoldReturnIntoUncondBranch(ReturnInst *RI, BasicBlock *BB,
624 BasicBlock *Pred) {
625 Instruction *UncondBranch = Pred->getTerminator();
626 // Clone the return and add it to the end of the predecessor.
627 Instruction *NewRet = RI->clone();
628 Pred->getInstList().push_back(NewRet);
Jakub Staszak190db2f2013-01-14 23:16:36 +0000629
Evan Chengd983eba2011-01-29 04:46:23 +0000630 // If the return instruction returns a value, and if the value was a
631 // PHI node in "BB", propagate the right value into the return.
632 for (User::op_iterator i = NewRet->op_begin(), e = NewRet->op_end();
Evan Cheng249716e2012-07-27 21:21:26 +0000633 i != e; ++i) {
634 Value *V = *i;
Craig Topperf40110f2014-04-25 05:29:35 +0000635 Instruction *NewBC = nullptr;
Evan Cheng249716e2012-07-27 21:21:26 +0000636 if (BitCastInst *BCI = dyn_cast<BitCastInst>(V)) {
637 // Return value might be bitcasted. Clone and insert it before the
638 // return instruction.
639 V = BCI->getOperand(0);
640 NewBC = BCI->clone();
Duncan P. N. Exon Smith5b4c8372015-10-13 02:39:05 +0000641 Pred->getInstList().insert(NewRet->getIterator(), NewBC);
Evan Cheng249716e2012-07-27 21:21:26 +0000642 *i = NewBC;
643 }
644 if (PHINode *PN = dyn_cast<PHINode>(V)) {
645 if (PN->getParent() == BB) {
646 if (NewBC)
647 NewBC->setOperand(0, PN->getIncomingValueForBlock(Pred));
648 else
649 *i = PN->getIncomingValueForBlock(Pred);
650 }
651 }
652 }
Jakub Staszak190db2f2013-01-14 23:16:36 +0000653
Evan Chengd983eba2011-01-29 04:46:23 +0000654 // Update any PHI nodes in the returning block to realize that we no
655 // longer branch to them.
656 BB->removePredecessor(Pred);
657 UncondBranch->eraseFromParent();
658 return cast<ReturnInst>(NewRet);
Chris Lattner351134b2009-05-04 02:25:58 +0000659}
Devang Patela8e74112011-04-29 22:28:59 +0000660
Adam Nemetfdb20592016-03-15 18:06:20 +0000661TerminatorInst *
662llvm::SplitBlockAndInsertIfThen(Value *Cond, Instruction *SplitBefore,
663 bool Unreachable, MDNode *BranchWeights,
664 DominatorTree *DT, LoopInfo *LI) {
Evgeniy Stepanov8eb77d82012-10-19 10:48:31 +0000665 BasicBlock *Head = SplitBefore->getParent();
Duncan P. N. Exon Smith5b4c8372015-10-13 02:39:05 +0000666 BasicBlock *Tail = Head->splitBasicBlock(SplitBefore->getIterator());
Evgeniy Stepanov8eb77d82012-10-19 10:48:31 +0000667 TerminatorInst *HeadOldTerm = Head->getTerminator();
668 LLVMContext &C = Head->getContext();
669 BasicBlock *ThenBlock = BasicBlock::Create(C, "", Head->getParent(), Tail);
670 TerminatorInst *CheckTerm;
671 if (Unreachable)
672 CheckTerm = new UnreachableInst(C, ThenBlock);
673 else
674 CheckTerm = BranchInst::Create(Tail, ThenBlock);
Evgeniy Stepanov2275a012014-03-19 12:56:38 +0000675 CheckTerm->setDebugLoc(SplitBefore->getDebugLoc());
Evgeniy Stepanov8eb77d82012-10-19 10:48:31 +0000676 BranchInst *HeadNewTerm =
Evgeniy Stepanova9164e92013-12-19 13:29:56 +0000677 BranchInst::Create(/*ifTrue*/ThenBlock, /*ifFalse*/Tail, Cond);
Evgeniy Stepanov8eb77d82012-10-19 10:48:31 +0000678 HeadNewTerm->setMetadata(LLVMContext::MD_prof, BranchWeights);
679 ReplaceInstWithInst(HeadOldTerm, HeadNewTerm);
Peter Collingbourne818f5c42014-07-15 04:40:27 +0000680
681 if (DT) {
682 if (DomTreeNode *OldNode = DT->getNode(Head)) {
683 std::vector<DomTreeNode *> Children(OldNode->begin(), OldNode->end());
684
685 DomTreeNode *NewNode = DT->addNewBlock(Tail, Head);
Benjamin Kramer135f7352016-06-26 12:28:59 +0000686 for (DomTreeNode *Child : Children)
Peter Collingbourne818f5c42014-07-15 04:40:27 +0000687 DT->changeImmediateDominator(Child, NewNode);
688
689 // Head dominates ThenBlock.
690 DT->addNewBlock(ThenBlock, Head);
691 }
692 }
693
Adam Nemetfdb20592016-03-15 18:06:20 +0000694 if (LI) {
Michael Kruse811de8a2017-03-06 15:33:05 +0000695 if (Loop *L = LI->getLoopFor(Head)) {
696 L->addBasicBlockToLoop(ThenBlock, *LI);
697 L->addBasicBlockToLoop(Tail, *LI);
698 }
Adam Nemetfdb20592016-03-15 18:06:20 +0000699 }
700
Evgeniy Stepanov8eb77d82012-10-19 10:48:31 +0000701 return CheckTerm;
702}
Tom Stellardaa664d92013-08-06 02:43:45 +0000703
Kostya Serebryany530e2072013-12-23 14:15:08 +0000704void llvm::SplitBlockAndInsertIfThenElse(Value *Cond, Instruction *SplitBefore,
705 TerminatorInst **ThenTerm,
706 TerminatorInst **ElseTerm,
707 MDNode *BranchWeights) {
708 BasicBlock *Head = SplitBefore->getParent();
Duncan P. N. Exon Smith5b4c8372015-10-13 02:39:05 +0000709 BasicBlock *Tail = Head->splitBasicBlock(SplitBefore->getIterator());
Kostya Serebryany530e2072013-12-23 14:15:08 +0000710 TerminatorInst *HeadOldTerm = Head->getTerminator();
711 LLVMContext &C = Head->getContext();
712 BasicBlock *ThenBlock = BasicBlock::Create(C, "", Head->getParent(), Tail);
713 BasicBlock *ElseBlock = BasicBlock::Create(C, "", Head->getParent(), Tail);
714 *ThenTerm = BranchInst::Create(Tail, ThenBlock);
Evgeniy Stepanov2275a012014-03-19 12:56:38 +0000715 (*ThenTerm)->setDebugLoc(SplitBefore->getDebugLoc());
Kostya Serebryany530e2072013-12-23 14:15:08 +0000716 *ElseTerm = BranchInst::Create(Tail, ElseBlock);
Evgeniy Stepanov2275a012014-03-19 12:56:38 +0000717 (*ElseTerm)->setDebugLoc(SplitBefore->getDebugLoc());
Kostya Serebryany530e2072013-12-23 14:15:08 +0000718 BranchInst *HeadNewTerm =
719 BranchInst::Create(/*ifTrue*/ThenBlock, /*ifFalse*/ElseBlock, Cond);
720 HeadNewTerm->setMetadata(LLVMContext::MD_prof, BranchWeights);
721 ReplaceInstWithInst(HeadOldTerm, HeadNewTerm);
722}
723
Tom Stellardaa664d92013-08-06 02:43:45 +0000724Value *llvm::GetIfCondition(BasicBlock *BB, BasicBlock *&IfTrue,
725 BasicBlock *&IfFalse) {
726 PHINode *SomePHI = dyn_cast<PHINode>(BB->begin());
Craig Topperf40110f2014-04-25 05:29:35 +0000727 BasicBlock *Pred1 = nullptr;
728 BasicBlock *Pred2 = nullptr;
Tom Stellardaa664d92013-08-06 02:43:45 +0000729
730 if (SomePHI) {
731 if (SomePHI->getNumIncomingValues() != 2)
Craig Topperf40110f2014-04-25 05:29:35 +0000732 return nullptr;
Tom Stellardaa664d92013-08-06 02:43:45 +0000733 Pred1 = SomePHI->getIncomingBlock(0);
734 Pred2 = SomePHI->getIncomingBlock(1);
735 } else {
736 pred_iterator PI = pred_begin(BB), PE = pred_end(BB);
737 if (PI == PE) // No predecessor
Craig Topperf40110f2014-04-25 05:29:35 +0000738 return nullptr;
Tom Stellardaa664d92013-08-06 02:43:45 +0000739 Pred1 = *PI++;
740 if (PI == PE) // Only one predecessor
Craig Topperf40110f2014-04-25 05:29:35 +0000741 return nullptr;
Tom Stellardaa664d92013-08-06 02:43:45 +0000742 Pred2 = *PI++;
743 if (PI != PE) // More than two predecessors
Craig Topperf40110f2014-04-25 05:29:35 +0000744 return nullptr;
Tom Stellardaa664d92013-08-06 02:43:45 +0000745 }
746
747 // We can only handle branches. Other control flow will be lowered to
748 // branches if possible anyway.
749 BranchInst *Pred1Br = dyn_cast<BranchInst>(Pred1->getTerminator());
750 BranchInst *Pred2Br = dyn_cast<BranchInst>(Pred2->getTerminator());
Craig Topperf40110f2014-04-25 05:29:35 +0000751 if (!Pred1Br || !Pred2Br)
752 return nullptr;
Tom Stellardaa664d92013-08-06 02:43:45 +0000753
754 // Eliminate code duplication by ensuring that Pred1Br is conditional if
755 // either are.
756 if (Pred2Br->isConditional()) {
757 // If both branches are conditional, we don't have an "if statement". In
758 // reality, we could transform this case, but since the condition will be
759 // required anyway, we stand no chance of eliminating it, so the xform is
760 // probably not profitable.
761 if (Pred1Br->isConditional())
Craig Topperf40110f2014-04-25 05:29:35 +0000762 return nullptr;
Tom Stellardaa664d92013-08-06 02:43:45 +0000763
764 std::swap(Pred1, Pred2);
765 std::swap(Pred1Br, Pred2Br);
766 }
767
768 if (Pred1Br->isConditional()) {
769 // The only thing we have to watch out for here is to make sure that Pred2
770 // doesn't have incoming edges from other blocks. If it does, the condition
771 // doesn't dominate BB.
Craig Topperf40110f2014-04-25 05:29:35 +0000772 if (!Pred2->getSinglePredecessor())
773 return nullptr;
Tom Stellardaa664d92013-08-06 02:43:45 +0000774
775 // If we found a conditional branch predecessor, make sure that it branches
776 // to BB and Pred2Br. If it doesn't, this isn't an "if statement".
777 if (Pred1Br->getSuccessor(0) == BB &&
778 Pred1Br->getSuccessor(1) == Pred2) {
779 IfTrue = Pred1;
780 IfFalse = Pred2;
781 } else if (Pred1Br->getSuccessor(0) == Pred2 &&
782 Pred1Br->getSuccessor(1) == BB) {
783 IfTrue = Pred2;
784 IfFalse = Pred1;
785 } else {
786 // We know that one arm of the conditional goes to BB, so the other must
787 // go somewhere unrelated, and this must not be an "if statement".
Craig Topperf40110f2014-04-25 05:29:35 +0000788 return nullptr;
Tom Stellardaa664d92013-08-06 02:43:45 +0000789 }
790
791 return Pred1Br->getCondition();
792 }
793
794 // Ok, if we got here, both predecessors end with an unconditional branch to
795 // BB. Don't panic! If both blocks only have a single (identical)
796 // predecessor, and THAT is a conditional branch, then we're all ok!
797 BasicBlock *CommonPred = Pred1->getSinglePredecessor();
Craig Topperf40110f2014-04-25 05:29:35 +0000798 if (CommonPred == nullptr || CommonPred != Pred2->getSinglePredecessor())
799 return nullptr;
Tom Stellardaa664d92013-08-06 02:43:45 +0000800
801 // Otherwise, if this is a conditional branch, then we can use it!
802 BranchInst *BI = dyn_cast<BranchInst>(CommonPred->getTerminator());
Craig Topperf40110f2014-04-25 05:29:35 +0000803 if (!BI) return nullptr;
Tom Stellardaa664d92013-08-06 02:43:45 +0000804
805 assert(BI->isConditional() && "Two successors but not conditional?");
806 if (BI->getSuccessor(0) == Pred1) {
807 IfTrue = Pred1;
808 IfFalse = Pred2;
809 } else {
810 IfTrue = Pred2;
811 IfFalse = Pred1;
812 }
813 return BI->getCondition();
814}