blob: aa7b933022c00ddbf0b8bffefc70b1f3778f65b5 [file] [log] [blame]
Eugene Zelenko57bd5a02017-10-27 01:09:08 +00001//===- BasicBlockUtils.cpp - BasicBlock Utilities --------------------------==//
Misha Brukmanb1c93172005-04-21 23:48:37 +00002//
Chandler Carruth2946cd72019-01-19 08:50:56 +00003// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4// See https://llvm.org/LICENSE.txt for license information.
5// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
Misha Brukmanb1c93172005-04-21 23:48:37 +00006//
John Criswell482202a2003-10-20 19:43:21 +00007//===----------------------------------------------------------------------===//
Chris Lattner28537df2002-05-07 18:07:59 +00008//
9// This family of functions perform manipulations on basic blocks, and
10// instructions contained within basic blocks.
11//
12//===----------------------------------------------------------------------===//
13
14#include "llvm/Transforms/Utils/BasicBlockUtils.h"
Eugene Zelenko57bd5a02017-10-27 01:09:08 +000015#include "llvm/ADT/ArrayRef.h"
16#include "llvm/ADT/SmallPtrSet.h"
17#include "llvm/ADT/SmallVector.h"
18#include "llvm/ADT/Twine.h"
Nick Lewycky0b682452013-07-27 01:24:00 +000019#include "llvm/Analysis/CFG.h"
Richard Trieu5f436fc2019-02-06 02:52:52 +000020#include "llvm/Analysis/DomTreeUpdater.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"
Chandler Carruth5ad5f152014-01-13 09:26:24 +000029#include "llvm/IR/Dominators.h"
Chandler Carruth9fb823b2013-01-02 11:36:10 +000030#include "llvm/IR/Function.h"
Eugene Zelenko57bd5a02017-10-27 01:09:08 +000031#include "llvm/IR/InstrTypes.h"
32#include "llvm/IR/Instruction.h"
Chandler Carruth9fb823b2013-01-02 11:36:10 +000033#include "llvm/IR/Instructions.h"
Adrian Prantld60f34c2017-11-01 20:43:30 +000034#include "llvm/IR/IntrinsicInst.h"
Eugene Zelenko57bd5a02017-10-27 01:09:08 +000035#include "llvm/IR/LLVMContext.h"
Chandler Carruth9fb823b2013-01-02 11:36:10 +000036#include "llvm/IR/Type.h"
Eugene Zelenko57bd5a02017-10-27 01:09:08 +000037#include "llvm/IR/User.h"
38#include "llvm/IR/Value.h"
Chandler Carruth4220e9c2014-03-04 11:17:44 +000039#include "llvm/IR/ValueHandle.h"
Eugene Zelenko57bd5a02017-10-27 01:09:08 +000040#include "llvm/Support/Casting.h"
Chijun Sima21a8b602018-08-03 05:08:17 +000041#include "llvm/Transforms/Utils/Local.h"
Eugene Zelenko57bd5a02017-10-27 01:09:08 +000042#include <cassert>
43#include <cstdint>
44#include <string>
45#include <utility>
46#include <vector>
47
Chris Lattnerdf3c3422004-01-09 06:12:26 +000048using namespace llvm;
Brian Gaeke960707c2003-11-11 22:41:34 +000049
Max Kazantsev36b392c2019-02-06 07:56:36 +000050void llvm::DetatchDeadBlocks(
51 ArrayRef<BasicBlock *> BBs,
Max Kazantsev0686d1a2019-02-12 06:14:27 +000052 SmallVectorImpl<DominatorTree::UpdateType> *Updates,
Max Kazantsev20b91892019-02-12 07:09:29 +000053 bool KeepOneInputPHIs) {
Max Kazantsev1f733102019-01-14 10:26:26 +000054 for (auto *BB : BBs) {
55 // Loop through all of our successors and make sure they know that one
56 // of their predecessors is going away.
Max Kazantsev36b392c2019-02-06 07:56:36 +000057 SmallPtrSet<BasicBlock *, 4> UniqueSuccessors;
Max Kazantsev1f733102019-01-14 10:26:26 +000058 for (BasicBlock *Succ : successors(BB)) {
Max Kazantsev20b91892019-02-12 07:09:29 +000059 Succ->removePredecessor(BB, KeepOneInputPHIs);
Max Kazantsev36b392c2019-02-06 07:56:36 +000060 if (Updates && UniqueSuccessors.insert(Succ).second)
61 Updates->push_back({DominatorTree::Delete, BB, Succ});
Max Kazantsev1f733102019-01-14 10:26:26 +000062 }
63
64 // Zap all the instructions in the block.
65 while (!BB->empty()) {
66 Instruction &I = BB->back();
67 // If this instruction is used, replace uses with an arbitrary value.
68 // Because control flow can't get here, we don't care what we replace the
69 // value with. Note that since this block is unreachable, and all values
70 // contained within it must dominate their uses, that all uses will
71 // eventually be removed (they are themselves dead).
72 if (!I.use_empty())
73 I.replaceAllUsesWith(UndefValue::get(I.getType()));
74 BB->getInstList().pop_back();
75 }
76 new UnreachableInst(BB->getContext(), BB);
77 assert(BB->getInstList().size() == 1 &&
78 isa<UnreachableInst>(BB->getTerminator()) &&
79 "The successor list of BB isn't empty before "
80 "applying corresponding DTU updates.");
81 }
Max Kazantsev36b392c2019-02-06 07:56:36 +000082}
83
Max Kazantsev0686d1a2019-02-12 06:14:27 +000084void llvm::DeleteDeadBlock(BasicBlock *BB, DomTreeUpdater *DTU,
Max Kazantsev20b91892019-02-12 07:09:29 +000085 bool KeepOneInputPHIs) {
86 DeleteDeadBlocks({BB}, DTU, KeepOneInputPHIs);
Max Kazantsev36b392c2019-02-06 07:56:36 +000087}
88
Max Kazantsev0686d1a2019-02-12 06:14:27 +000089void llvm::DeleteDeadBlocks(ArrayRef <BasicBlock *> BBs, DomTreeUpdater *DTU,
Max Kazantsev20b91892019-02-12 07:09:29 +000090 bool KeepOneInputPHIs) {
Max Kazantsev36b392c2019-02-06 07:56:36 +000091#ifndef NDEBUG
92 // Make sure that all predecessors of each dead block is also dead.
93 SmallPtrSet<BasicBlock *, 4> Dead(BBs.begin(), BBs.end());
94 assert(Dead.size() == BBs.size() && "Duplicating blocks?");
95 for (auto *BB : Dead)
96 for (BasicBlock *Pred : predecessors(BB))
97 assert(Dead.count(Pred) && "All predecessors must be dead!");
98#endif
99
100 SmallVector<DominatorTree::UpdateType, 4> Updates;
Max Kazantsev20b91892019-02-12 07:09:29 +0000101 DetatchDeadBlocks(BBs, DTU ? &Updates : nullptr, KeepOneInputPHIs);
Max Kazantsev36b392c2019-02-06 07:56:36 +0000102
Chijun Sima21a8b602018-08-03 05:08:17 +0000103 if (DTU)
Chijun Sima70e97162019-02-22 13:48:38 +0000104 DTU->applyUpdatesPermissive(Updates);
Max Kazantsev1f733102019-01-14 10:26:26 +0000105
106 for (BasicBlock *BB : BBs)
107 if (DTU)
108 DTU->deleteBB(BB);
109 else
110 BB->eraseFromParent();
Chris Lattnerbcc904a2008-12-03 06:37:44 +0000111}
112
Brian Gesiak4349dc72019-03-11 17:51:57 +0000113bool llvm::EliminateUnreachableBlocks(Function &F, DomTreeUpdater *DTU,
114 bool KeepOneInputPHIs) {
115 df_iterator_default_set<BasicBlock*> Reachable;
116
117 // Mark all reachable blocks.
118 for (BasicBlock *BB : depth_first_ext(&F, Reachable))
119 (void)BB/* Mark all reachable blocks */;
120
121 // Collect all dead blocks.
122 std::vector<BasicBlock*> DeadBlocks;
123 for (Function::iterator I = F.begin(), E = F.end(); I != E; ++I)
124 if (!Reachable.count(&*I)) {
125 BasicBlock *BB = &*I;
126 DeadBlocks.push_back(BB);
127 }
128
129 // Delete the dead blocks.
130 DeleteDeadBlocks(DeadBlocks, DTU, KeepOneInputPHIs);
131
132 return !DeadBlocks.empty();
133}
134
Chandler Carruth96ada252015-07-22 09:52:54 +0000135void llvm::FoldSingleEntryPHINodes(BasicBlock *BB,
Chandler Carruth61440d22016-03-10 00:55:30 +0000136 MemoryDependenceResults *MemDep) {
Chris Lattnerf6ae9042011-01-11 08:13:40 +0000137 if (!isa<PHINode>(BB->begin())) return;
Jakub Staszak190db2f2013-01-14 23:16:36 +0000138
Chris Lattnerdc3f6f22008-12-03 19:44:02 +0000139 while (PHINode *PN = dyn_cast<PHINode>(BB->begin())) {
140 if (PN->getIncomingValue(0) != PN)
141 PN->replaceAllUsesWith(PN->getIncomingValue(0));
142 else
Owen Andersonb292b8c2009-07-30 23:03:37 +0000143 PN->replaceAllUsesWith(UndefValue::get(PN->getType()));
Jakub Staszak190db2f2013-01-14 23:16:36 +0000144
Chris Lattnerf6ae9042011-01-11 08:13:40 +0000145 if (MemDep)
146 MemDep->removeInstruction(PN); // Memdep updates AA itself.
Jakub Staszak190db2f2013-01-14 23:16:36 +0000147
Chris Lattnerdc3f6f22008-12-03 19:44:02 +0000148 PN->eraseFromParent();
149 }
150}
151
Benjamin Kramer8bcc9712012-08-29 15:32:21 +0000152bool llvm::DeleteDeadPHIs(BasicBlock *BB, const TargetLibraryInfo *TLI) {
Dan Gohmanff089952009-05-02 18:29:22 +0000153 // Recursively deleting a PHI may cause multiple PHIs to be deleted
Sanjoy Dase6bca0e2017-05-01 17:07:49 +0000154 // or RAUW'd undef, so use an array of WeakTrackingVH for the PHIs to delete.
155 SmallVector<WeakTrackingVH, 8> PHIs;
Benjamin Kramerc7fc81e2017-12-30 15:27:33 +0000156 for (PHINode &PN : BB->phis())
157 PHIs.push_back(&PN);
Dan Gohmanff089952009-05-02 18:29:22 +0000158
Dan Gohmancb99fe92010-01-05 15:45:31 +0000159 bool Changed = false;
Dan Gohmanff089952009-05-02 18:29:22 +0000160 for (unsigned i = 0, e = PHIs.size(); i != e; ++i)
161 if (PHINode *PN = dyn_cast_or_null<PHINode>(PHIs[i].operator Value*()))
Benjamin Kramer8bcc9712012-08-29 15:32:21 +0000162 Changed |= RecursivelyDeleteDeadPHINode(PN, TLI);
Dan Gohmancb99fe92010-01-05 15:45:31 +0000163
164 return Changed;
Dan Gohmanff089952009-05-02 18:29:22 +0000165}
166
Chijun Sima21a8b602018-08-03 05:08:17 +0000167bool llvm::MergeBlockIntoPredecessor(BasicBlock *BB, DomTreeUpdater *DTU,
Alina Sbirleaab6f84f72018-08-21 23:32:03 +0000168 LoopInfo *LI, MemorySSAUpdater *MSSAU,
Chijun Sima21a8b602018-08-03 05:08:17 +0000169 MemoryDependenceResults *MemDep) {
Alina Sbirleadfd14ad2018-06-20 22:01:04 +0000170 if (BB->hasAddressTaken())
171 return false;
Jakub Staszak190db2f2013-01-14 23:16:36 +0000172
Dan Gohman941020e2010-08-17 17:07:02 +0000173 // Can't merge if there are multiple predecessors, or no predecessors.
174 BasicBlock *PredBB = BB->getUniquePredecessor();
Dan Gohman2d02ff82009-10-31 17:33:01 +0000175 if (!PredBB) return false;
Dan Gohman941020e2010-08-17 17:07:02 +0000176
Dan Gohman2d02ff82009-10-31 17:33:01 +0000177 // Don't break self-loops.
178 if (PredBB == BB) return false;
David Majnemer654e1302015-07-31 17:58:14 +0000179 // Don't break unwinding instructions.
Chandler Carruth698fbe72018-08-26 08:56:42 +0000180 if (PredBB->getTerminator()->isExceptionalTerminator())
David Majnemer654e1302015-07-31 17:58:14 +0000181 return false;
Jakub Staszak190db2f2013-01-14 23:16:36 +0000182
Alina Sbirleadfd14ad2018-06-20 22:01:04 +0000183 // Can't merge if there are multiple distinct successors.
184 if (PredBB->getUniqueSuccessor() != BB)
185 return false;
Devang Patel0f7a3502008-09-09 01:06:56 +0000186
Dan Gohman2d02ff82009-10-31 17:33:01 +0000187 // Can't merge if there is PHI loop.
Benjamin Kramerc7fc81e2017-12-30 15:27:33 +0000188 for (PHINode &PN : BB->phis())
189 for (Value *IncValue : PN.incoming_values())
190 if (IncValue == &PN)
191 return false;
Dan Gohman2d02ff82009-10-31 17:33:01 +0000192
193 // Begin by getting rid of unneeded PHIs.
Davide Italiano48283ba2018-05-08 23:28:15 +0000194 SmallVector<AssertingVH<Value>, 4> IncomingValues;
Adrian Prantld60f34c2017-11-01 20:43:30 +0000195 if (isa<PHINode>(BB->front())) {
Benjamin Kramerc7fc81e2017-12-30 15:27:33 +0000196 for (PHINode &PN : BB->phis())
Davide Italiano48283ba2018-05-08 23:28:15 +0000197 if (!isa<PHINode>(PN.getIncomingValue(0)) ||
198 cast<PHINode>(PN.getIncomingValue(0))->getParent() != BB)
Benjamin Kramerc7fc81e2017-12-30 15:27:33 +0000199 IncomingValues.push_back(PN.getIncomingValue(0));
Chandler Carruth96ada252015-07-22 09:52:54 +0000200 FoldSingleEntryPHINodes(BB, MemDep);
Adrian Prantld60f34c2017-11-01 20:43:30 +0000201 }
Jakub Staszak190db2f2013-01-14 23:16:36 +0000202
Chijun Sima21a8b602018-08-03 05:08:17 +0000203 // DTU update: Collect all the edges that exit BB.
204 // These dominator edges will be redirected from Pred.
Alina Sbirleadfd14ad2018-06-20 22:01:04 +0000205 std::vector<DominatorTree::UpdateType> Updates;
Chijun Sima21a8b602018-08-03 05:08:17 +0000206 if (DTU) {
Alina Sbirleadfd14ad2018-06-20 22:01:04 +0000207 Updates.reserve(1 + (2 * succ_size(BB)));
208 Updates.push_back({DominatorTree::Delete, PredBB, BB});
209 for (auto I = succ_begin(BB), E = succ_end(BB); I != E; ++I) {
210 Updates.push_back({DominatorTree::Delete, BB, *I});
Chijun Sima58618762019-02-28 16:47:18 +0000211 // This successor of BB may already have PredBB as a predecessor.
212 if (llvm::find(successors(PredBB), *I) == succ_end(PredBB))
213 Updates.push_back({DominatorTree::Insert, PredBB, *I});
Alina Sbirleadfd14ad2018-06-20 22:01:04 +0000214 }
215 }
216
Alina Sbirleaab6f84f72018-08-21 23:32:03 +0000217 if (MSSAU)
218 MSSAU->moveAllAfterMergeBlocks(BB, PredBB, &*(BB->begin()));
219
Owen Andersonc0623812008-07-17 00:01:40 +0000220 // Delete the unconditional branch from the predecessor...
221 PredBB->getInstList().pop_back();
Jakub Staszak190db2f2013-01-14 23:16:36 +0000222
Owen Andersonc0623812008-07-17 00:01:40 +0000223 // Make all PHI nodes that referred to BB now refer to Pred as their
224 // source...
225 BB->replaceAllUsesWith(PredBB);
Jakub Staszak190db2f2013-01-14 23:16:36 +0000226
Jay Foad61ea0e42011-06-23 09:09:15 +0000227 // Move all definitions in the successor to the predecessor...
228 PredBB->getInstList().splice(PredBB->end(), BB->getInstList());
Chijun Sima21a8b602018-08-03 05:08:17 +0000229 new UnreachableInst(BB->getContext(), BB);
Jakub Staszak190db2f2013-01-14 23:16:36 +0000230
Adrian Prantld60f34c2017-11-01 20:43:30 +0000231 // Eliminate duplicate dbg.values describing the entry PHI node post-splice.
Davide Italiano48283ba2018-05-08 23:28:15 +0000232 for (auto Incoming : IncomingValues) {
233 if (isa<Instruction>(*Incoming)) {
Adrian Prantld60f34c2017-11-01 20:43:30 +0000234 SmallVector<DbgValueInst *, 2> DbgValues;
235 SmallDenseSet<std::pair<DILocalVariable *, DIExpression *>, 2>
236 DbgValueSet;
237 llvm::findDbgValues(DbgValues, Incoming);
238 for (auto &DVI : DbgValues) {
239 auto R = DbgValueSet.insert({DVI->getVariable(), DVI->getExpression()});
240 if (!R.second)
241 DVI->eraseFromParent();
242 }
243 }
244 }
245
Dan Gohman2d02ff82009-10-31 17:33:01 +0000246 // Inherit predecessors name if it exists.
Owen Anderson27405ef2008-07-17 19:42:29 +0000247 if (!PredBB->hasName())
248 PredBB->takeName(BB);
Jakub Staszak190db2f2013-01-14 23:16:36 +0000249
Chandler Carruthb5c11532015-01-18 02:11:23 +0000250 if (LI)
251 LI->removeBlock(BB);
252
253 if (MemDep)
254 MemDep->invalidateCachedPredecessors();
Jakub Staszak190db2f2013-01-14 23:16:36 +0000255
Chijun Sima21a8b602018-08-03 05:08:17 +0000256 // Finally, erase the old block and update dominator info.
257 if (DTU) {
258 assert(BB->getInstList().size() == 1 &&
259 isa<UnreachableInst>(BB->getTerminator()) &&
260 "The successor list of BB isn't empty before "
261 "applying corresponding DTU updates.");
Chijun Sima70e97162019-02-22 13:48:38 +0000262 DTU->applyUpdatesPermissive(Updates);
Chijun Sima21a8b602018-08-03 05:08:17 +0000263 DTU->deleteBB(BB);
264 }
265
266 else {
267 BB->eraseFromParent(); // Nuke BB if DTU is nullptr.
Alina Sbirleadfd14ad2018-06-20 22:01:04 +0000268 }
Dan Gohman2d02ff82009-10-31 17:33:01 +0000269 return true;
Owen Andersonc0623812008-07-17 00:01:40 +0000270}
271
Chris Lattnerdf3c3422004-01-09 06:12:26 +0000272void llvm::ReplaceInstWithValue(BasicBlock::InstListType &BIL,
273 BasicBlock::iterator &BI, Value *V) {
Chris Lattnerfda72b12002-06-25 16:12:52 +0000274 Instruction &I = *BI;
Chris Lattner28537df2002-05-07 18:07:59 +0000275 // Replaces all of the uses of the instruction with uses of the value
Chris Lattnerfda72b12002-06-25 16:12:52 +0000276 I.replaceAllUsesWith(V);
Chris Lattner28537df2002-05-07 18:07:59 +0000277
Chris Lattner8dd4cae2007-02-11 01:37:51 +0000278 // Make sure to propagate a name if there is one already.
279 if (I.hasName() && !V->hasName())
280 V->takeName(&I);
Misha Brukmanb1c93172005-04-21 23:48:37 +0000281
Misha Brukman7eb05a12003-08-18 14:43:39 +0000282 // Delete the unnecessary instruction now...
Chris Lattnerfda72b12002-06-25 16:12:52 +0000283 BI = BIL.erase(BI);
Chris Lattner28537df2002-05-07 18:07:59 +0000284}
285
Chris Lattnerdf3c3422004-01-09 06:12:26 +0000286void llvm::ReplaceInstWithInst(BasicBlock::InstListType &BIL,
287 BasicBlock::iterator &BI, Instruction *I) {
Craig Toppere73658d2014-04-28 04:05:08 +0000288 assert(I->getParent() == nullptr &&
Chris Lattner28537df2002-05-07 18:07:59 +0000289 "ReplaceInstWithInst: Instruction already inserted into basic block!");
290
Alexey Samsonov19ffcb92015-06-23 21:00:08 +0000291 // Copy debug location to newly added instruction, if it wasn't already set
292 // by the caller.
293 if (!I->getDebugLoc())
294 I->setDebugLoc(BI->getDebugLoc());
295
Chris Lattner28537df2002-05-07 18:07:59 +0000296 // Insert the new instruction into the basic block...
Chris Lattnerfda72b12002-06-25 16:12:52 +0000297 BasicBlock::iterator New = BIL.insert(BI, I);
Chris Lattner28537df2002-05-07 18:07:59 +0000298
299 // Replace all uses of the old instruction, and delete it.
300 ReplaceInstWithValue(BIL, BI, I);
301
302 // Move BI back to point to the newly inserted instruction
Chris Lattnerfda72b12002-06-25 16:12:52 +0000303 BI = New;
Chris Lattner28537df2002-05-07 18:07:59 +0000304}
305
Chris Lattnerdf3c3422004-01-09 06:12:26 +0000306void llvm::ReplaceInstWithInst(Instruction *From, Instruction *To) {
Chris Lattnerfda72b12002-06-25 16:12:52 +0000307 BasicBlock::iterator BI(From);
308 ReplaceInstWithInst(From->getParent()->getInstList(), BI, To);
Chris Lattner28537df2002-05-07 18:07:59 +0000309}
Chris Lattnerb17274e2002-07-29 22:32:08 +0000310
Chandler Carruthd4500562015-01-19 12:36:53 +0000311BasicBlock *llvm::SplitEdge(BasicBlock *BB, BasicBlock *Succ, DominatorTree *DT,
Alina Sbirleaab6f84f72018-08-21 23:32:03 +0000312 LoopInfo *LI, MemorySSAUpdater *MSSAU) {
Bob Wilsonaff96b22010-02-16 21:06:42 +0000313 unsigned SuccNum = GetSuccessorNumber(BB, Succ);
Jakub Staszak190db2f2013-01-14 23:16:36 +0000314
Chandler Carruth37df2cf2015-01-19 12:09:11 +0000315 // If this is a critical edge, let SplitCriticalEdge do it.
Chandler Carruth4a2d58e2018-10-15 09:34:05 +0000316 Instruction *LatchTerm = BB->getTerminator();
Alina Sbirleaab6f84f72018-08-21 23:32:03 +0000317 if (SplitCriticalEdge(
318 LatchTerm, SuccNum,
319 CriticalEdgeSplittingOptions(DT, LI, MSSAU).setPreserveLCSSA()))
Chandler Carruth37df2cf2015-01-19 12:09:11 +0000320 return LatchTerm->getSuccessor(SuccNum);
Chandler Carruth32c52c72015-01-18 02:39:37 +0000321
Devang Pateld7767cc2007-07-06 21:39:20 +0000322 // If the edge isn't critical, then BB has a single successor or Succ has a
323 // single pred. Split the block.
Devang Pateld7767cc2007-07-06 21:39:20 +0000324 if (BasicBlock *SP = Succ->getSinglePredecessor()) {
325 // If the successor only has a single pred, split the top of the successor
326 // block.
327 assert(SP == BB && "CFG broken");
Craig Topperf40110f2014-04-25 05:29:35 +0000328 SP = nullptr;
Alina Sbirleaab6f84f72018-08-21 23:32:03 +0000329 return SplitBlock(Succ, &Succ->front(), DT, LI, MSSAU);
Devang Pateld7767cc2007-07-06 21:39:20 +0000330 }
Jakub Staszak190db2f2013-01-14 23:16:36 +0000331
Chris Lattner30d95f92011-01-08 18:47:43 +0000332 // Otherwise, if BB has a single successor, split it at the bottom of the
333 // block.
334 assert(BB->getTerminator()->getNumSuccessors() == 1 &&
Jakub Staszak190db2f2013-01-14 23:16:36 +0000335 "Should have a single succ!");
Alina Sbirleaab6f84f72018-08-21 23:32:03 +0000336 return SplitBlock(BB, BB->getTerminator(), DT, LI, MSSAU);
Devang Pateld7767cc2007-07-06 21:39:20 +0000337}
338
Chandler Carruth37df2cf2015-01-19 12:09:11 +0000339unsigned
340llvm::SplitAllCriticalEdges(Function &F,
341 const CriticalEdgeSplittingOptions &Options) {
Kostya Serebryanye5ea4242014-11-19 00:17:31 +0000342 unsigned NumBroken = 0;
Benjamin Kramer135f7352016-06-26 12:28:59 +0000343 for (BasicBlock &BB : F) {
Chandler Carruth4a2d58e2018-10-15 09:34:05 +0000344 Instruction *TI = BB.getTerminator();
Kostya Serebryanye5ea4242014-11-19 00:17:31 +0000345 if (TI->getNumSuccessors() > 1 && !isa<IndirectBrInst>(TI))
346 for (unsigned i = 0, e = TI->getNumSuccessors(); i != e; ++i)
Chandler Carruth37df2cf2015-01-19 12:09:11 +0000347 if (SplitCriticalEdge(TI, i, Options))
Kostya Serebryanye5ea4242014-11-19 00:17:31 +0000348 ++NumBroken;
349 }
350 return NumBroken;
351}
352
Chandler Carruth32c52c72015-01-18 02:39:37 +0000353BasicBlock *llvm::SplitBlock(BasicBlock *Old, Instruction *SplitPt,
Alina Sbirleaab6f84f72018-08-21 23:32:03 +0000354 DominatorTree *DT, LoopInfo *LI,
355 MemorySSAUpdater *MSSAU) {
Duncan P. N. Exon Smith5b4c8372015-10-13 02:39:05 +0000356 BasicBlock::iterator SplitIt = SplitPt->getIterator();
David Majnemer654e1302015-07-31 17:58:14 +0000357 while (isa<PHINode>(SplitIt) || SplitIt->isEHPad())
Devang Pateld7767cc2007-07-06 21:39:20 +0000358 ++SplitIt;
359 BasicBlock *New = Old->splitBasicBlock(SplitIt, Old->getName()+".split");
360
Dan Gohman3ddbc242009-09-08 15:45:00 +0000361 // The new block lives in whichever loop the old one did. This preserves
362 // LCSSA as well, because we force the split point to be after any PHI nodes.
Chandler Carruth32c52c72015-01-18 02:39:37 +0000363 if (LI)
364 if (Loop *L = LI->getLoopFor(Old))
365 L->addBasicBlockToLoop(New, *LI);
Devang Pateld7767cc2007-07-06 21:39:20 +0000366
Chandler Carruth32c52c72015-01-18 02:39:37 +0000367 if (DT)
Gabor Greif2f5f6962010-09-10 22:25:58 +0000368 // Old dominates New. New node dominates all other nodes dominated by Old.
Chandler Carruth32c52c72015-01-18 02:39:37 +0000369 if (DomTreeNode *OldNode = DT->getNode(Old)) {
Benjamin Kramer135f7352016-06-26 12:28:59 +0000370 std::vector<DomTreeNode *> Children(OldNode->begin(), OldNode->end());
Devang Patel186e0d82007-07-19 02:29:24 +0000371
Chandler Carruth32c52c72015-01-18 02:39:37 +0000372 DomTreeNode *NewNode = DT->addNewBlock(New, Old);
Benjamin Kramer135f7352016-06-26 12:28:59 +0000373 for (DomTreeNode *I : Children)
374 DT->changeImmediateDominator(I, NewNode);
Rafael Espindolad3e65e72011-08-24 18:07:01 +0000375 }
Devang Pateld7767cc2007-07-06 21:39:20 +0000376
Alina Sbirleaab6f84f72018-08-21 23:32:03 +0000377 // Move MemoryAccesses still tracked in Old, but part of New now.
378 // Update accesses in successor blocks accordingly.
379 if (MSSAU)
380 MSSAU->moveAllAfterSpliceBlocks(Old, New, &*(New->begin()));
381
Devang Pateld7767cc2007-07-06 21:39:20 +0000382 return New;
383}
Chris Lattnera5b11702008-04-21 01:28:02 +0000384
Sanjay Patel85ce0f12016-04-23 16:31:48 +0000385/// Update DominatorTree, LoopInfo, and LCCSA analysis information.
Bill Wendling60291352011-08-18 17:57:57 +0000386static void UpdateAnalysisInformation(BasicBlock *OldBB, BasicBlock *NewBB,
Bill Wendlingec3823d2011-08-18 20:39:32 +0000387 ArrayRef<BasicBlock *> Preds,
Chandler Carruthb5797b62015-01-18 09:21:15 +0000388 DominatorTree *DT, LoopInfo *LI,
Alina Sbirleaab6f84f72018-08-21 23:32:03 +0000389 MemorySSAUpdater *MSSAU,
Chandler Carruthb5797b62015-01-18 09:21:15 +0000390 bool PreserveLCSSA, bool &HasLoopExit) {
391 // Update dominator tree if available.
Matt Arsenault06dfbb52018-01-31 22:54:37 +0000392 if (DT) {
393 if (OldBB == DT->getRootNode()->getBlock()) {
394 assert(NewBB == &NewBB->getParent()->getEntryBlock());
395 DT->setNewRoot(NewBB);
396 } else {
397 // Split block expects NewBB to have a non-empty set of predecessors.
398 DT->splitBlock(NewBB);
399 }
400 }
Bill Wendling0a693f42011-08-18 05:25:23 +0000401
Alina Sbirleaab6f84f72018-08-21 23:32:03 +0000402 // Update MemoryPhis after split if MemorySSA is available
403 if (MSSAU)
404 MSSAU->wireOldPredecessorsToNewImmediatePredecessor(OldBB, NewBB, Preds);
405
Chandler Carruthb5797b62015-01-18 09:21:15 +0000406 // The rest of the logic is only relevant for updating the loop structures.
407 if (!LI)
408 return;
409
Anna Thomas9fca5832018-01-04 17:21:15 +0000410 assert(DT && "DT should be available to update LoopInfo!");
Chandler Carruthb5797b62015-01-18 09:21:15 +0000411 Loop *L = LI->getLoopFor(OldBB);
Bill Wendling0a693f42011-08-18 05:25:23 +0000412
413 // If we need to preserve loop analyses, collect some information about how
414 // this split will affect loops.
415 bool IsLoopEntry = !!L;
416 bool SplitMakesNewLoopHeader = false;
Benjamin Kramer135f7352016-06-26 12:28:59 +0000417 for (BasicBlock *Pred : Preds) {
Anna Thomasbdb94302018-01-02 16:25:50 +0000418 // Preds that are not reachable from entry should not be used to identify if
419 // OldBB is a loop entry or if SplitMakesNewLoopHeader. Unreachable blocks
420 // are not within any loops, so we incorrectly mark SplitMakesNewLoopHeader
421 // as true and make the NewBB the header of some loop. This breaks LI.
422 if (!DT->isReachableFromEntry(Pred))
423 continue;
Chandler Carruthb5797b62015-01-18 09:21:15 +0000424 // If we need to preserve LCSSA, determine if any of the preds is a loop
425 // exit.
426 if (PreserveLCSSA)
427 if (Loop *PL = LI->getLoopFor(Pred))
428 if (!PL->contains(OldBB))
429 HasLoopExit = true;
Bill Wendling0a693f42011-08-18 05:25:23 +0000430
Chandler Carruthb5797b62015-01-18 09:21:15 +0000431 // If we need to preserve LoopInfo, note whether any of the preds crosses
432 // an interesting loop boundary.
433 if (!L)
434 continue;
435 if (L->contains(Pred))
436 IsLoopEntry = false;
437 else
438 SplitMakesNewLoopHeader = true;
Bill Wendling0a693f42011-08-18 05:25:23 +0000439 }
440
Chandler Carruthb5797b62015-01-18 09:21:15 +0000441 // Unless we have a loop for OldBB, nothing else to do here.
442 if (!L)
443 return;
Bill Wendling0a693f42011-08-18 05:25:23 +0000444
445 if (IsLoopEntry) {
446 // Add the new block to the nearest enclosing loop (and not an adjacent
447 // loop). To find this, examine each of the predecessors and determine which
448 // loops enclose them, and select the most-nested loop which contains the
449 // loop containing the block being split.
Craig Topperf40110f2014-04-25 05:29:35 +0000450 Loop *InnermostPredLoop = nullptr;
Benjamin Kramer135f7352016-06-26 12:28:59 +0000451 for (BasicBlock *Pred : Preds) {
Bill Wendlingec3823d2011-08-18 20:39:32 +0000452 if (Loop *PredLoop = LI->getLoopFor(Pred)) {
Bill Wendling0a693f42011-08-18 05:25:23 +0000453 // Seek a loop which actually contains the block being split (to avoid
454 // adjacent loops).
455 while (PredLoop && !PredLoop->contains(OldBB))
456 PredLoop = PredLoop->getParentLoop();
457
458 // Select the most-nested of these loops which contains the block.
459 if (PredLoop && PredLoop->contains(OldBB) &&
460 (!InnermostPredLoop ||
461 InnermostPredLoop->getLoopDepth() < PredLoop->getLoopDepth()))
462 InnermostPredLoop = PredLoop;
463 }
Bill Wendlingec3823d2011-08-18 20:39:32 +0000464 }
Bill Wendling0a693f42011-08-18 05:25:23 +0000465
466 if (InnermostPredLoop)
Chandler Carruth691addc2015-01-18 01:25:51 +0000467 InnermostPredLoop->addBasicBlockToLoop(NewBB, *LI);
Bill Wendling0a693f42011-08-18 05:25:23 +0000468 } else {
Chandler Carruth691addc2015-01-18 01:25:51 +0000469 L->addBasicBlockToLoop(NewBB, *LI);
Bill Wendling0a693f42011-08-18 05:25:23 +0000470 if (SplitMakesNewLoopHeader)
471 L->moveToHeader(NewBB);
472 }
473}
474
Sanjay Patel85ce0f12016-04-23 16:31:48 +0000475/// Update the PHI nodes in OrigBB to include the values coming from NewBB.
476/// This also updates AliasAnalysis, if available.
Bill Wendlingb267e2a2011-08-18 20:51:04 +0000477static void UpdatePHINodes(BasicBlock *OrigBB, BasicBlock *NewBB,
Chandler Carruthb5797b62015-01-18 09:21:15 +0000478 ArrayRef<BasicBlock *> Preds, BranchInst *BI,
Chandler Carruth96ada252015-07-22 09:52:54 +0000479 bool HasLoopExit) {
Bill Wendlingb267e2a2011-08-18 20:51:04 +0000480 // Otherwise, create a new PHI node in NewBB for each PHI node in OrigBB.
Chandler Carruth5bdf72c2014-04-28 10:37:30 +0000481 SmallPtrSet<BasicBlock *, 16> PredSet(Preds.begin(), Preds.end());
Bill Wendlingb267e2a2011-08-18 20:51:04 +0000482 for (BasicBlock::iterator I = OrigBB->begin(); isa<PHINode>(I); ) {
483 PHINode *PN = cast<PHINode>(I++);
484
485 // Check to see if all of the values coming in are the same. If so, we
486 // don't need to create a new PHI node, unless it's needed for LCSSA.
Craig Topperf40110f2014-04-25 05:29:35 +0000487 Value *InVal = nullptr;
Bill Wendlingb267e2a2011-08-18 20:51:04 +0000488 if (!HasLoopExit) {
489 InVal = PN->getIncomingValueForBlock(Preds[0]);
Chandler Carruth5bdf72c2014-04-28 10:37:30 +0000490 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) {
491 if (!PredSet.count(PN->getIncomingBlock(i)))
492 continue;
493 if (!InVal)
494 InVal = PN->getIncomingValue(i);
495 else if (InVal != PN->getIncomingValue(i)) {
Craig Topperf40110f2014-04-25 05:29:35 +0000496 InVal = nullptr;
Bill Wendlingb267e2a2011-08-18 20:51:04 +0000497 break;
498 }
Chandler Carruth5bdf72c2014-04-28 10:37:30 +0000499 }
Bill Wendlingb267e2a2011-08-18 20:51:04 +0000500 }
501
502 if (InVal) {
503 // If all incoming values for the new PHI would be the same, just don't
504 // make a new PHI. Instead, just remove the incoming values from the old
505 // PHI.
Jakub Staszak190db2f2013-01-14 23:16:36 +0000506
Chandler Carruth5bdf72c2014-04-28 10:37:30 +0000507 // NOTE! This loop walks backwards for a reason! First off, this minimizes
508 // the cost of removal if we end up removing a large number of values, and
509 // second off, this ensures that the indices for the incoming values
510 // aren't invalidated when we remove one.
511 for (int64_t i = PN->getNumIncomingValues() - 1; i >= 0; --i)
512 if (PredSet.count(PN->getIncomingBlock(i)))
513 PN->removeIncomingValue(i, false);
Bill Wendlingb267e2a2011-08-18 20:51:04 +0000514
Chandler Carruth5bdf72c2014-04-28 10:37:30 +0000515 // Add an incoming value to the PHI node in the loop for the preheader
516 // edge.
517 PN->addIncoming(InVal, NewBB);
518 continue;
Bill Wendlingb267e2a2011-08-18 20:51:04 +0000519 }
520
Chandler Carruth5bdf72c2014-04-28 10:37:30 +0000521 // If the values coming into the block are not the same, we need a new
522 // PHI.
523 // Create the new PHI node, insert it into NewBB at the end of the block
524 PHINode *NewPHI =
525 PHINode::Create(PN->getType(), Preds.size(), PN->getName() + ".ph", BI);
Chandler Carruth5bdf72c2014-04-28 10:37:30 +0000526
527 // NOTE! This loop walks backwards for a reason! First off, this minimizes
528 // the cost of removal if we end up removing a large number of values, and
529 // second off, this ensures that the indices for the incoming values aren't
530 // invalidated when we remove one.
531 for (int64_t i = PN->getNumIncomingValues() - 1; i >= 0; --i) {
532 BasicBlock *IncomingBB = PN->getIncomingBlock(i);
533 if (PredSet.count(IncomingBB)) {
534 Value *V = PN->removeIncomingValue(i, false);
535 NewPHI->addIncoming(V, IncomingBB);
536 }
537 }
538
539 PN->addIncoming(NewPHI, NewBB);
Bill Wendlingb267e2a2011-08-18 20:51:04 +0000540 }
541}
542
Jakub Staszak190db2f2013-01-14 23:16:36 +0000543BasicBlock *llvm::SplitBlockPredecessors(BasicBlock *BB,
Chandler Carruthb5797b62015-01-18 09:21:15 +0000544 ArrayRef<BasicBlock *> Preds,
Chandler Carruth96ada252015-07-22 09:52:54 +0000545 const char *Suffix, DominatorTree *DT,
Alina Sbirleaab6f84f72018-08-21 23:32:03 +0000546 LoopInfo *LI, MemorySSAUpdater *MSSAU,
547 bool PreserveLCSSA) {
David Majnemer654e1302015-07-31 17:58:14 +0000548 // Do not attempt to split that which cannot be split.
549 if (!BB->canSplitPredecessors())
550 return nullptr;
551
Philip Reames9198b332015-01-28 23:06:47 +0000552 // For the landingpads we need to act a bit differently.
553 // Delegate this work to the SplitLandingPadPredecessors.
554 if (BB->isLandingPad()) {
555 SmallVector<BasicBlock*, 2> NewBBs;
556 std::string NewName = std::string(Suffix) + ".split-lp";
557
Chandler Carruth96ada252015-07-22 09:52:54 +0000558 SplitLandingPadPredecessors(BB, Preds, Suffix, NewName.c_str(), NewBBs, DT,
Alina Sbirleaab6f84f72018-08-21 23:32:03 +0000559 LI, MSSAU, PreserveLCSSA);
Philip Reames9198b332015-01-28 23:06:47 +0000560 return NewBBs[0];
561 }
562
Chris Lattnera5b11702008-04-21 01:28:02 +0000563 // Create new basic block, insert right before the original block.
Alexey Samsonovb7f02d32015-06-09 22:10:29 +0000564 BasicBlock *NewBB = BasicBlock::Create(
565 BB->getContext(), BB->getName() + Suffix, BB->getParent(), BB);
Jakub Staszak190db2f2013-01-14 23:16:36 +0000566
Chris Lattnera5b11702008-04-21 01:28:02 +0000567 // The new block unconditionally branches to the old block.
568 BranchInst *BI = BranchInst::Create(BB, NewBB);
Taewook Oh2e945eb2017-02-14 21:10:40 +0000569 BI->setDebugLoc(BB->getFirstNonPHIOrDbg()->getDebugLoc());
Jakub Staszak190db2f2013-01-14 23:16:36 +0000570
Chris Lattnera5b11702008-04-21 01:28:02 +0000571 // Move the edges from Preds to point to NewBB instead of BB.
Jakub Staszakf5b32e52011-12-09 21:19:53 +0000572 for (unsigned i = 0, e = Preds.size(); i != e; ++i) {
Dan Gohman00c79382009-11-05 18:25:44 +0000573 // This is slightly more strict than necessary; the minimum requirement
574 // is that there be no more than one indirectbr branching to BB. And
575 // all BlockAddress uses would need to be updated.
576 assert(!isa<IndirectBrInst>(Preds[i]->getTerminator()) &&
577 "Cannot split an edge from an IndirectBrInst");
Craig Topper784929d2019-02-08 20:48:56 +0000578 assert(!isa<CallBrInst>(Preds[i]->getTerminator()) &&
579 "Cannot split an edge from a CallBrInst");
Chris Lattnera5b11702008-04-21 01:28:02 +0000580 Preds[i]->getTerminator()->replaceUsesOfWith(BB, NewBB);
Dan Gohman3ddbc242009-09-08 15:45:00 +0000581 }
582
Chris Lattnera5b11702008-04-21 01:28:02 +0000583 // Insert a new PHI node into NewBB for every PHI node in BB and that new PHI
584 // node becomes an incoming value for BB's phi node. However, if the Preds
585 // list is empty, we need to insert dummy entries into the PHI nodes in BB to
586 // account for the newly created predecessor.
Eugene Zelenko57bd5a02017-10-27 01:09:08 +0000587 if (Preds.empty()) {
Chris Lattnera5b11702008-04-21 01:28:02 +0000588 // Insert dummy values as the incoming value.
589 for (BasicBlock::iterator I = BB->begin(); isa<PHINode>(I); ++I)
Owen Andersonb292b8c2009-07-30 23:03:37 +0000590 cast<PHINode>(I)->addIncoming(UndefValue::get(I->getType()), NewBB);
Chris Lattnera5b11702008-04-21 01:28:02 +0000591 }
Dan Gohman3ddbc242009-09-08 15:45:00 +0000592
Bill Wendling0a693f42011-08-18 05:25:23 +0000593 // Update DominatorTree, LoopInfo, and LCCSA analysis information.
594 bool HasLoopExit = false;
Alina Sbirleaab6f84f72018-08-21 23:32:03 +0000595 UpdateAnalysisInformation(BB, NewBB, Preds, DT, LI, MSSAU, PreserveLCSSA,
Chandler Carruthb5797b62015-01-18 09:21:15 +0000596 HasLoopExit);
Dan Gohman3ddbc242009-09-08 15:45:00 +0000597
Matt Arsenault06dfbb52018-01-31 22:54:37 +0000598 if (!Preds.empty()) {
599 // Update the PHI nodes in BB with the values coming from NewBB.
600 UpdatePHINodes(BB, NewBB, Preds, BI, HasLoopExit);
601 }
602
Chris Lattnera5b11702008-04-21 01:28:02 +0000603 return NewBB;
604}
Chris Lattner72f16e72008-11-27 08:10:05 +0000605
Bill Wendlingca7d3092011-08-19 00:05:40 +0000606void llvm::SplitLandingPadPredecessors(BasicBlock *OrigBB,
Chandler Carruth0eae1122015-01-19 03:03:39 +0000607 ArrayRef<BasicBlock *> Preds,
Bill Wendlingca7d3092011-08-19 00:05:40 +0000608 const char *Suffix1, const char *Suffix2,
Chandler Carruth0eae1122015-01-19 03:03:39 +0000609 SmallVectorImpl<BasicBlock *> &NewBBs,
Chandler Carruth96ada252015-07-22 09:52:54 +0000610 DominatorTree *DT, LoopInfo *LI,
Alina Sbirleaab6f84f72018-08-21 23:32:03 +0000611 MemorySSAUpdater *MSSAU,
Chandler Carruth96ada252015-07-22 09:52:54 +0000612 bool PreserveLCSSA) {
Bill Wendlingca7d3092011-08-19 00:05:40 +0000613 assert(OrigBB->isLandingPad() && "Trying to split a non-landing pad!");
614
615 // Create a new basic block for OrigBB's predecessors listed in Preds. Insert
616 // it right before the original block.
617 BasicBlock *NewBB1 = BasicBlock::Create(OrigBB->getContext(),
618 OrigBB->getName() + Suffix1,
619 OrigBB->getParent(), OrigBB);
620 NewBBs.push_back(NewBB1);
621
622 // The new block unconditionally branches to the old block.
623 BranchInst *BI1 = BranchInst::Create(OrigBB, NewBB1);
Alexey Samsonovb7f02d32015-06-09 22:10:29 +0000624 BI1->setDebugLoc(OrigBB->getFirstNonPHI()->getDebugLoc());
Bill Wendlingca7d3092011-08-19 00:05:40 +0000625
626 // Move the edges from Preds to point to NewBB1 instead of OrigBB.
627 for (unsigned i = 0, e = Preds.size(); i != e; ++i) {
628 // This is slightly more strict than necessary; the minimum requirement
629 // is that there be no more than one indirectbr branching to BB. And
630 // all BlockAddress uses would need to be updated.
631 assert(!isa<IndirectBrInst>(Preds[i]->getTerminator()) &&
632 "Cannot split an edge from an IndirectBrInst");
633 Preds[i]->getTerminator()->replaceUsesOfWith(OrigBB, NewBB1);
634 }
635
Bill Wendlingca7d3092011-08-19 00:05:40 +0000636 bool HasLoopExit = false;
Alina Sbirleaab6f84f72018-08-21 23:32:03 +0000637 UpdateAnalysisInformation(OrigBB, NewBB1, Preds, DT, LI, MSSAU, PreserveLCSSA,
Chandler Carruthb5797b62015-01-18 09:21:15 +0000638 HasLoopExit);
Bill Wendlingca7d3092011-08-19 00:05:40 +0000639
640 // Update the PHI nodes in OrigBB with the values coming from NewBB1.
Chandler Carruth96ada252015-07-22 09:52:54 +0000641 UpdatePHINodes(OrigBB, NewBB1, Preds, BI1, HasLoopExit);
Bill Wendlingca7d3092011-08-19 00:05:40 +0000642
Bill Wendlingca7d3092011-08-19 00:05:40 +0000643 // Move the remaining edges from OrigBB to point to NewBB2.
644 SmallVector<BasicBlock*, 8> NewBB2Preds;
Duncan P. N. Exon Smith6c990152014-07-21 17:06:51 +0000645 for (pred_iterator i = pred_begin(OrigBB), e = pred_end(OrigBB);
646 i != e; ) {
647 BasicBlock *Pred = *i++;
Bill Wendling38d81302011-08-19 23:46:30 +0000648 if (Pred == NewBB1) continue;
Bill Wendlingca7d3092011-08-19 00:05:40 +0000649 assert(!isa<IndirectBrInst>(Pred->getTerminator()) &&
650 "Cannot split an edge from an IndirectBrInst");
Bill Wendlingca7d3092011-08-19 00:05:40 +0000651 NewBB2Preds.push_back(Pred);
Duncan P. N. Exon Smith6c990152014-07-21 17:06:51 +0000652 e = pred_end(OrigBB);
Bill Wendlingca7d3092011-08-19 00:05:40 +0000653 }
654
Craig Topperf40110f2014-04-25 05:29:35 +0000655 BasicBlock *NewBB2 = nullptr;
Bill Wendling38d81302011-08-19 23:46:30 +0000656 if (!NewBB2Preds.empty()) {
657 // Create another basic block for the rest of OrigBB's predecessors.
658 NewBB2 = BasicBlock::Create(OrigBB->getContext(),
659 OrigBB->getName() + Suffix2,
660 OrigBB->getParent(), OrigBB);
661 NewBBs.push_back(NewBB2);
Bill Wendlingca7d3092011-08-19 00:05:40 +0000662
Bill Wendling38d81302011-08-19 23:46:30 +0000663 // The new block unconditionally branches to the old block.
664 BranchInst *BI2 = BranchInst::Create(OrigBB, NewBB2);
Alexey Samsonovb7f02d32015-06-09 22:10:29 +0000665 BI2->setDebugLoc(OrigBB->getFirstNonPHI()->getDebugLoc());
Bill Wendling38d81302011-08-19 23:46:30 +0000666
667 // Move the remaining edges from OrigBB to point to NewBB2.
Benjamin Kramer135f7352016-06-26 12:28:59 +0000668 for (BasicBlock *NewBB2Pred : NewBB2Preds)
669 NewBB2Pred->getTerminator()->replaceUsesOfWith(OrigBB, NewBB2);
Bill Wendling38d81302011-08-19 23:46:30 +0000670
671 // Update DominatorTree, LoopInfo, and LCCSA analysis information.
672 HasLoopExit = false;
Alina Sbirleaab6f84f72018-08-21 23:32:03 +0000673 UpdateAnalysisInformation(OrigBB, NewBB2, NewBB2Preds, DT, LI, MSSAU,
Chandler Carruthb5797b62015-01-18 09:21:15 +0000674 PreserveLCSSA, HasLoopExit);
Bill Wendling38d81302011-08-19 23:46:30 +0000675
676 // Update the PHI nodes in OrigBB with the values coming from NewBB2.
Chandler Carruth96ada252015-07-22 09:52:54 +0000677 UpdatePHINodes(OrigBB, NewBB2, NewBB2Preds, BI2, HasLoopExit);
Bill Wendling38d81302011-08-19 23:46:30 +0000678 }
Bill Wendlingca7d3092011-08-19 00:05:40 +0000679
680 LandingPadInst *LPad = OrigBB->getLandingPadInst();
681 Instruction *Clone1 = LPad->clone();
682 Clone1->setName(Twine("lpad") + Suffix1);
683 NewBB1->getInstList().insert(NewBB1->getFirstInsertionPt(), Clone1);
684
Bill Wendling38d81302011-08-19 23:46:30 +0000685 if (NewBB2) {
686 Instruction *Clone2 = LPad->clone();
687 Clone2->setName(Twine("lpad") + Suffix2);
688 NewBB2->getInstList().insert(NewBB2->getFirstInsertionPt(), Clone2);
Bill Wendlingca7d3092011-08-19 00:05:40 +0000689
Chen Li78bde832016-01-06 20:32:05 +0000690 // Create a PHI node for the two cloned landingpad instructions only
691 // if the original landingpad instruction has some uses.
692 if (!LPad->use_empty()) {
693 assert(!LPad->getType()->isTokenTy() &&
694 "Split cannot be applied if LPad is token type. Otherwise an "
695 "invalid PHINode of token type would be created.");
696 PHINode *PN = PHINode::Create(LPad->getType(), 2, "lpad.phi", LPad);
697 PN->addIncoming(Clone1, NewBB1);
698 PN->addIncoming(Clone2, NewBB2);
699 LPad->replaceAllUsesWith(PN);
700 }
Bill Wendling38d81302011-08-19 23:46:30 +0000701 LPad->eraseFromParent();
702 } else {
703 // There is no second clone. Just replace the landing pad with the first
704 // clone.
705 LPad->replaceAllUsesWith(Clone1);
706 LPad->eraseFromParent();
707 }
Bill Wendlingca7d3092011-08-19 00:05:40 +0000708}
709
Evan Chengd983eba2011-01-29 04:46:23 +0000710ReturnInst *llvm::FoldReturnIntoUncondBranch(ReturnInst *RI, BasicBlock *BB,
Chijun Sima8b5de482018-08-04 08:13:47 +0000711 BasicBlock *Pred,
712 DomTreeUpdater *DTU) {
Evan Chengd983eba2011-01-29 04:46:23 +0000713 Instruction *UncondBranch = Pred->getTerminator();
714 // Clone the return and add it to the end of the predecessor.
715 Instruction *NewRet = RI->clone();
716 Pred->getInstList().push_back(NewRet);
Jakub Staszak190db2f2013-01-14 23:16:36 +0000717
Evan Chengd983eba2011-01-29 04:46:23 +0000718 // If the return instruction returns a value, and if the value was a
719 // PHI node in "BB", propagate the right value into the return.
720 for (User::op_iterator i = NewRet->op_begin(), e = NewRet->op_end();
Evan Cheng249716e2012-07-27 21:21:26 +0000721 i != e; ++i) {
722 Value *V = *i;
Craig Topperf40110f2014-04-25 05:29:35 +0000723 Instruction *NewBC = nullptr;
Evan Cheng249716e2012-07-27 21:21:26 +0000724 if (BitCastInst *BCI = dyn_cast<BitCastInst>(V)) {
725 // Return value might be bitcasted. Clone and insert it before the
726 // return instruction.
727 V = BCI->getOperand(0);
728 NewBC = BCI->clone();
Duncan P. N. Exon Smith5b4c8372015-10-13 02:39:05 +0000729 Pred->getInstList().insert(NewRet->getIterator(), NewBC);
Evan Cheng249716e2012-07-27 21:21:26 +0000730 *i = NewBC;
731 }
732 if (PHINode *PN = dyn_cast<PHINode>(V)) {
733 if (PN->getParent() == BB) {
734 if (NewBC)
735 NewBC->setOperand(0, PN->getIncomingValueForBlock(Pred));
736 else
737 *i = PN->getIncomingValueForBlock(Pred);
738 }
739 }
740 }
Jakub Staszak190db2f2013-01-14 23:16:36 +0000741
Evan Chengd983eba2011-01-29 04:46:23 +0000742 // Update any PHI nodes in the returning block to realize that we no
743 // longer branch to them.
744 BB->removePredecessor(Pred);
745 UncondBranch->eraseFromParent();
Chijun Sima8b5de482018-08-04 08:13:47 +0000746
747 if (DTU)
Chijun Simaf131d612019-02-22 05:41:43 +0000748 DTU->applyUpdates({{DominatorTree::Delete, Pred, BB}});
Chijun Sima8b5de482018-08-04 08:13:47 +0000749
Evan Chengd983eba2011-01-29 04:46:23 +0000750 return cast<ReturnInst>(NewRet);
Chris Lattner351134b2009-05-04 02:25:58 +0000751}
Devang Patela8e74112011-04-29 22:28:59 +0000752
Chandler Carruth4a2d58e2018-10-15 09:34:05 +0000753Instruction *llvm::SplitBlockAndInsertIfThen(Value *Cond,
754 Instruction *SplitBefore,
755 bool Unreachable,
756 MDNode *BranchWeights,
Max Kazantsev73db5c12019-02-15 08:18:00 +0000757 DominatorTree *DT, LoopInfo *LI,
758 BasicBlock *ThenBlock) {
Evgeniy Stepanov8eb77d82012-10-19 10:48:31 +0000759 BasicBlock *Head = SplitBefore->getParent();
Duncan P. N. Exon Smith5b4c8372015-10-13 02:39:05 +0000760 BasicBlock *Tail = Head->splitBasicBlock(SplitBefore->getIterator());
Chandler Carruth4a2d58e2018-10-15 09:34:05 +0000761 Instruction *HeadOldTerm = Head->getTerminator();
Evgeniy Stepanov8eb77d82012-10-19 10:48:31 +0000762 LLVMContext &C = Head->getContext();
Chandler Carruth4a2d58e2018-10-15 09:34:05 +0000763 Instruction *CheckTerm;
Max Kazantsev73db5c12019-02-15 08:18:00 +0000764 bool CreateThenBlock = (ThenBlock == nullptr);
765 if (CreateThenBlock) {
766 ThenBlock = BasicBlock::Create(C, "", Head->getParent(), Tail);
767 if (Unreachable)
768 CheckTerm = new UnreachableInst(C, ThenBlock);
769 else
770 CheckTerm = BranchInst::Create(Tail, ThenBlock);
771 CheckTerm->setDebugLoc(SplitBefore->getDebugLoc());
772 } else
773 CheckTerm = ThenBlock->getTerminator();
Evgeniy Stepanov8eb77d82012-10-19 10:48:31 +0000774 BranchInst *HeadNewTerm =
Evgeniy Stepanova9164e92013-12-19 13:29:56 +0000775 BranchInst::Create(/*ifTrue*/ThenBlock, /*ifFalse*/Tail, Cond);
Evgeniy Stepanov8eb77d82012-10-19 10:48:31 +0000776 HeadNewTerm->setMetadata(LLVMContext::MD_prof, BranchWeights);
777 ReplaceInstWithInst(HeadOldTerm, HeadNewTerm);
Peter Collingbourne818f5c42014-07-15 04:40:27 +0000778
779 if (DT) {
780 if (DomTreeNode *OldNode = DT->getNode(Head)) {
781 std::vector<DomTreeNode *> Children(OldNode->begin(), OldNode->end());
782
783 DomTreeNode *NewNode = DT->addNewBlock(Tail, Head);
Benjamin Kramer135f7352016-06-26 12:28:59 +0000784 for (DomTreeNode *Child : Children)
Peter Collingbourne818f5c42014-07-15 04:40:27 +0000785 DT->changeImmediateDominator(Child, NewNode);
786
787 // Head dominates ThenBlock.
Max Kazantsev73db5c12019-02-15 08:18:00 +0000788 if (CreateThenBlock)
789 DT->addNewBlock(ThenBlock, Head);
790 else
791 DT->changeImmediateDominator(ThenBlock, Head);
Peter Collingbourne818f5c42014-07-15 04:40:27 +0000792 }
793 }
794
Adam Nemetfdb20592016-03-15 18:06:20 +0000795 if (LI) {
Michael Kruse811de8a2017-03-06 15:33:05 +0000796 if (Loop *L = LI->getLoopFor(Head)) {
797 L->addBasicBlockToLoop(ThenBlock, *LI);
798 L->addBasicBlockToLoop(Tail, *LI);
799 }
Adam Nemetfdb20592016-03-15 18:06:20 +0000800 }
801
Evgeniy Stepanov8eb77d82012-10-19 10:48:31 +0000802 return CheckTerm;
803}
Tom Stellardaa664d92013-08-06 02:43:45 +0000804
Kostya Serebryany530e2072013-12-23 14:15:08 +0000805void llvm::SplitBlockAndInsertIfThenElse(Value *Cond, Instruction *SplitBefore,
Chandler Carruth4a2d58e2018-10-15 09:34:05 +0000806 Instruction **ThenTerm,
807 Instruction **ElseTerm,
Kostya Serebryany530e2072013-12-23 14:15:08 +0000808 MDNode *BranchWeights) {
809 BasicBlock *Head = SplitBefore->getParent();
Duncan P. N. Exon Smith5b4c8372015-10-13 02:39:05 +0000810 BasicBlock *Tail = Head->splitBasicBlock(SplitBefore->getIterator());
Chandler Carruth4a2d58e2018-10-15 09:34:05 +0000811 Instruction *HeadOldTerm = Head->getTerminator();
Kostya Serebryany530e2072013-12-23 14:15:08 +0000812 LLVMContext &C = Head->getContext();
813 BasicBlock *ThenBlock = BasicBlock::Create(C, "", Head->getParent(), Tail);
814 BasicBlock *ElseBlock = BasicBlock::Create(C, "", Head->getParent(), Tail);
815 *ThenTerm = BranchInst::Create(Tail, ThenBlock);
Evgeniy Stepanov2275a012014-03-19 12:56:38 +0000816 (*ThenTerm)->setDebugLoc(SplitBefore->getDebugLoc());
Kostya Serebryany530e2072013-12-23 14:15:08 +0000817 *ElseTerm = BranchInst::Create(Tail, ElseBlock);
Evgeniy Stepanov2275a012014-03-19 12:56:38 +0000818 (*ElseTerm)->setDebugLoc(SplitBefore->getDebugLoc());
Kostya Serebryany530e2072013-12-23 14:15:08 +0000819 BranchInst *HeadNewTerm =
820 BranchInst::Create(/*ifTrue*/ThenBlock, /*ifFalse*/ElseBlock, Cond);
821 HeadNewTerm->setMetadata(LLVMContext::MD_prof, BranchWeights);
822 ReplaceInstWithInst(HeadOldTerm, HeadNewTerm);
823}
824
Tom Stellardaa664d92013-08-06 02:43:45 +0000825Value *llvm::GetIfCondition(BasicBlock *BB, BasicBlock *&IfTrue,
826 BasicBlock *&IfFalse) {
827 PHINode *SomePHI = dyn_cast<PHINode>(BB->begin());
Craig Topperf40110f2014-04-25 05:29:35 +0000828 BasicBlock *Pred1 = nullptr;
829 BasicBlock *Pred2 = nullptr;
Tom Stellardaa664d92013-08-06 02:43:45 +0000830
831 if (SomePHI) {
832 if (SomePHI->getNumIncomingValues() != 2)
Craig Topperf40110f2014-04-25 05:29:35 +0000833 return nullptr;
Tom Stellardaa664d92013-08-06 02:43:45 +0000834 Pred1 = SomePHI->getIncomingBlock(0);
835 Pred2 = SomePHI->getIncomingBlock(1);
836 } else {
837 pred_iterator PI = pred_begin(BB), PE = pred_end(BB);
838 if (PI == PE) // No predecessor
Craig Topperf40110f2014-04-25 05:29:35 +0000839 return nullptr;
Tom Stellardaa664d92013-08-06 02:43:45 +0000840 Pred1 = *PI++;
841 if (PI == PE) // Only one predecessor
Craig Topperf40110f2014-04-25 05:29:35 +0000842 return nullptr;
Tom Stellardaa664d92013-08-06 02:43:45 +0000843 Pred2 = *PI++;
844 if (PI != PE) // More than two predecessors
Craig Topperf40110f2014-04-25 05:29:35 +0000845 return nullptr;
Tom Stellardaa664d92013-08-06 02:43:45 +0000846 }
847
848 // We can only handle branches. Other control flow will be lowered to
849 // branches if possible anyway.
850 BranchInst *Pred1Br = dyn_cast<BranchInst>(Pred1->getTerminator());
851 BranchInst *Pred2Br = dyn_cast<BranchInst>(Pred2->getTerminator());
Craig Topperf40110f2014-04-25 05:29:35 +0000852 if (!Pred1Br || !Pred2Br)
853 return nullptr;
Tom Stellardaa664d92013-08-06 02:43:45 +0000854
855 // Eliminate code duplication by ensuring that Pred1Br is conditional if
856 // either are.
857 if (Pred2Br->isConditional()) {
858 // If both branches are conditional, we don't have an "if statement". In
859 // reality, we could transform this case, but since the condition will be
860 // required anyway, we stand no chance of eliminating it, so the xform is
861 // probably not profitable.
862 if (Pred1Br->isConditional())
Craig Topperf40110f2014-04-25 05:29:35 +0000863 return nullptr;
Tom Stellardaa664d92013-08-06 02:43:45 +0000864
865 std::swap(Pred1, Pred2);
866 std::swap(Pred1Br, Pred2Br);
867 }
868
869 if (Pred1Br->isConditional()) {
870 // The only thing we have to watch out for here is to make sure that Pred2
871 // doesn't have incoming edges from other blocks. If it does, the condition
872 // doesn't dominate BB.
Craig Topperf40110f2014-04-25 05:29:35 +0000873 if (!Pred2->getSinglePredecessor())
874 return nullptr;
Tom Stellardaa664d92013-08-06 02:43:45 +0000875
876 // If we found a conditional branch predecessor, make sure that it branches
877 // to BB and Pred2Br. If it doesn't, this isn't an "if statement".
878 if (Pred1Br->getSuccessor(0) == BB &&
879 Pred1Br->getSuccessor(1) == Pred2) {
880 IfTrue = Pred1;
881 IfFalse = Pred2;
882 } else if (Pred1Br->getSuccessor(0) == Pred2 &&
883 Pred1Br->getSuccessor(1) == BB) {
884 IfTrue = Pred2;
885 IfFalse = Pred1;
886 } else {
887 // We know that one arm of the conditional goes to BB, so the other must
888 // go somewhere unrelated, and this must not be an "if statement".
Craig Topperf40110f2014-04-25 05:29:35 +0000889 return nullptr;
Tom Stellardaa664d92013-08-06 02:43:45 +0000890 }
891
892 return Pred1Br->getCondition();
893 }
894
895 // Ok, if we got here, both predecessors end with an unconditional branch to
896 // BB. Don't panic! If both blocks only have a single (identical)
897 // predecessor, and THAT is a conditional branch, then we're all ok!
898 BasicBlock *CommonPred = Pred1->getSinglePredecessor();
Craig Topperf40110f2014-04-25 05:29:35 +0000899 if (CommonPred == nullptr || CommonPred != Pred2->getSinglePredecessor())
900 return nullptr;
Tom Stellardaa664d92013-08-06 02:43:45 +0000901
902 // Otherwise, if this is a conditional branch, then we can use it!
903 BranchInst *BI = dyn_cast<BranchInst>(CommonPred->getTerminator());
Craig Topperf40110f2014-04-25 05:29:35 +0000904 if (!BI) return nullptr;
Tom Stellardaa664d92013-08-06 02:43:45 +0000905
906 assert(BI->isConditional() && "Two successors but not conditional?");
907 if (BI->getSuccessor(0) == Pred1) {
908 IfTrue = Pred1;
909 IfFalse = Pred2;
910 } else {
911 IfTrue = Pred2;
912 IfFalse = Pred1;
913 }
914 return BI->getCondition();
915}