blob: 11a0114150ffb29a8964d7ed97440d8443425919 [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"
Alina Sbirleaab6f84f72018-08-21 23:32:03 +000023#include "llvm/Analysis/MemorySSAUpdater.h"
Chijun Sima21a8b602018-08-03 05:08:17 +000024#include "llvm/Analysis/PostDominators.h"
Eugene Zelenko57bd5a02017-10-27 01:09:08 +000025#include "llvm/IR/BasicBlock.h"
26#include "llvm/IR/CFG.h"
27#include "llvm/IR/Constants.h"
Adrian Prantld60f34c2017-11-01 20:43:30 +000028#include "llvm/IR/DebugInfoMetadata.h"
Chijun Sima21a8b602018-08-03 05:08:17 +000029#include "llvm/IR/DomTreeUpdater.h"
Chandler Carruth5ad5f152014-01-13 09:26:24 +000030#include "llvm/IR/Dominators.h"
Chandler Carruth9fb823b2013-01-02 11:36:10 +000031#include "llvm/IR/Function.h"
Eugene Zelenko57bd5a02017-10-27 01:09:08 +000032#include "llvm/IR/InstrTypes.h"
33#include "llvm/IR/Instruction.h"
Chandler Carruth9fb823b2013-01-02 11:36:10 +000034#include "llvm/IR/Instructions.h"
Adrian Prantld60f34c2017-11-01 20:43:30 +000035#include "llvm/IR/IntrinsicInst.h"
Eugene Zelenko57bd5a02017-10-27 01:09:08 +000036#include "llvm/IR/LLVMContext.h"
Chandler Carruth9fb823b2013-01-02 11:36:10 +000037#include "llvm/IR/Type.h"
Eugene Zelenko57bd5a02017-10-27 01:09:08 +000038#include "llvm/IR/User.h"
39#include "llvm/IR/Value.h"
Chandler Carruth4220e9c2014-03-04 11:17:44 +000040#include "llvm/IR/ValueHandle.h"
Eugene Zelenko57bd5a02017-10-27 01:09:08 +000041#include "llvm/Support/Casting.h"
Chijun Sima21a8b602018-08-03 05:08:17 +000042#include "llvm/Transforms/Utils/Local.h"
Eugene Zelenko57bd5a02017-10-27 01:09:08 +000043#include <cassert>
44#include <cstdint>
45#include <string>
46#include <utility>
47#include <vector>
48
Chris Lattnerdf3c3422004-01-09 06:12:26 +000049using namespace llvm;
Brian Gaeke960707c2003-11-11 22:41:34 +000050
Chijun Sima21a8b602018-08-03 05:08:17 +000051void llvm::DeleteDeadBlock(BasicBlock *BB, DomTreeUpdater *DTU) {
Chris Lattner37e01362008-12-03 07:45:15 +000052 assert((pred_begin(BB) == pred_end(BB) ||
53 // Can delete self loop.
54 BB->getSinglePredecessor() == BB) && "Block is not dead!");
Chandler Carruth4a2d58e2018-10-15 09:34:05 +000055 Instruction *BBTerm = BB->getTerminator();
Brian M. Rzycki9b7ae232018-01-12 21:06:48 +000056 std::vector<DominatorTree::UpdateType> Updates;
Jakub Staszak190db2f2013-01-14 23:16:36 +000057
Chris Lattnerbcc904a2008-12-03 06:37:44 +000058 // Loop through all of our successors and make sure they know that one
59 // of their predecessors is going away.
Chijun Sima21a8b602018-08-03 05:08:17 +000060 if (DTU)
Brian M. Rzycki9b7ae232018-01-12 21:06:48 +000061 Updates.reserve(BBTerm->getNumSuccessors());
Chandler Carruth96fc1de2018-08-26 08:41:15 +000062 for (BasicBlock *Succ : successors(BBTerm)) {
Pete Cooperebcd7482015-08-06 20:22:46 +000063 Succ->removePredecessor(BB);
Chijun Sima21a8b602018-08-03 05:08:17 +000064 if (DTU)
Brian M. Rzycki9b7ae232018-01-12 21:06:48 +000065 Updates.push_back({DominatorTree::Delete, BB, Succ});
66 }
Jakub Staszak190db2f2013-01-14 23:16:36 +000067
Chris Lattnerbcc904a2008-12-03 06:37:44 +000068 // Zap all the instructions in the block.
69 while (!BB->empty()) {
70 Instruction &I = BB->back();
71 // If this instruction is used, replace uses with an arbitrary value.
72 // Because control flow can't get here, we don't care what we replace the
73 // value with. Note that since this block is unreachable, and all values
74 // contained within it must dominate their uses, that all uses will
75 // eventually be removed (they are themselves dead).
76 if (!I.use_empty())
Owen Andersonb292b8c2009-07-30 23:03:37 +000077 I.replaceAllUsesWith(UndefValue::get(I.getType()));
Chris Lattnerbcc904a2008-12-03 06:37:44 +000078 BB->getInstList().pop_back();
79 }
Chijun Sima21a8b602018-08-03 05:08:17 +000080 new UnreachableInst(BB->getContext(), BB);
81 assert(BB->getInstList().size() == 1 &&
82 isa<UnreachableInst>(BB->getTerminator()) &&
83 "The successor list of BB isn't empty before "
84 "applying corresponding DTU updates.");
Jakub Staszak190db2f2013-01-14 23:16:36 +000085
Chijun Sima21a8b602018-08-03 05:08:17 +000086 if (DTU) {
87 DTU->applyUpdates(Updates, /*ForceRemoveDuplicates*/ true);
88 DTU->deleteBB(BB);
Brian M. Rzycki9b7ae232018-01-12 21:06:48 +000089 } else {
90 BB->eraseFromParent(); // Zap the block!
91 }
Chris Lattnerbcc904a2008-12-03 06:37:44 +000092}
93
Chandler Carruth96ada252015-07-22 09:52:54 +000094void llvm::FoldSingleEntryPHINodes(BasicBlock *BB,
Chandler Carruth61440d22016-03-10 00:55:30 +000095 MemoryDependenceResults *MemDep) {
Chris Lattnerf6ae9042011-01-11 08:13:40 +000096 if (!isa<PHINode>(BB->begin())) return;
Jakub Staszak190db2f2013-01-14 23:16:36 +000097
Chris Lattnerdc3f6f22008-12-03 19:44:02 +000098 while (PHINode *PN = dyn_cast<PHINode>(BB->begin())) {
99 if (PN->getIncomingValue(0) != PN)
100 PN->replaceAllUsesWith(PN->getIncomingValue(0));
101 else
Owen Andersonb292b8c2009-07-30 23:03:37 +0000102 PN->replaceAllUsesWith(UndefValue::get(PN->getType()));
Jakub Staszak190db2f2013-01-14 23:16:36 +0000103
Chris Lattnerf6ae9042011-01-11 08:13:40 +0000104 if (MemDep)
105 MemDep->removeInstruction(PN); // Memdep updates AA itself.
Jakub Staszak190db2f2013-01-14 23:16:36 +0000106
Chris Lattnerdc3f6f22008-12-03 19:44:02 +0000107 PN->eraseFromParent();
108 }
109}
110
Benjamin Kramer8bcc9712012-08-29 15:32:21 +0000111bool llvm::DeleteDeadPHIs(BasicBlock *BB, const TargetLibraryInfo *TLI) {
Dan Gohmanff089952009-05-02 18:29:22 +0000112 // Recursively deleting a PHI may cause multiple PHIs to be deleted
Sanjoy Dase6bca0e2017-05-01 17:07:49 +0000113 // or RAUW'd undef, so use an array of WeakTrackingVH for the PHIs to delete.
114 SmallVector<WeakTrackingVH, 8> PHIs;
Benjamin Kramerc7fc81e2017-12-30 15:27:33 +0000115 for (PHINode &PN : BB->phis())
116 PHIs.push_back(&PN);
Dan Gohmanff089952009-05-02 18:29:22 +0000117
Dan Gohmancb99fe92010-01-05 15:45:31 +0000118 bool Changed = false;
Dan Gohmanff089952009-05-02 18:29:22 +0000119 for (unsigned i = 0, e = PHIs.size(); i != e; ++i)
120 if (PHINode *PN = dyn_cast_or_null<PHINode>(PHIs[i].operator Value*()))
Benjamin Kramer8bcc9712012-08-29 15:32:21 +0000121 Changed |= RecursivelyDeleteDeadPHINode(PN, TLI);
Dan Gohmancb99fe92010-01-05 15:45:31 +0000122
123 return Changed;
Dan Gohmanff089952009-05-02 18:29:22 +0000124}
125
Chijun Sima21a8b602018-08-03 05:08:17 +0000126bool llvm::MergeBlockIntoPredecessor(BasicBlock *BB, DomTreeUpdater *DTU,
Alina Sbirleaab6f84f72018-08-21 23:32:03 +0000127 LoopInfo *LI, MemorySSAUpdater *MSSAU,
Chijun Sima21a8b602018-08-03 05:08:17 +0000128 MemoryDependenceResults *MemDep) {
Alina Sbirleadfd14ad2018-06-20 22:01:04 +0000129 if (BB->hasAddressTaken())
130 return false;
Jakub Staszak190db2f2013-01-14 23:16:36 +0000131
Dan Gohman941020e2010-08-17 17:07:02 +0000132 // Can't merge if there are multiple predecessors, or no predecessors.
133 BasicBlock *PredBB = BB->getUniquePredecessor();
Dan Gohman2d02ff82009-10-31 17:33:01 +0000134 if (!PredBB) return false;
Dan Gohman941020e2010-08-17 17:07:02 +0000135
Dan Gohman2d02ff82009-10-31 17:33:01 +0000136 // Don't break self-loops.
137 if (PredBB == BB) return false;
David Majnemer654e1302015-07-31 17:58:14 +0000138 // Don't break unwinding instructions.
Chandler Carruth698fbe72018-08-26 08:56:42 +0000139 if (PredBB->getTerminator()->isExceptionalTerminator())
David Majnemer654e1302015-07-31 17:58:14 +0000140 return false;
Jakub Staszak190db2f2013-01-14 23:16:36 +0000141
Alina Sbirleadfd14ad2018-06-20 22:01:04 +0000142 // Can't merge if there are multiple distinct successors.
143 if (PredBB->getUniqueSuccessor() != BB)
144 return false;
Devang Patel0f7a3502008-09-09 01:06:56 +0000145
Dan Gohman2d02ff82009-10-31 17:33:01 +0000146 // Can't merge if there is PHI loop.
Benjamin Kramerc7fc81e2017-12-30 15:27:33 +0000147 for (PHINode &PN : BB->phis())
148 for (Value *IncValue : PN.incoming_values())
149 if (IncValue == &PN)
150 return false;
Dan Gohman2d02ff82009-10-31 17:33:01 +0000151
152 // Begin by getting rid of unneeded PHIs.
Davide Italiano48283ba2018-05-08 23:28:15 +0000153 SmallVector<AssertingVH<Value>, 4> IncomingValues;
Adrian Prantld60f34c2017-11-01 20:43:30 +0000154 if (isa<PHINode>(BB->front())) {
Benjamin Kramerc7fc81e2017-12-30 15:27:33 +0000155 for (PHINode &PN : BB->phis())
Davide Italiano48283ba2018-05-08 23:28:15 +0000156 if (!isa<PHINode>(PN.getIncomingValue(0)) ||
157 cast<PHINode>(PN.getIncomingValue(0))->getParent() != BB)
Benjamin Kramerc7fc81e2017-12-30 15:27:33 +0000158 IncomingValues.push_back(PN.getIncomingValue(0));
Chandler Carruth96ada252015-07-22 09:52:54 +0000159 FoldSingleEntryPHINodes(BB, MemDep);
Adrian Prantld60f34c2017-11-01 20:43:30 +0000160 }
Jakub Staszak190db2f2013-01-14 23:16:36 +0000161
Chijun Sima21a8b602018-08-03 05:08:17 +0000162 // DTU update: Collect all the edges that exit BB.
163 // These dominator edges will be redirected from Pred.
Alina Sbirleadfd14ad2018-06-20 22:01:04 +0000164 std::vector<DominatorTree::UpdateType> Updates;
Chijun Sima21a8b602018-08-03 05:08:17 +0000165 if (DTU) {
Alina Sbirleadfd14ad2018-06-20 22:01:04 +0000166 Updates.reserve(1 + (2 * succ_size(BB)));
167 Updates.push_back({DominatorTree::Delete, PredBB, BB});
168 for (auto I = succ_begin(BB), E = succ_end(BB); I != E; ++I) {
169 Updates.push_back({DominatorTree::Delete, BB, *I});
170 Updates.push_back({DominatorTree::Insert, PredBB, *I});
171 }
172 }
173
Alina Sbirleaab6f84f72018-08-21 23:32:03 +0000174 if (MSSAU)
175 MSSAU->moveAllAfterMergeBlocks(BB, PredBB, &*(BB->begin()));
176
Owen Andersonc0623812008-07-17 00:01:40 +0000177 // Delete the unconditional branch from the predecessor...
178 PredBB->getInstList().pop_back();
Jakub Staszak190db2f2013-01-14 23:16:36 +0000179
Owen Andersonc0623812008-07-17 00:01:40 +0000180 // Make all PHI nodes that referred to BB now refer to Pred as their
181 // source...
182 BB->replaceAllUsesWith(PredBB);
Jakub Staszak190db2f2013-01-14 23:16:36 +0000183
Jay Foad61ea0e42011-06-23 09:09:15 +0000184 // Move all definitions in the successor to the predecessor...
185 PredBB->getInstList().splice(PredBB->end(), BB->getInstList());
Chijun Sima21a8b602018-08-03 05:08:17 +0000186 new UnreachableInst(BB->getContext(), BB);
Jakub Staszak190db2f2013-01-14 23:16:36 +0000187
Adrian Prantld60f34c2017-11-01 20:43:30 +0000188 // Eliminate duplicate dbg.values describing the entry PHI node post-splice.
Davide Italiano48283ba2018-05-08 23:28:15 +0000189 for (auto Incoming : IncomingValues) {
190 if (isa<Instruction>(*Incoming)) {
Adrian Prantld60f34c2017-11-01 20:43:30 +0000191 SmallVector<DbgValueInst *, 2> DbgValues;
192 SmallDenseSet<std::pair<DILocalVariable *, DIExpression *>, 2>
193 DbgValueSet;
194 llvm::findDbgValues(DbgValues, Incoming);
195 for (auto &DVI : DbgValues) {
196 auto R = DbgValueSet.insert({DVI->getVariable(), DVI->getExpression()});
197 if (!R.second)
198 DVI->eraseFromParent();
199 }
200 }
201 }
202
Dan Gohman2d02ff82009-10-31 17:33:01 +0000203 // Inherit predecessors name if it exists.
Owen Anderson27405ef2008-07-17 19:42:29 +0000204 if (!PredBB->hasName())
205 PredBB->takeName(BB);
Jakub Staszak190db2f2013-01-14 23:16:36 +0000206
Chandler Carruthb5c11532015-01-18 02:11:23 +0000207 if (LI)
208 LI->removeBlock(BB);
209
210 if (MemDep)
211 MemDep->invalidateCachedPredecessors();
Jakub Staszak190db2f2013-01-14 23:16:36 +0000212
Chijun Sima21a8b602018-08-03 05:08:17 +0000213 // Finally, erase the old block and update dominator info.
214 if (DTU) {
215 assert(BB->getInstList().size() == 1 &&
216 isa<UnreachableInst>(BB->getTerminator()) &&
217 "The successor list of BB isn't empty before "
218 "applying corresponding DTU updates.");
219 DTU->applyUpdates(Updates, /*ForceRemoveDuplicates*/ true);
220 DTU->deleteBB(BB);
221 }
222
223 else {
224 BB->eraseFromParent(); // Nuke BB if DTU is nullptr.
Alina Sbirleadfd14ad2018-06-20 22:01:04 +0000225 }
Dan Gohman2d02ff82009-10-31 17:33:01 +0000226 return true;
Owen Andersonc0623812008-07-17 00:01:40 +0000227}
228
Chris Lattnerdf3c3422004-01-09 06:12:26 +0000229void llvm::ReplaceInstWithValue(BasicBlock::InstListType &BIL,
230 BasicBlock::iterator &BI, Value *V) {
Chris Lattnerfda72b12002-06-25 16:12:52 +0000231 Instruction &I = *BI;
Chris Lattner28537df2002-05-07 18:07:59 +0000232 // Replaces all of the uses of the instruction with uses of the value
Chris Lattnerfda72b12002-06-25 16:12:52 +0000233 I.replaceAllUsesWith(V);
Chris Lattner28537df2002-05-07 18:07:59 +0000234
Chris Lattner8dd4cae2007-02-11 01:37:51 +0000235 // Make sure to propagate a name if there is one already.
236 if (I.hasName() && !V->hasName())
237 V->takeName(&I);
Misha Brukmanb1c93172005-04-21 23:48:37 +0000238
Misha Brukman7eb05a12003-08-18 14:43:39 +0000239 // Delete the unnecessary instruction now...
Chris Lattnerfda72b12002-06-25 16:12:52 +0000240 BI = BIL.erase(BI);
Chris Lattner28537df2002-05-07 18:07:59 +0000241}
242
Chris Lattnerdf3c3422004-01-09 06:12:26 +0000243void llvm::ReplaceInstWithInst(BasicBlock::InstListType &BIL,
244 BasicBlock::iterator &BI, Instruction *I) {
Craig Toppere73658d2014-04-28 04:05:08 +0000245 assert(I->getParent() == nullptr &&
Chris Lattner28537df2002-05-07 18:07:59 +0000246 "ReplaceInstWithInst: Instruction already inserted into basic block!");
247
Alexey Samsonov19ffcb92015-06-23 21:00:08 +0000248 // Copy debug location to newly added instruction, if it wasn't already set
249 // by the caller.
250 if (!I->getDebugLoc())
251 I->setDebugLoc(BI->getDebugLoc());
252
Chris Lattner28537df2002-05-07 18:07:59 +0000253 // Insert the new instruction into the basic block...
Chris Lattnerfda72b12002-06-25 16:12:52 +0000254 BasicBlock::iterator New = BIL.insert(BI, I);
Chris Lattner28537df2002-05-07 18:07:59 +0000255
256 // Replace all uses of the old instruction, and delete it.
257 ReplaceInstWithValue(BIL, BI, I);
258
259 // Move BI back to point to the newly inserted instruction
Chris Lattnerfda72b12002-06-25 16:12:52 +0000260 BI = New;
Chris Lattner28537df2002-05-07 18:07:59 +0000261}
262
Chris Lattnerdf3c3422004-01-09 06:12:26 +0000263void llvm::ReplaceInstWithInst(Instruction *From, Instruction *To) {
Chris Lattnerfda72b12002-06-25 16:12:52 +0000264 BasicBlock::iterator BI(From);
265 ReplaceInstWithInst(From->getParent()->getInstList(), BI, To);
Chris Lattner28537df2002-05-07 18:07:59 +0000266}
Chris Lattnerb17274e2002-07-29 22:32:08 +0000267
Chandler Carruthd4500562015-01-19 12:36:53 +0000268BasicBlock *llvm::SplitEdge(BasicBlock *BB, BasicBlock *Succ, DominatorTree *DT,
Alina Sbirleaab6f84f72018-08-21 23:32:03 +0000269 LoopInfo *LI, MemorySSAUpdater *MSSAU) {
Bob Wilsonaff96b22010-02-16 21:06:42 +0000270 unsigned SuccNum = GetSuccessorNumber(BB, Succ);
Jakub Staszak190db2f2013-01-14 23:16:36 +0000271
Chandler Carruth37df2cf2015-01-19 12:09:11 +0000272 // If this is a critical edge, let SplitCriticalEdge do it.
Chandler Carruth4a2d58e2018-10-15 09:34:05 +0000273 Instruction *LatchTerm = BB->getTerminator();
Alina Sbirleaab6f84f72018-08-21 23:32:03 +0000274 if (SplitCriticalEdge(
275 LatchTerm, SuccNum,
276 CriticalEdgeSplittingOptions(DT, LI, MSSAU).setPreserveLCSSA()))
Chandler Carruth37df2cf2015-01-19 12:09:11 +0000277 return LatchTerm->getSuccessor(SuccNum);
Chandler Carruth32c52c72015-01-18 02:39:37 +0000278
Devang Pateld7767cc2007-07-06 21:39:20 +0000279 // If the edge isn't critical, then BB has a single successor or Succ has a
280 // single pred. Split the block.
Devang Pateld7767cc2007-07-06 21:39:20 +0000281 if (BasicBlock *SP = Succ->getSinglePredecessor()) {
282 // If the successor only has a single pred, split the top of the successor
283 // block.
284 assert(SP == BB && "CFG broken");
Craig Topperf40110f2014-04-25 05:29:35 +0000285 SP = nullptr;
Alina Sbirleaab6f84f72018-08-21 23:32:03 +0000286 return SplitBlock(Succ, &Succ->front(), DT, LI, MSSAU);
Devang Pateld7767cc2007-07-06 21:39:20 +0000287 }
Jakub Staszak190db2f2013-01-14 23:16:36 +0000288
Chris Lattner30d95f92011-01-08 18:47:43 +0000289 // Otherwise, if BB has a single successor, split it at the bottom of the
290 // block.
291 assert(BB->getTerminator()->getNumSuccessors() == 1 &&
Jakub Staszak190db2f2013-01-14 23:16:36 +0000292 "Should have a single succ!");
Alina Sbirleaab6f84f72018-08-21 23:32:03 +0000293 return SplitBlock(BB, BB->getTerminator(), DT, LI, MSSAU);
Devang Pateld7767cc2007-07-06 21:39:20 +0000294}
295
Chandler Carruth37df2cf2015-01-19 12:09:11 +0000296unsigned
297llvm::SplitAllCriticalEdges(Function &F,
298 const CriticalEdgeSplittingOptions &Options) {
Kostya Serebryanye5ea4242014-11-19 00:17:31 +0000299 unsigned NumBroken = 0;
Benjamin Kramer135f7352016-06-26 12:28:59 +0000300 for (BasicBlock &BB : F) {
Chandler Carruth4a2d58e2018-10-15 09:34:05 +0000301 Instruction *TI = BB.getTerminator();
Kostya Serebryanye5ea4242014-11-19 00:17:31 +0000302 if (TI->getNumSuccessors() > 1 && !isa<IndirectBrInst>(TI))
303 for (unsigned i = 0, e = TI->getNumSuccessors(); i != e; ++i)
Chandler Carruth37df2cf2015-01-19 12:09:11 +0000304 if (SplitCriticalEdge(TI, i, Options))
Kostya Serebryanye5ea4242014-11-19 00:17:31 +0000305 ++NumBroken;
306 }
307 return NumBroken;
308}
309
Chandler Carruth32c52c72015-01-18 02:39:37 +0000310BasicBlock *llvm::SplitBlock(BasicBlock *Old, Instruction *SplitPt,
Alina Sbirleaab6f84f72018-08-21 23:32:03 +0000311 DominatorTree *DT, LoopInfo *LI,
312 MemorySSAUpdater *MSSAU) {
Duncan P. N. Exon Smith5b4c8372015-10-13 02:39:05 +0000313 BasicBlock::iterator SplitIt = SplitPt->getIterator();
David Majnemer654e1302015-07-31 17:58:14 +0000314 while (isa<PHINode>(SplitIt) || SplitIt->isEHPad())
Devang Pateld7767cc2007-07-06 21:39:20 +0000315 ++SplitIt;
316 BasicBlock *New = Old->splitBasicBlock(SplitIt, Old->getName()+".split");
317
Dan Gohman3ddbc242009-09-08 15:45:00 +0000318 // The new block lives in whichever loop the old one did. This preserves
319 // LCSSA as well, because we force the split point to be after any PHI nodes.
Chandler Carruth32c52c72015-01-18 02:39:37 +0000320 if (LI)
321 if (Loop *L = LI->getLoopFor(Old))
322 L->addBasicBlockToLoop(New, *LI);
Devang Pateld7767cc2007-07-06 21:39:20 +0000323
Chandler Carruth32c52c72015-01-18 02:39:37 +0000324 if (DT)
Gabor Greif2f5f6962010-09-10 22:25:58 +0000325 // Old dominates New. New node dominates all other nodes dominated by Old.
Chandler Carruth32c52c72015-01-18 02:39:37 +0000326 if (DomTreeNode *OldNode = DT->getNode(Old)) {
Benjamin Kramer135f7352016-06-26 12:28:59 +0000327 std::vector<DomTreeNode *> Children(OldNode->begin(), OldNode->end());
Devang Patel186e0d82007-07-19 02:29:24 +0000328
Chandler Carruth32c52c72015-01-18 02:39:37 +0000329 DomTreeNode *NewNode = DT->addNewBlock(New, Old);
Benjamin Kramer135f7352016-06-26 12:28:59 +0000330 for (DomTreeNode *I : Children)
331 DT->changeImmediateDominator(I, NewNode);
Rafael Espindolad3e65e72011-08-24 18:07:01 +0000332 }
Devang Pateld7767cc2007-07-06 21:39:20 +0000333
Alina Sbirleaab6f84f72018-08-21 23:32:03 +0000334 // Move MemoryAccesses still tracked in Old, but part of New now.
335 // Update accesses in successor blocks accordingly.
336 if (MSSAU)
337 MSSAU->moveAllAfterSpliceBlocks(Old, New, &*(New->begin()));
338
Devang Pateld7767cc2007-07-06 21:39:20 +0000339 return New;
340}
Chris Lattnera5b11702008-04-21 01:28:02 +0000341
Sanjay Patel85ce0f12016-04-23 16:31:48 +0000342/// Update DominatorTree, LoopInfo, and LCCSA analysis information.
Bill Wendling60291352011-08-18 17:57:57 +0000343static void UpdateAnalysisInformation(BasicBlock *OldBB, BasicBlock *NewBB,
Bill Wendlingec3823d2011-08-18 20:39:32 +0000344 ArrayRef<BasicBlock *> Preds,
Chandler Carruthb5797b62015-01-18 09:21:15 +0000345 DominatorTree *DT, LoopInfo *LI,
Alina Sbirleaab6f84f72018-08-21 23:32:03 +0000346 MemorySSAUpdater *MSSAU,
Chandler Carruthb5797b62015-01-18 09:21:15 +0000347 bool PreserveLCSSA, bool &HasLoopExit) {
348 // Update dominator tree if available.
Matt Arsenault06dfbb52018-01-31 22:54:37 +0000349 if (DT) {
350 if (OldBB == DT->getRootNode()->getBlock()) {
351 assert(NewBB == &NewBB->getParent()->getEntryBlock());
352 DT->setNewRoot(NewBB);
353 } else {
354 // Split block expects NewBB to have a non-empty set of predecessors.
355 DT->splitBlock(NewBB);
356 }
357 }
Bill Wendling0a693f42011-08-18 05:25:23 +0000358
Alina Sbirleaab6f84f72018-08-21 23:32:03 +0000359 // Update MemoryPhis after split if MemorySSA is available
360 if (MSSAU)
361 MSSAU->wireOldPredecessorsToNewImmediatePredecessor(OldBB, NewBB, Preds);
362
Chandler Carruthb5797b62015-01-18 09:21:15 +0000363 // The rest of the logic is only relevant for updating the loop structures.
364 if (!LI)
365 return;
366
Anna Thomas9fca5832018-01-04 17:21:15 +0000367 assert(DT && "DT should be available to update LoopInfo!");
Chandler Carruthb5797b62015-01-18 09:21:15 +0000368 Loop *L = LI->getLoopFor(OldBB);
Bill Wendling0a693f42011-08-18 05:25:23 +0000369
370 // If we need to preserve loop analyses, collect some information about how
371 // this split will affect loops.
372 bool IsLoopEntry = !!L;
373 bool SplitMakesNewLoopHeader = false;
Benjamin Kramer135f7352016-06-26 12:28:59 +0000374 for (BasicBlock *Pred : Preds) {
Anna Thomasbdb94302018-01-02 16:25:50 +0000375 // Preds that are not reachable from entry should not be used to identify if
376 // OldBB is a loop entry or if SplitMakesNewLoopHeader. Unreachable blocks
377 // are not within any loops, so we incorrectly mark SplitMakesNewLoopHeader
378 // as true and make the NewBB the header of some loop. This breaks LI.
379 if (!DT->isReachableFromEntry(Pred))
380 continue;
Chandler Carruthb5797b62015-01-18 09:21:15 +0000381 // If we need to preserve LCSSA, determine if any of the preds is a loop
382 // exit.
383 if (PreserveLCSSA)
384 if (Loop *PL = LI->getLoopFor(Pred))
385 if (!PL->contains(OldBB))
386 HasLoopExit = true;
Bill Wendling0a693f42011-08-18 05:25:23 +0000387
Chandler Carruthb5797b62015-01-18 09:21:15 +0000388 // If we need to preserve LoopInfo, note whether any of the preds crosses
389 // an interesting loop boundary.
390 if (!L)
391 continue;
392 if (L->contains(Pred))
393 IsLoopEntry = false;
394 else
395 SplitMakesNewLoopHeader = true;
Bill Wendling0a693f42011-08-18 05:25:23 +0000396 }
397
Chandler Carruthb5797b62015-01-18 09:21:15 +0000398 // Unless we have a loop for OldBB, nothing else to do here.
399 if (!L)
400 return;
Bill Wendling0a693f42011-08-18 05:25:23 +0000401
402 if (IsLoopEntry) {
403 // Add the new block to the nearest enclosing loop (and not an adjacent
404 // loop). To find this, examine each of the predecessors and determine which
405 // loops enclose them, and select the most-nested loop which contains the
406 // loop containing the block being split.
Craig Topperf40110f2014-04-25 05:29:35 +0000407 Loop *InnermostPredLoop = nullptr;
Benjamin Kramer135f7352016-06-26 12:28:59 +0000408 for (BasicBlock *Pred : Preds) {
Bill Wendlingec3823d2011-08-18 20:39:32 +0000409 if (Loop *PredLoop = LI->getLoopFor(Pred)) {
Bill Wendling0a693f42011-08-18 05:25:23 +0000410 // Seek a loop which actually contains the block being split (to avoid
411 // adjacent loops).
412 while (PredLoop && !PredLoop->contains(OldBB))
413 PredLoop = PredLoop->getParentLoop();
414
415 // Select the most-nested of these loops which contains the block.
416 if (PredLoop && PredLoop->contains(OldBB) &&
417 (!InnermostPredLoop ||
418 InnermostPredLoop->getLoopDepth() < PredLoop->getLoopDepth()))
419 InnermostPredLoop = PredLoop;
420 }
Bill Wendlingec3823d2011-08-18 20:39:32 +0000421 }
Bill Wendling0a693f42011-08-18 05:25:23 +0000422
423 if (InnermostPredLoop)
Chandler Carruth691addc2015-01-18 01:25:51 +0000424 InnermostPredLoop->addBasicBlockToLoop(NewBB, *LI);
Bill Wendling0a693f42011-08-18 05:25:23 +0000425 } else {
Chandler Carruth691addc2015-01-18 01:25:51 +0000426 L->addBasicBlockToLoop(NewBB, *LI);
Bill Wendling0a693f42011-08-18 05:25:23 +0000427 if (SplitMakesNewLoopHeader)
428 L->moveToHeader(NewBB);
429 }
430}
431
Sanjay Patel85ce0f12016-04-23 16:31:48 +0000432/// Update the PHI nodes in OrigBB to include the values coming from NewBB.
433/// This also updates AliasAnalysis, if available.
Bill Wendlingb267e2a2011-08-18 20:51:04 +0000434static void UpdatePHINodes(BasicBlock *OrigBB, BasicBlock *NewBB,
Chandler Carruthb5797b62015-01-18 09:21:15 +0000435 ArrayRef<BasicBlock *> Preds, BranchInst *BI,
Chandler Carruth96ada252015-07-22 09:52:54 +0000436 bool HasLoopExit) {
Bill Wendlingb267e2a2011-08-18 20:51:04 +0000437 // Otherwise, create a new PHI node in NewBB for each PHI node in OrigBB.
Chandler Carruth5bdf72c2014-04-28 10:37:30 +0000438 SmallPtrSet<BasicBlock *, 16> PredSet(Preds.begin(), Preds.end());
Bill Wendlingb267e2a2011-08-18 20:51:04 +0000439 for (BasicBlock::iterator I = OrigBB->begin(); isa<PHINode>(I); ) {
440 PHINode *PN = cast<PHINode>(I++);
441
442 // Check to see if all of the values coming in are the same. If so, we
443 // don't need to create a new PHI node, unless it's needed for LCSSA.
Craig Topperf40110f2014-04-25 05:29:35 +0000444 Value *InVal = nullptr;
Bill Wendlingb267e2a2011-08-18 20:51:04 +0000445 if (!HasLoopExit) {
446 InVal = PN->getIncomingValueForBlock(Preds[0]);
Chandler Carruth5bdf72c2014-04-28 10:37:30 +0000447 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) {
448 if (!PredSet.count(PN->getIncomingBlock(i)))
449 continue;
450 if (!InVal)
451 InVal = PN->getIncomingValue(i);
452 else if (InVal != PN->getIncomingValue(i)) {
Craig Topperf40110f2014-04-25 05:29:35 +0000453 InVal = nullptr;
Bill Wendlingb267e2a2011-08-18 20:51:04 +0000454 break;
455 }
Chandler Carruth5bdf72c2014-04-28 10:37:30 +0000456 }
Bill Wendlingb267e2a2011-08-18 20:51:04 +0000457 }
458
459 if (InVal) {
460 // If all incoming values for the new PHI would be the same, just don't
461 // make a new PHI. Instead, just remove the incoming values from the old
462 // PHI.
Jakub Staszak190db2f2013-01-14 23:16:36 +0000463
Chandler Carruth5bdf72c2014-04-28 10:37:30 +0000464 // NOTE! This loop walks backwards for a reason! First off, this minimizes
465 // the cost of removal if we end up removing a large number of values, and
466 // second off, this ensures that the indices for the incoming values
467 // aren't invalidated when we remove one.
468 for (int64_t i = PN->getNumIncomingValues() - 1; i >= 0; --i)
469 if (PredSet.count(PN->getIncomingBlock(i)))
470 PN->removeIncomingValue(i, false);
Bill Wendlingb267e2a2011-08-18 20:51:04 +0000471
Chandler Carruth5bdf72c2014-04-28 10:37:30 +0000472 // Add an incoming value to the PHI node in the loop for the preheader
473 // edge.
474 PN->addIncoming(InVal, NewBB);
475 continue;
Bill Wendlingb267e2a2011-08-18 20:51:04 +0000476 }
477
Chandler Carruth5bdf72c2014-04-28 10:37:30 +0000478 // If the values coming into the block are not the same, we need a new
479 // PHI.
480 // Create the new PHI node, insert it into NewBB at the end of the block
481 PHINode *NewPHI =
482 PHINode::Create(PN->getType(), Preds.size(), PN->getName() + ".ph", BI);
Chandler Carruth5bdf72c2014-04-28 10:37:30 +0000483
484 // NOTE! This loop walks backwards for a reason! First off, this minimizes
485 // the cost of removal if we end up removing a large number of values, and
486 // second off, this ensures that the indices for the incoming values aren't
487 // invalidated when we remove one.
488 for (int64_t i = PN->getNumIncomingValues() - 1; i >= 0; --i) {
489 BasicBlock *IncomingBB = PN->getIncomingBlock(i);
490 if (PredSet.count(IncomingBB)) {
491 Value *V = PN->removeIncomingValue(i, false);
492 NewPHI->addIncoming(V, IncomingBB);
493 }
494 }
495
496 PN->addIncoming(NewPHI, NewBB);
Bill Wendlingb267e2a2011-08-18 20:51:04 +0000497 }
498}
499
Jakub Staszak190db2f2013-01-14 23:16:36 +0000500BasicBlock *llvm::SplitBlockPredecessors(BasicBlock *BB,
Chandler Carruthb5797b62015-01-18 09:21:15 +0000501 ArrayRef<BasicBlock *> Preds,
Chandler Carruth96ada252015-07-22 09:52:54 +0000502 const char *Suffix, DominatorTree *DT,
Alina Sbirleaab6f84f72018-08-21 23:32:03 +0000503 LoopInfo *LI, MemorySSAUpdater *MSSAU,
504 bool PreserveLCSSA) {
David Majnemer654e1302015-07-31 17:58:14 +0000505 // Do not attempt to split that which cannot be split.
506 if (!BB->canSplitPredecessors())
507 return nullptr;
508
Philip Reames9198b332015-01-28 23:06:47 +0000509 // For the landingpads we need to act a bit differently.
510 // Delegate this work to the SplitLandingPadPredecessors.
511 if (BB->isLandingPad()) {
512 SmallVector<BasicBlock*, 2> NewBBs;
513 std::string NewName = std::string(Suffix) + ".split-lp";
514
Chandler Carruth96ada252015-07-22 09:52:54 +0000515 SplitLandingPadPredecessors(BB, Preds, Suffix, NewName.c_str(), NewBBs, DT,
Alina Sbirleaab6f84f72018-08-21 23:32:03 +0000516 LI, MSSAU, PreserveLCSSA);
Philip Reames9198b332015-01-28 23:06:47 +0000517 return NewBBs[0];
518 }
519
Chris Lattnera5b11702008-04-21 01:28:02 +0000520 // Create new basic block, insert right before the original block.
Alexey Samsonovb7f02d32015-06-09 22:10:29 +0000521 BasicBlock *NewBB = BasicBlock::Create(
522 BB->getContext(), BB->getName() + Suffix, BB->getParent(), BB);
Jakub Staszak190db2f2013-01-14 23:16:36 +0000523
Chris Lattnera5b11702008-04-21 01:28:02 +0000524 // The new block unconditionally branches to the old block.
525 BranchInst *BI = BranchInst::Create(BB, NewBB);
Taewook Oh2e945eb2017-02-14 21:10:40 +0000526 BI->setDebugLoc(BB->getFirstNonPHIOrDbg()->getDebugLoc());
Jakub Staszak190db2f2013-01-14 23:16:36 +0000527
Chris Lattnera5b11702008-04-21 01:28:02 +0000528 // Move the edges from Preds to point to NewBB instead of BB.
Jakub Staszakf5b32e52011-12-09 21:19:53 +0000529 for (unsigned i = 0, e = Preds.size(); i != e; ++i) {
Dan Gohman00c79382009-11-05 18:25:44 +0000530 // This is slightly more strict than necessary; the minimum requirement
531 // is that there be no more than one indirectbr branching to BB. And
532 // all BlockAddress uses would need to be updated.
533 assert(!isa<IndirectBrInst>(Preds[i]->getTerminator()) &&
534 "Cannot split an edge from an IndirectBrInst");
Chris Lattnera5b11702008-04-21 01:28:02 +0000535 Preds[i]->getTerminator()->replaceUsesOfWith(BB, NewBB);
Dan Gohman3ddbc242009-09-08 15:45:00 +0000536 }
537
Chris Lattnera5b11702008-04-21 01:28:02 +0000538 // Insert a new PHI node into NewBB for every PHI node in BB and that new PHI
539 // node becomes an incoming value for BB's phi node. However, if the Preds
540 // list is empty, we need to insert dummy entries into the PHI nodes in BB to
541 // account for the newly created predecessor.
Eugene Zelenko57bd5a02017-10-27 01:09:08 +0000542 if (Preds.empty()) {
Chris Lattnera5b11702008-04-21 01:28:02 +0000543 // Insert dummy values as the incoming value.
544 for (BasicBlock::iterator I = BB->begin(); isa<PHINode>(I); ++I)
Owen Andersonb292b8c2009-07-30 23:03:37 +0000545 cast<PHINode>(I)->addIncoming(UndefValue::get(I->getType()), NewBB);
Chris Lattnera5b11702008-04-21 01:28:02 +0000546 }
Dan Gohman3ddbc242009-09-08 15:45:00 +0000547
Bill Wendling0a693f42011-08-18 05:25:23 +0000548 // Update DominatorTree, LoopInfo, and LCCSA analysis information.
549 bool HasLoopExit = false;
Alina Sbirleaab6f84f72018-08-21 23:32:03 +0000550 UpdateAnalysisInformation(BB, NewBB, Preds, DT, LI, MSSAU, PreserveLCSSA,
Chandler Carruthb5797b62015-01-18 09:21:15 +0000551 HasLoopExit);
Dan Gohman3ddbc242009-09-08 15:45:00 +0000552
Matt Arsenault06dfbb52018-01-31 22:54:37 +0000553 if (!Preds.empty()) {
554 // Update the PHI nodes in BB with the values coming from NewBB.
555 UpdatePHINodes(BB, NewBB, Preds, BI, HasLoopExit);
556 }
557
Chris Lattnera5b11702008-04-21 01:28:02 +0000558 return NewBB;
559}
Chris Lattner72f16e72008-11-27 08:10:05 +0000560
Bill Wendlingca7d3092011-08-19 00:05:40 +0000561void llvm::SplitLandingPadPredecessors(BasicBlock *OrigBB,
Chandler Carruth0eae1122015-01-19 03:03:39 +0000562 ArrayRef<BasicBlock *> Preds,
Bill Wendlingca7d3092011-08-19 00:05:40 +0000563 const char *Suffix1, const char *Suffix2,
Chandler Carruth0eae1122015-01-19 03:03:39 +0000564 SmallVectorImpl<BasicBlock *> &NewBBs,
Chandler Carruth96ada252015-07-22 09:52:54 +0000565 DominatorTree *DT, LoopInfo *LI,
Alina Sbirleaab6f84f72018-08-21 23:32:03 +0000566 MemorySSAUpdater *MSSAU,
Chandler Carruth96ada252015-07-22 09:52:54 +0000567 bool PreserveLCSSA) {
Bill Wendlingca7d3092011-08-19 00:05:40 +0000568 assert(OrigBB->isLandingPad() && "Trying to split a non-landing pad!");
569
570 // Create a new basic block for OrigBB's predecessors listed in Preds. Insert
571 // it right before the original block.
572 BasicBlock *NewBB1 = BasicBlock::Create(OrigBB->getContext(),
573 OrigBB->getName() + Suffix1,
574 OrigBB->getParent(), OrigBB);
575 NewBBs.push_back(NewBB1);
576
577 // The new block unconditionally branches to the old block.
578 BranchInst *BI1 = BranchInst::Create(OrigBB, NewBB1);
Alexey Samsonovb7f02d32015-06-09 22:10:29 +0000579 BI1->setDebugLoc(OrigBB->getFirstNonPHI()->getDebugLoc());
Bill Wendlingca7d3092011-08-19 00:05:40 +0000580
581 // Move the edges from Preds to point to NewBB1 instead of OrigBB.
582 for (unsigned i = 0, e = Preds.size(); i != e; ++i) {
583 // This is slightly more strict than necessary; the minimum requirement
584 // is that there be no more than one indirectbr branching to BB. And
585 // all BlockAddress uses would need to be updated.
586 assert(!isa<IndirectBrInst>(Preds[i]->getTerminator()) &&
587 "Cannot split an edge from an IndirectBrInst");
588 Preds[i]->getTerminator()->replaceUsesOfWith(OrigBB, NewBB1);
589 }
590
Bill Wendlingca7d3092011-08-19 00:05:40 +0000591 bool HasLoopExit = false;
Alina Sbirleaab6f84f72018-08-21 23:32:03 +0000592 UpdateAnalysisInformation(OrigBB, NewBB1, Preds, DT, LI, MSSAU, PreserveLCSSA,
Chandler Carruthb5797b62015-01-18 09:21:15 +0000593 HasLoopExit);
Bill Wendlingca7d3092011-08-19 00:05:40 +0000594
595 // Update the PHI nodes in OrigBB with the values coming from NewBB1.
Chandler Carruth96ada252015-07-22 09:52:54 +0000596 UpdatePHINodes(OrigBB, NewBB1, Preds, BI1, HasLoopExit);
Bill Wendlingca7d3092011-08-19 00:05:40 +0000597
Bill Wendlingca7d3092011-08-19 00:05:40 +0000598 // Move the remaining edges from OrigBB to point to NewBB2.
599 SmallVector<BasicBlock*, 8> NewBB2Preds;
Duncan P. N. Exon Smith6c990152014-07-21 17:06:51 +0000600 for (pred_iterator i = pred_begin(OrigBB), e = pred_end(OrigBB);
601 i != e; ) {
602 BasicBlock *Pred = *i++;
Bill Wendling38d81302011-08-19 23:46:30 +0000603 if (Pred == NewBB1) continue;
Bill Wendlingca7d3092011-08-19 00:05:40 +0000604 assert(!isa<IndirectBrInst>(Pred->getTerminator()) &&
605 "Cannot split an edge from an IndirectBrInst");
Bill Wendlingca7d3092011-08-19 00:05:40 +0000606 NewBB2Preds.push_back(Pred);
Duncan P. N. Exon Smith6c990152014-07-21 17:06:51 +0000607 e = pred_end(OrigBB);
Bill Wendlingca7d3092011-08-19 00:05:40 +0000608 }
609
Craig Topperf40110f2014-04-25 05:29:35 +0000610 BasicBlock *NewBB2 = nullptr;
Bill Wendling38d81302011-08-19 23:46:30 +0000611 if (!NewBB2Preds.empty()) {
612 // Create another basic block for the rest of OrigBB's predecessors.
613 NewBB2 = BasicBlock::Create(OrigBB->getContext(),
614 OrigBB->getName() + Suffix2,
615 OrigBB->getParent(), OrigBB);
616 NewBBs.push_back(NewBB2);
Bill Wendlingca7d3092011-08-19 00:05:40 +0000617
Bill Wendling38d81302011-08-19 23:46:30 +0000618 // The new block unconditionally branches to the old block.
619 BranchInst *BI2 = BranchInst::Create(OrigBB, NewBB2);
Alexey Samsonovb7f02d32015-06-09 22:10:29 +0000620 BI2->setDebugLoc(OrigBB->getFirstNonPHI()->getDebugLoc());
Bill Wendling38d81302011-08-19 23:46:30 +0000621
622 // Move the remaining edges from OrigBB to point to NewBB2.
Benjamin Kramer135f7352016-06-26 12:28:59 +0000623 for (BasicBlock *NewBB2Pred : NewBB2Preds)
624 NewBB2Pred->getTerminator()->replaceUsesOfWith(OrigBB, NewBB2);
Bill Wendling38d81302011-08-19 23:46:30 +0000625
626 // Update DominatorTree, LoopInfo, and LCCSA analysis information.
627 HasLoopExit = false;
Alina Sbirleaab6f84f72018-08-21 23:32:03 +0000628 UpdateAnalysisInformation(OrigBB, NewBB2, NewBB2Preds, DT, LI, MSSAU,
Chandler Carruthb5797b62015-01-18 09:21:15 +0000629 PreserveLCSSA, HasLoopExit);
Bill Wendling38d81302011-08-19 23:46:30 +0000630
631 // Update the PHI nodes in OrigBB with the values coming from NewBB2.
Chandler Carruth96ada252015-07-22 09:52:54 +0000632 UpdatePHINodes(OrigBB, NewBB2, NewBB2Preds, BI2, HasLoopExit);
Bill Wendling38d81302011-08-19 23:46:30 +0000633 }
Bill Wendlingca7d3092011-08-19 00:05:40 +0000634
635 LandingPadInst *LPad = OrigBB->getLandingPadInst();
636 Instruction *Clone1 = LPad->clone();
637 Clone1->setName(Twine("lpad") + Suffix1);
638 NewBB1->getInstList().insert(NewBB1->getFirstInsertionPt(), Clone1);
639
Bill Wendling38d81302011-08-19 23:46:30 +0000640 if (NewBB2) {
641 Instruction *Clone2 = LPad->clone();
642 Clone2->setName(Twine("lpad") + Suffix2);
643 NewBB2->getInstList().insert(NewBB2->getFirstInsertionPt(), Clone2);
Bill Wendlingca7d3092011-08-19 00:05:40 +0000644
Chen Li78bde832016-01-06 20:32:05 +0000645 // Create a PHI node for the two cloned landingpad instructions only
646 // if the original landingpad instruction has some uses.
647 if (!LPad->use_empty()) {
648 assert(!LPad->getType()->isTokenTy() &&
649 "Split cannot be applied if LPad is token type. Otherwise an "
650 "invalid PHINode of token type would be created.");
651 PHINode *PN = PHINode::Create(LPad->getType(), 2, "lpad.phi", LPad);
652 PN->addIncoming(Clone1, NewBB1);
653 PN->addIncoming(Clone2, NewBB2);
654 LPad->replaceAllUsesWith(PN);
655 }
Bill Wendling38d81302011-08-19 23:46:30 +0000656 LPad->eraseFromParent();
657 } else {
658 // There is no second clone. Just replace the landing pad with the first
659 // clone.
660 LPad->replaceAllUsesWith(Clone1);
661 LPad->eraseFromParent();
662 }
Bill Wendlingca7d3092011-08-19 00:05:40 +0000663}
664
Evan Chengd983eba2011-01-29 04:46:23 +0000665ReturnInst *llvm::FoldReturnIntoUncondBranch(ReturnInst *RI, BasicBlock *BB,
Chijun Sima8b5de482018-08-04 08:13:47 +0000666 BasicBlock *Pred,
667 DomTreeUpdater *DTU) {
Evan Chengd983eba2011-01-29 04:46:23 +0000668 Instruction *UncondBranch = Pred->getTerminator();
669 // Clone the return and add it to the end of the predecessor.
670 Instruction *NewRet = RI->clone();
671 Pred->getInstList().push_back(NewRet);
Jakub Staszak190db2f2013-01-14 23:16:36 +0000672
Evan Chengd983eba2011-01-29 04:46:23 +0000673 // If the return instruction returns a value, and if the value was a
674 // PHI node in "BB", propagate the right value into the return.
675 for (User::op_iterator i = NewRet->op_begin(), e = NewRet->op_end();
Evan Cheng249716e2012-07-27 21:21:26 +0000676 i != e; ++i) {
677 Value *V = *i;
Craig Topperf40110f2014-04-25 05:29:35 +0000678 Instruction *NewBC = nullptr;
Evan Cheng249716e2012-07-27 21:21:26 +0000679 if (BitCastInst *BCI = dyn_cast<BitCastInst>(V)) {
680 // Return value might be bitcasted. Clone and insert it before the
681 // return instruction.
682 V = BCI->getOperand(0);
683 NewBC = BCI->clone();
Duncan P. N. Exon Smith5b4c8372015-10-13 02:39:05 +0000684 Pred->getInstList().insert(NewRet->getIterator(), NewBC);
Evan Cheng249716e2012-07-27 21:21:26 +0000685 *i = NewBC;
686 }
687 if (PHINode *PN = dyn_cast<PHINode>(V)) {
688 if (PN->getParent() == BB) {
689 if (NewBC)
690 NewBC->setOperand(0, PN->getIncomingValueForBlock(Pred));
691 else
692 *i = PN->getIncomingValueForBlock(Pred);
693 }
694 }
695 }
Jakub Staszak190db2f2013-01-14 23:16:36 +0000696
Evan Chengd983eba2011-01-29 04:46:23 +0000697 // Update any PHI nodes in the returning block to realize that we no
698 // longer branch to them.
699 BB->removePredecessor(Pred);
700 UncondBranch->eraseFromParent();
Chijun Sima8b5de482018-08-04 08:13:47 +0000701
702 if (DTU)
703 DTU->deleteEdge(Pred, BB);
704
Evan Chengd983eba2011-01-29 04:46:23 +0000705 return cast<ReturnInst>(NewRet);
Chris Lattner351134b2009-05-04 02:25:58 +0000706}
Devang Patela8e74112011-04-29 22:28:59 +0000707
Chandler Carruth4a2d58e2018-10-15 09:34:05 +0000708Instruction *llvm::SplitBlockAndInsertIfThen(Value *Cond,
709 Instruction *SplitBefore,
710 bool Unreachable,
711 MDNode *BranchWeights,
712 DominatorTree *DT, LoopInfo *LI) {
Evgeniy Stepanov8eb77d82012-10-19 10:48:31 +0000713 BasicBlock *Head = SplitBefore->getParent();
Duncan P. N. Exon Smith5b4c8372015-10-13 02:39:05 +0000714 BasicBlock *Tail = Head->splitBasicBlock(SplitBefore->getIterator());
Chandler Carruth4a2d58e2018-10-15 09:34:05 +0000715 Instruction *HeadOldTerm = Head->getTerminator();
Evgeniy Stepanov8eb77d82012-10-19 10:48:31 +0000716 LLVMContext &C = Head->getContext();
717 BasicBlock *ThenBlock = BasicBlock::Create(C, "", Head->getParent(), Tail);
Chandler Carruth4a2d58e2018-10-15 09:34:05 +0000718 Instruction *CheckTerm;
Evgeniy Stepanov8eb77d82012-10-19 10:48:31 +0000719 if (Unreachable)
720 CheckTerm = new UnreachableInst(C, ThenBlock);
721 else
722 CheckTerm = BranchInst::Create(Tail, ThenBlock);
Evgeniy Stepanov2275a012014-03-19 12:56:38 +0000723 CheckTerm->setDebugLoc(SplitBefore->getDebugLoc());
Evgeniy Stepanov8eb77d82012-10-19 10:48:31 +0000724 BranchInst *HeadNewTerm =
Evgeniy Stepanova9164e92013-12-19 13:29:56 +0000725 BranchInst::Create(/*ifTrue*/ThenBlock, /*ifFalse*/Tail, Cond);
Evgeniy Stepanov8eb77d82012-10-19 10:48:31 +0000726 HeadNewTerm->setMetadata(LLVMContext::MD_prof, BranchWeights);
727 ReplaceInstWithInst(HeadOldTerm, HeadNewTerm);
Peter Collingbourne818f5c42014-07-15 04:40:27 +0000728
729 if (DT) {
730 if (DomTreeNode *OldNode = DT->getNode(Head)) {
731 std::vector<DomTreeNode *> Children(OldNode->begin(), OldNode->end());
732
733 DomTreeNode *NewNode = DT->addNewBlock(Tail, Head);
Benjamin Kramer135f7352016-06-26 12:28:59 +0000734 for (DomTreeNode *Child : Children)
Peter Collingbourne818f5c42014-07-15 04:40:27 +0000735 DT->changeImmediateDominator(Child, NewNode);
736
737 // Head dominates ThenBlock.
738 DT->addNewBlock(ThenBlock, Head);
739 }
740 }
741
Adam Nemetfdb20592016-03-15 18:06:20 +0000742 if (LI) {
Michael Kruse811de8a2017-03-06 15:33:05 +0000743 if (Loop *L = LI->getLoopFor(Head)) {
744 L->addBasicBlockToLoop(ThenBlock, *LI);
745 L->addBasicBlockToLoop(Tail, *LI);
746 }
Adam Nemetfdb20592016-03-15 18:06:20 +0000747 }
748
Evgeniy Stepanov8eb77d82012-10-19 10:48:31 +0000749 return CheckTerm;
750}
Tom Stellardaa664d92013-08-06 02:43:45 +0000751
Kostya Serebryany530e2072013-12-23 14:15:08 +0000752void llvm::SplitBlockAndInsertIfThenElse(Value *Cond, Instruction *SplitBefore,
Chandler Carruth4a2d58e2018-10-15 09:34:05 +0000753 Instruction **ThenTerm,
754 Instruction **ElseTerm,
Kostya Serebryany530e2072013-12-23 14:15:08 +0000755 MDNode *BranchWeights) {
756 BasicBlock *Head = SplitBefore->getParent();
Duncan P. N. Exon Smith5b4c8372015-10-13 02:39:05 +0000757 BasicBlock *Tail = Head->splitBasicBlock(SplitBefore->getIterator());
Chandler Carruth4a2d58e2018-10-15 09:34:05 +0000758 Instruction *HeadOldTerm = Head->getTerminator();
Kostya Serebryany530e2072013-12-23 14:15:08 +0000759 LLVMContext &C = Head->getContext();
760 BasicBlock *ThenBlock = BasicBlock::Create(C, "", Head->getParent(), Tail);
761 BasicBlock *ElseBlock = BasicBlock::Create(C, "", Head->getParent(), Tail);
762 *ThenTerm = BranchInst::Create(Tail, ThenBlock);
Evgeniy Stepanov2275a012014-03-19 12:56:38 +0000763 (*ThenTerm)->setDebugLoc(SplitBefore->getDebugLoc());
Kostya Serebryany530e2072013-12-23 14:15:08 +0000764 *ElseTerm = BranchInst::Create(Tail, ElseBlock);
Evgeniy Stepanov2275a012014-03-19 12:56:38 +0000765 (*ElseTerm)->setDebugLoc(SplitBefore->getDebugLoc());
Kostya Serebryany530e2072013-12-23 14:15:08 +0000766 BranchInst *HeadNewTerm =
767 BranchInst::Create(/*ifTrue*/ThenBlock, /*ifFalse*/ElseBlock, Cond);
768 HeadNewTerm->setMetadata(LLVMContext::MD_prof, BranchWeights);
769 ReplaceInstWithInst(HeadOldTerm, HeadNewTerm);
770}
771
Tom Stellardaa664d92013-08-06 02:43:45 +0000772Value *llvm::GetIfCondition(BasicBlock *BB, BasicBlock *&IfTrue,
773 BasicBlock *&IfFalse) {
774 PHINode *SomePHI = dyn_cast<PHINode>(BB->begin());
Craig Topperf40110f2014-04-25 05:29:35 +0000775 BasicBlock *Pred1 = nullptr;
776 BasicBlock *Pred2 = nullptr;
Tom Stellardaa664d92013-08-06 02:43:45 +0000777
778 if (SomePHI) {
779 if (SomePHI->getNumIncomingValues() != 2)
Craig Topperf40110f2014-04-25 05:29:35 +0000780 return nullptr;
Tom Stellardaa664d92013-08-06 02:43:45 +0000781 Pred1 = SomePHI->getIncomingBlock(0);
782 Pred2 = SomePHI->getIncomingBlock(1);
783 } else {
784 pred_iterator PI = pred_begin(BB), PE = pred_end(BB);
785 if (PI == PE) // No predecessor
Craig Topperf40110f2014-04-25 05:29:35 +0000786 return nullptr;
Tom Stellardaa664d92013-08-06 02:43:45 +0000787 Pred1 = *PI++;
788 if (PI == PE) // Only one predecessor
Craig Topperf40110f2014-04-25 05:29:35 +0000789 return nullptr;
Tom Stellardaa664d92013-08-06 02:43:45 +0000790 Pred2 = *PI++;
791 if (PI != PE) // More than two predecessors
Craig Topperf40110f2014-04-25 05:29:35 +0000792 return nullptr;
Tom Stellardaa664d92013-08-06 02:43:45 +0000793 }
794
795 // We can only handle branches. Other control flow will be lowered to
796 // branches if possible anyway.
797 BranchInst *Pred1Br = dyn_cast<BranchInst>(Pred1->getTerminator());
798 BranchInst *Pred2Br = dyn_cast<BranchInst>(Pred2->getTerminator());
Craig Topperf40110f2014-04-25 05:29:35 +0000799 if (!Pred1Br || !Pred2Br)
800 return nullptr;
Tom Stellardaa664d92013-08-06 02:43:45 +0000801
802 // Eliminate code duplication by ensuring that Pred1Br is conditional if
803 // either are.
804 if (Pred2Br->isConditional()) {
805 // If both branches are conditional, we don't have an "if statement". In
806 // reality, we could transform this case, but since the condition will be
807 // required anyway, we stand no chance of eliminating it, so the xform is
808 // probably not profitable.
809 if (Pred1Br->isConditional())
Craig Topperf40110f2014-04-25 05:29:35 +0000810 return nullptr;
Tom Stellardaa664d92013-08-06 02:43:45 +0000811
812 std::swap(Pred1, Pred2);
813 std::swap(Pred1Br, Pred2Br);
814 }
815
816 if (Pred1Br->isConditional()) {
817 // The only thing we have to watch out for here is to make sure that Pred2
818 // doesn't have incoming edges from other blocks. If it does, the condition
819 // doesn't dominate BB.
Craig Topperf40110f2014-04-25 05:29:35 +0000820 if (!Pred2->getSinglePredecessor())
821 return nullptr;
Tom Stellardaa664d92013-08-06 02:43:45 +0000822
823 // If we found a conditional branch predecessor, make sure that it branches
824 // to BB and Pred2Br. If it doesn't, this isn't an "if statement".
825 if (Pred1Br->getSuccessor(0) == BB &&
826 Pred1Br->getSuccessor(1) == Pred2) {
827 IfTrue = Pred1;
828 IfFalse = Pred2;
829 } else if (Pred1Br->getSuccessor(0) == Pred2 &&
830 Pred1Br->getSuccessor(1) == BB) {
831 IfTrue = Pred2;
832 IfFalse = Pred1;
833 } else {
834 // We know that one arm of the conditional goes to BB, so the other must
835 // go somewhere unrelated, and this must not be an "if statement".
Craig Topperf40110f2014-04-25 05:29:35 +0000836 return nullptr;
Tom Stellardaa664d92013-08-06 02:43:45 +0000837 }
838
839 return Pred1Br->getCondition();
840 }
841
842 // Ok, if we got here, both predecessors end with an unconditional branch to
843 // BB. Don't panic! If both blocks only have a single (identical)
844 // predecessor, and THAT is a conditional branch, then we're all ok!
845 BasicBlock *CommonPred = Pred1->getSinglePredecessor();
Craig Topperf40110f2014-04-25 05:29:35 +0000846 if (CommonPred == nullptr || CommonPred != Pred2->getSinglePredecessor())
847 return nullptr;
Tom Stellardaa664d92013-08-06 02:43:45 +0000848
849 // Otherwise, if this is a conditional branch, then we can use it!
850 BranchInst *BI = dyn_cast<BranchInst>(CommonPred->getTerminator());
Craig Topperf40110f2014-04-25 05:29:35 +0000851 if (!BI) return nullptr;
Tom Stellardaa664d92013-08-06 02:43:45 +0000852
853 assert(BI->isConditional() && "Two successors but not conditional?");
854 if (BI->getSuccessor(0) == Pred1) {
855 IfTrue = Pred1;
856 IfFalse = Pred2;
857 } else {
858 IfTrue = Pred2;
859 IfFalse = Pred1;
860 }
861 return BI->getCondition();
862}