1ef860a24SChandler Carruth //===-- BasicBlock.cpp - Implement BasicBlock related methods -------------===//
2ef860a24SChandler Carruth //
32946cd70SChandler Carruth // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
42946cd70SChandler Carruth // See https://llvm.org/LICENSE.txt for license information.
52946cd70SChandler Carruth // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6ef860a24SChandler Carruth //
7ef860a24SChandler Carruth //===----------------------------------------------------------------------===//
8ef860a24SChandler Carruth //
9ef860a24SChandler Carruth // This file implements the BasicBlock class for the IR library.
10ef860a24SChandler Carruth //
11ef860a24SChandler Carruth //===----------------------------------------------------------------------===//
12ef860a24SChandler Carruth 
139fb823bbSChandler Carruth #include "llvm/IR/BasicBlock.h"
14ef860a24SChandler Carruth #include "SymbolTableListTraitsImpl.h"
15ef860a24SChandler Carruth #include "llvm/ADT/STLExtras.h"
16*e188aae4Sserge-sans-paille #include "llvm/ADT/Statistic.h"
171305dc33SChandler Carruth #include "llvm/IR/CFG.h"
189fb823bbSChandler Carruth #include "llvm/IR/Constants.h"
199fb823bbSChandler Carruth #include "llvm/IR/Instructions.h"
209fb823bbSChandler Carruth #include "llvm/IR/IntrinsicInst.h"
219fb823bbSChandler Carruth #include "llvm/IR/LLVMContext.h"
229fb823bbSChandler Carruth #include "llvm/IR/Type.h"
23083ca9bbSHans Wennborg 
24ef860a24SChandler Carruth using namespace llvm;
25ef860a24SChandler Carruth 
26de5477edSPhilip Reames #define DEBUG_TYPE "ir"
27de5477edSPhilip Reames STATISTIC(NumInstrRenumberings, "Number of renumberings across all blocks");
28de5477edSPhilip Reames 
getValueSymbolTable()29ef860a24SChandler Carruth ValueSymbolTable *BasicBlock::getValueSymbolTable() {
30ef860a24SChandler Carruth   if (Function *F = getParent())
31a53d49e1SMehdi Amini     return F->getValueSymbolTable();
32c620761cSCraig Topper   return nullptr;
33ef860a24SChandler Carruth }
34ef860a24SChandler Carruth 
getContext() const35ef860a24SChandler Carruth LLVMContext &BasicBlock::getContext() const {
36ef860a24SChandler Carruth   return getType()->getContext();
37ef860a24SChandler Carruth }
38ef860a24SChandler Carruth 
invalidateParentIListOrdering(BasicBlock * BB)390c2b09a9SReid Kleckner template <> void llvm::invalidateParentIListOrdering(BasicBlock *BB) {
400c2b09a9SReid Kleckner   BB->invalidateOrders();
410c2b09a9SReid Kleckner }
420c2b09a9SReid Kleckner 
43ef860a24SChandler Carruth // Explicit instantiation of SymbolTableListTraits since some of the methods
44ef860a24SChandler Carruth // are not in the public header file...
4537bf678aSDuncan P. N. Exon Smith template class llvm::SymbolTableListTraits<Instruction>;
46ef860a24SChandler Carruth 
BasicBlock(LLVMContext & C,const Twine & Name,Function * NewParent,BasicBlock * InsertBefore)47ef860a24SChandler Carruth BasicBlock::BasicBlock(LLVMContext &C, const Twine &Name, Function *NewParent,
48ef860a24SChandler Carruth                        BasicBlock *InsertBefore)
49c620761cSCraig Topper   : Value(Type::getLabelTy(C), Value::BasicBlockVal), Parent(nullptr) {
50ef860a24SChandler Carruth 
5117cbb978SDuncan P. N. Exon Smith   if (NewParent)
5217cbb978SDuncan P. N. Exon Smith     insertInto(NewParent, InsertBefore);
5317cbb978SDuncan P. N. Exon Smith   else
5417cbb978SDuncan P. N. Exon Smith     assert(!InsertBefore &&
55ef860a24SChandler Carruth            "Cannot insert block before another block with no function!");
56ef860a24SChandler Carruth 
57ef860a24SChandler Carruth   setName(Name);
58ef860a24SChandler Carruth }
59ef860a24SChandler Carruth 
insertInto(Function * NewParent,BasicBlock * InsertBefore)6017cbb978SDuncan P. N. Exon Smith void BasicBlock::insertInto(Function *NewParent, BasicBlock *InsertBefore) {
6117cbb978SDuncan P. N. Exon Smith   assert(NewParent && "Expected a parent");
6217cbb978SDuncan P. N. Exon Smith   assert(!Parent && "Already has a parent");
6317cbb978SDuncan P. N. Exon Smith 
6417cbb978SDuncan P. N. Exon Smith   if (InsertBefore)
6552888a67SDuncan P. N. Exon Smith     NewParent->getBasicBlockList().insert(InsertBefore->getIterator(), this);
6617cbb978SDuncan P. N. Exon Smith   else
6717cbb978SDuncan P. N. Exon Smith     NewParent->getBasicBlockList().push_back(this);
6817cbb978SDuncan P. N. Exon Smith }
69ef860a24SChandler Carruth 
~BasicBlock()70ef860a24SChandler Carruth BasicBlock::~BasicBlock() {
710c2b09a9SReid Kleckner   validateInstrOrdering();
720c2b09a9SReid Kleckner 
73ef860a24SChandler Carruth   // If the address of the block is taken and it is being deleted (e.g. because
74ef860a24SChandler Carruth   // it is dead), this means that there is either a dangling constant expr
75ef860a24SChandler Carruth   // hanging off the block, or an undefined use of the block (source code
76ef860a24SChandler Carruth   // expecting the address of a label to keep the block alive even though there
77ef860a24SChandler Carruth   // is no indirect branch).  Handle these cases by zapping the BlockAddress
78ef860a24SChandler Carruth   // nodes.  There are no other possible uses at this point.
79ef860a24SChandler Carruth   if (hasAddressTaken()) {
80ef860a24SChandler Carruth     assert(!use_empty() && "There should be at least one blockaddress!");
81ef860a24SChandler Carruth     Constant *Replacement =
82ef860a24SChandler Carruth       ConstantInt::get(llvm::Type::getInt32Ty(getContext()), 1);
83ef860a24SChandler Carruth     while (!use_empty()) {
84cdf47884SChandler Carruth       BlockAddress *BA = cast<BlockAddress>(user_back());
85ef860a24SChandler Carruth       BA->replaceAllUsesWith(ConstantExpr::getIntToPtr(Replacement,
86ef860a24SChandler Carruth                                                        BA->getType()));
87ef860a24SChandler Carruth       BA->destroyConstant();
88ef860a24SChandler Carruth     }
89ef860a24SChandler Carruth   }
90ef860a24SChandler Carruth 
912617dcceSCraig Topper   assert(getParent() == nullptr && "BasicBlock still linked into the program!");
92ef860a24SChandler Carruth   dropAllReferences();
93ef860a24SChandler Carruth   InstList.clear();
94ef860a24SChandler Carruth }
95ef860a24SChandler Carruth 
setParent(Function * parent)96ef860a24SChandler Carruth void BasicBlock::setParent(Function *parent) {
97ef860a24SChandler Carruth   // Set Parent=parent, updating instruction symtab entries as appropriate.
98ef860a24SChandler Carruth   InstList.setSymTabObject(&Parent, parent);
99ef860a24SChandler Carruth }
100ef860a24SChandler Carruth 
101147fc016SFlorian Hahn iterator_range<filter_iterator<BasicBlock::const_iterator,
102147fc016SFlorian Hahn                                std::function<bool(const Instruction &)>>>
instructionsWithoutDebug(bool SkipPseudoOp) const103f3c44569SHongtao Yu BasicBlock::instructionsWithoutDebug(bool SkipPseudoOp) const {
104f3c44569SHongtao Yu   std::function<bool(const Instruction &)> Fn = [=](const Instruction &I) {
105f3c44569SHongtao Yu     return !isa<DbgInfoIntrinsic>(I) &&
106f3c44569SHongtao Yu            !(SkipPseudoOp && isa<PseudoProbeInst>(I));
107147fc016SFlorian Hahn   };
108147fc016SFlorian Hahn   return make_filter_range(*this, Fn);
109147fc016SFlorian Hahn }
110147fc016SFlorian Hahn 
111f3c44569SHongtao Yu iterator_range<
112f3c44569SHongtao Yu     filter_iterator<BasicBlock::iterator, std::function<bool(Instruction &)>>>
instructionsWithoutDebug(bool SkipPseudoOp)113f3c44569SHongtao Yu BasicBlock::instructionsWithoutDebug(bool SkipPseudoOp) {
114f3c44569SHongtao Yu   std::function<bool(Instruction &)> Fn = [=](Instruction &I) {
115f3c44569SHongtao Yu     return !isa<DbgInfoIntrinsic>(I) &&
116f3c44569SHongtao Yu            !(SkipPseudoOp && isa<PseudoProbeInst>(I));
117147fc016SFlorian Hahn   };
118147fc016SFlorian Hahn   return make_filter_range(*this, Fn);
119147fc016SFlorian Hahn }
120147fc016SFlorian Hahn 
1212a47c77eSDavid Tellenbach filter_iterator<BasicBlock::const_iterator,
1222a47c77eSDavid Tellenbach                 std::function<bool(const Instruction &)>>::difference_type
sizeWithoutDebug() const1232a47c77eSDavid Tellenbach BasicBlock::sizeWithoutDebug() const {
1242a47c77eSDavid Tellenbach   return std::distance(instructionsWithoutDebug().begin(),
1252a47c77eSDavid Tellenbach                        instructionsWithoutDebug().end());
1262a47c77eSDavid Tellenbach }
1272a47c77eSDavid Tellenbach 
removeFromParent()128ef860a24SChandler Carruth void BasicBlock::removeFromParent() {
12952888a67SDuncan P. N. Exon Smith   getParent()->getBasicBlockList().remove(getIterator());
130ef860a24SChandler Carruth }
131ef860a24SChandler Carruth 
eraseFromParent()1320bf7ff56SDaniel Berlin iplist<BasicBlock>::iterator BasicBlock::eraseFromParent() {
13352888a67SDuncan P. N. Exon Smith   return getParent()->getBasicBlockList().erase(getIterator());
134ef860a24SChandler Carruth }
135ef860a24SChandler Carruth 
moveBefore(BasicBlock * MovePos)136ef860a24SChandler Carruth void BasicBlock::moveBefore(BasicBlock *MovePos) {
13752888a67SDuncan P. N. Exon Smith   MovePos->getParent()->getBasicBlockList().splice(
13852888a67SDuncan P. N. Exon Smith       MovePos->getIterator(), getParent()->getBasicBlockList(), getIterator());
139ef860a24SChandler Carruth }
140ef860a24SChandler Carruth 
moveAfter(BasicBlock * MovePos)141ef860a24SChandler Carruth void BasicBlock::moveAfter(BasicBlock *MovePos) {
14252888a67SDuncan P. N. Exon Smith   MovePos->getParent()->getBasicBlockList().splice(
14352888a67SDuncan P. N. Exon Smith       ++MovePos->getIterator(), getParent()->getBasicBlockList(),
14452888a67SDuncan P. N. Exon Smith       getIterator());
145ef860a24SChandler Carruth }
146ef860a24SChandler Carruth 
getModule() const14774fb7ac2SCraig Topper const Module *BasicBlock::getModule() const {
14838840245SPhilip Reames   return getParent()->getParent();
14938840245SPhilip Reames }
15038840245SPhilip Reames 
getTerminatingMustTailCall() const15174fb7ac2SCraig Topper const CallInst *BasicBlock::getTerminatingMustTailCall() const {
152e31acf23SReid Kleckner   if (InstList.empty())
153e31acf23SReid Kleckner     return nullptr;
15474fb7ac2SCraig Topper   const ReturnInst *RI = dyn_cast<ReturnInst>(&InstList.back());
155e31acf23SReid Kleckner   if (!RI || RI == &InstList.front())
156e31acf23SReid Kleckner     return nullptr;
157e31acf23SReid Kleckner 
15874fb7ac2SCraig Topper   const Instruction *Prev = RI->getPrevNode();
159e31acf23SReid Kleckner   if (!Prev)
160e31acf23SReid Kleckner     return nullptr;
161e31acf23SReid Kleckner 
162e31acf23SReid Kleckner   if (Value *RV = RI->getReturnValue()) {
163e31acf23SReid Kleckner     if (RV != Prev)
164e31acf23SReid Kleckner       return nullptr;
165e31acf23SReid Kleckner 
166e31acf23SReid Kleckner     // Look through the optional bitcast.
167e31acf23SReid Kleckner     if (auto *BI = dyn_cast<BitCastInst>(Prev)) {
168e31acf23SReid Kleckner       RV = BI->getOperand(0);
169e31acf23SReid Kleckner       Prev = BI->getPrevNode();
170e31acf23SReid Kleckner       if (!Prev || RV != Prev)
171e31acf23SReid Kleckner         return nullptr;
172e31acf23SReid Kleckner     }
173e31acf23SReid Kleckner   }
174e31acf23SReid Kleckner 
175e31acf23SReid Kleckner   if (auto *CI = dyn_cast<CallInst>(Prev)) {
176e31acf23SReid Kleckner     if (CI->isMustTailCall())
177e31acf23SReid Kleckner       return CI;
178e31acf23SReid Kleckner   }
179e31acf23SReid Kleckner   return nullptr;
180e31acf23SReid Kleckner }
181e31acf23SReid Kleckner 
getTerminatingDeoptimizeCall() const18274fb7ac2SCraig Topper const CallInst *BasicBlock::getTerminatingDeoptimizeCall() const {
183b51325dbSSanjoy Das   if (InstList.empty())
184b51325dbSSanjoy Das     return nullptr;
185b51325dbSSanjoy Das   auto *RI = dyn_cast<ReturnInst>(&InstList.back());
186b51325dbSSanjoy Das   if (!RI || RI == &InstList.front())
187b51325dbSSanjoy Das     return nullptr;
188b51325dbSSanjoy Das 
189b51325dbSSanjoy Das   if (auto *CI = dyn_cast_or_null<CallInst>(RI->getPrevNode()))
190b51325dbSSanjoy Das     if (Function *F = CI->getCalledFunction())
191b51325dbSSanjoy Das       if (F->getIntrinsicID() == Intrinsic::experimental_deoptimize)
192b51325dbSSanjoy Das         return CI;
193b51325dbSSanjoy Das 
194b51325dbSSanjoy Das   return nullptr;
195b51325dbSSanjoy Das }
196b51325dbSSanjoy Das 
getPostdominatingDeoptimizeCall() const1978a4d12aeSFedor Sergeev const CallInst *BasicBlock::getPostdominatingDeoptimizeCall() const {
1988a4d12aeSFedor Sergeev   const BasicBlock* BB = this;
199cc7cb05eSFedor Sergeev   SmallPtrSet<const BasicBlock *, 8> Visited;
200cc7cb05eSFedor Sergeev   Visited.insert(BB);
201cc7cb05eSFedor Sergeev   while (auto *Succ = BB->getUniqueSuccessor()) {
202cc7cb05eSFedor Sergeev     if (!Visited.insert(Succ).second)
203cc7cb05eSFedor Sergeev       return nullptr;
204cc7cb05eSFedor Sergeev     BB = Succ;
205cc7cb05eSFedor Sergeev   }
2068a4d12aeSFedor Sergeev   return BB->getTerminatingDeoptimizeCall();
2078a4d12aeSFedor Sergeev }
2088a4d12aeSFedor Sergeev 
getFirstNonPHI() const20974fb7ac2SCraig Topper const Instruction* BasicBlock::getFirstNonPHI() const {
21074fb7ac2SCraig Topper   for (const Instruction &I : *this)
2116cc21f90SDavid Majnemer     if (!isa<PHINode>(I))
2126cc21f90SDavid Majnemer       return &I;
2136cc21f90SDavid Majnemer   return nullptr;
214ef860a24SChandler Carruth }
215ef860a24SChandler Carruth 
getFirstNonPHIOrDbg(bool SkipPseudoOp) const216f3c44569SHongtao Yu const Instruction *BasicBlock::getFirstNonPHIOrDbg(bool SkipPseudoOp) const {
217f3c44569SHongtao Yu   for (const Instruction &I : *this) {
218f3c44569SHongtao Yu     if (isa<PHINode>(I) || isa<DbgInfoIntrinsic>(I))
219f3c44569SHongtao Yu       continue;
220f3c44569SHongtao Yu 
221f3c44569SHongtao Yu     if (SkipPseudoOp && isa<PseudoProbeInst>(I))
222f3c44569SHongtao Yu       continue;
223f3c44569SHongtao Yu 
2246cc21f90SDavid Majnemer     return &I;
225f3c44569SHongtao Yu   }
2266cc21f90SDavid Majnemer   return nullptr;
227ef860a24SChandler Carruth }
228ef860a24SChandler Carruth 
229f3c44569SHongtao Yu const Instruction *
getFirstNonPHIOrDbgOrLifetime(bool SkipPseudoOp) const230f3c44569SHongtao Yu BasicBlock::getFirstNonPHIOrDbgOrLifetime(bool SkipPseudoOp) const {
23174fb7ac2SCraig Topper   for (const Instruction &I : *this) {
2326cc21f90SDavid Majnemer     if (isa<PHINode>(I) || isa<DbgInfoIntrinsic>(I))
233ef860a24SChandler Carruth       continue;
234ef860a24SChandler Carruth 
235b264d69dSVedant Kumar     if (I.isLifetimeStartOrEnd())
2366cc21f90SDavid Majnemer       continue;
2376cc21f90SDavid Majnemer 
238f3c44569SHongtao Yu     if (SkipPseudoOp && isa<PseudoProbeInst>(I))
239f3c44569SHongtao Yu       continue;
240f3c44569SHongtao Yu 
2416cc21f90SDavid Majnemer     return &I;
242ef860a24SChandler Carruth   }
2436cc21f90SDavid Majnemer   return nullptr;
244ef860a24SChandler Carruth }
245ef860a24SChandler Carruth 
getFirstInsertionPt() const24674fb7ac2SCraig Topper BasicBlock::const_iterator BasicBlock::getFirstInsertionPt() const {
24774fb7ac2SCraig Topper   const Instruction *FirstNonPHI = getFirstNonPHI();
2486cc21f90SDavid Majnemer   if (!FirstNonPHI)
2496cc21f90SDavid Majnemer     return end();
2506cc21f90SDavid Majnemer 
25174fb7ac2SCraig Topper   const_iterator InsertPt = FirstNonPHI->getIterator();
252654e130bSDavid Majnemer   if (InsertPt->isEHPad()) ++InsertPt;
253ef860a24SChandler Carruth   return InsertPt;
254ef860a24SChandler Carruth }
255ef860a24SChandler Carruth 
dropAllReferences()256ef860a24SChandler Carruth void BasicBlock::dropAllReferences() {
257af28e7d6SBenjamin Kramer   for (Instruction &I : *this)
258af28e7d6SBenjamin Kramer     I.dropAllReferences();
259ef860a24SChandler Carruth }
260ef860a24SChandler Carruth 
getSinglePredecessor() const26174fb7ac2SCraig Topper const BasicBlock *BasicBlock::getSinglePredecessor() const {
26274fb7ac2SCraig Topper   const_pred_iterator PI = pred_begin(this), E = pred_end(this);
263c620761cSCraig Topper   if (PI == E) return nullptr;         // No preds.
26474fb7ac2SCraig Topper   const BasicBlock *ThePred = *PI;
265ef860a24SChandler Carruth   ++PI;
266c620761cSCraig Topper   return (PI == E) ? ThePred : nullptr /*multiple preds*/;
267ef860a24SChandler Carruth }
268ef860a24SChandler Carruth 
getUniquePredecessor() const26974fb7ac2SCraig Topper const BasicBlock *BasicBlock::getUniquePredecessor() const {
27074fb7ac2SCraig Topper   const_pred_iterator PI = pred_begin(this), E = pred_end(this);
271c620761cSCraig Topper   if (PI == E) return nullptr; // No preds.
27274fb7ac2SCraig Topper   const BasicBlock *PredBB = *PI;
273ef860a24SChandler Carruth   ++PI;
274ef860a24SChandler Carruth   for (;PI != E; ++PI) {
275ef860a24SChandler Carruth     if (*PI != PredBB)
276c620761cSCraig Topper       return nullptr;
277ef860a24SChandler Carruth     // The same predecessor appears multiple times in the predecessor list.
278ef860a24SChandler Carruth     // This is OK.
279ef860a24SChandler Carruth   }
280ef860a24SChandler Carruth   return PredBB;
281ef860a24SChandler Carruth }
282ef860a24SChandler Carruth 
hasNPredecessors(unsigned N) const2834de31bbaSVedant Kumar bool BasicBlock::hasNPredecessors(unsigned N) const {
2844de31bbaSVedant Kumar   return hasNItems(pred_begin(this), pred_end(this), N);
2854de31bbaSVedant Kumar }
2864de31bbaSVedant Kumar 
hasNPredecessorsOrMore(unsigned N) const2874de31bbaSVedant Kumar bool BasicBlock::hasNPredecessorsOrMore(unsigned N) const {
2884de31bbaSVedant Kumar   return hasNItemsOrMore(pred_begin(this), pred_end(this), N);
2894de31bbaSVedant Kumar }
2904de31bbaSVedant Kumar 
getSingleSuccessor() const29174fb7ac2SCraig Topper const BasicBlock *BasicBlock::getSingleSuccessor() const {
2923abcbf99SAlina Sbirlea   const_succ_iterator SI = succ_begin(this), E = succ_end(this);
293154eb5aaSJingyue Wu   if (SI == E) return nullptr; // no successors
29474fb7ac2SCraig Topper   const BasicBlock *TheSucc = *SI;
295154eb5aaSJingyue Wu   ++SI;
296154eb5aaSJingyue Wu   return (SI == E) ? TheSucc : nullptr /* multiple successors */;
297154eb5aaSJingyue Wu }
298154eb5aaSJingyue Wu 
getUniqueSuccessor() const29974fb7ac2SCraig Topper const BasicBlock *BasicBlock::getUniqueSuccessor() const {
3003abcbf99SAlina Sbirlea   const_succ_iterator SI = succ_begin(this), E = succ_end(this);
301083ca9bbSHans Wennborg   if (SI == E) return nullptr; // No successors
30274fb7ac2SCraig Topper   const BasicBlock *SuccBB = *SI;
30347cc673eSPhilip Reames   ++SI;
30447cc673eSPhilip Reames   for (;SI != E; ++SI) {
30547cc673eSPhilip Reames     if (*SI != SuccBB)
306083ca9bbSHans Wennborg       return nullptr;
30747cc673eSPhilip Reames     // The same successor appears multiple times in the successor list.
30847cc673eSPhilip Reames     // This is OK.
30947cc673eSPhilip Reames   }
31047cc673eSPhilip Reames   return SuccBB;
31147cc673eSPhilip Reames }
31247cc673eSPhilip Reames 
phis()3138fa1e373SChandler Carruth iterator_range<BasicBlock::phi_iterator> BasicBlock::phis() {
314344c0920SMatt Arsenault   PHINode *P = empty() ? nullptr : dyn_cast<PHINode>(&*begin());
315344c0920SMatt Arsenault   return make_range<phi_iterator>(P, nullptr);
3168fa1e373SChandler Carruth }
3178fa1e373SChandler Carruth 
removePredecessor(BasicBlock * Pred,bool KeepOneInputPHIs)3186fdd5a28SJay Foad void BasicBlock::removePredecessor(BasicBlock *Pred,
3196fdd5a28SJay Foad                                    bool KeepOneInputPHIs) {
320e5fc9a36SJay Foad   // Use hasNUsesOrMore to bound the cost of this assertion for complex CFGs.
321aa069513SKazu Hirata   assert((hasNUsesOrMore(16) || llvm::is_contained(predecessors(this), Pred)) &&
322e5fc9a36SJay Foad          "Pred is not a predecessor!");
323ef860a24SChandler Carruth 
324e5fc9a36SJay Foad   // Return early if there are no PHI nodes to update.
325b7dee667SMichael Kruse   if (empty() || !isa<PHINode>(begin()))
326e5fc9a36SJay Foad     return;
327ef860a24SChandler Carruth 
328ce134da4SSanjay Patel   unsigned NumPreds = cast<PHINode>(front()).getNumIncomingValues();
329ce134da4SSanjay Patel   for (PHINode &Phi : make_early_inc_range(phis())) {
330355aee3dSSanjay Patel     Phi.removeIncomingValue(Pred, !KeepOneInputPHIs);
331ce134da4SSanjay Patel     if (KeepOneInputPHIs)
332ce134da4SSanjay Patel       continue;
3331dc38f8cSSanjay Patel 
3341dc38f8cSSanjay Patel     // If we have a single predecessor, removeIncomingValue may have erased the
3351dc38f8cSSanjay Patel     // PHI node itself.
3361dc38f8cSSanjay Patel     if (NumPreds == 1)
3371dc38f8cSSanjay Patel       continue;
3381dc38f8cSSanjay Patel 
339ce134da4SSanjay Patel     // Try to replace the PHI node with a constant value.
340ce134da4SSanjay Patel     if (Value *PhiConstant = Phi.hasConstantValue()) {
341ce134da4SSanjay Patel       Phi.replaceAllUsesWith(PhiConstant);
342ce134da4SSanjay Patel       Phi.eraseFromParent();
343ef860a24SChandler Carruth     }
344ef860a24SChandler Carruth   }
345ef860a24SChandler Carruth }
346ef860a24SChandler Carruth 
canSplitPredecessors() const347654e130bSDavid Majnemer bool BasicBlock::canSplitPredecessors() const {
348654e130bSDavid Majnemer   const Instruction *FirstNonPHI = getFirstNonPHI();
349654e130bSDavid Majnemer   if (isa<LandingPadInst>(FirstNonPHI))
350654e130bSDavid Majnemer     return true;
351654e130bSDavid Majnemer   // This is perhaps a little conservative because constructs like
352654e130bSDavid Majnemer   // CleanupBlockInst are pretty easy to split.  However, SplitBlockPredecessors
353654e130bSDavid Majnemer   // cannot handle such things just yet.
354654e130bSDavid Majnemer   if (FirstNonPHI->isEHPad())
355654e130bSDavid Majnemer     return false;
356654e130bSDavid Majnemer   return true;
357654e130bSDavid Majnemer }
358ef860a24SChandler Carruth 
isLegalToHoistInto() const359d4971199SAndrew Kaylor bool BasicBlock::isLegalToHoistInto() const {
360d4971199SAndrew Kaylor   auto *Term = getTerminator();
361d4971199SAndrew Kaylor   // No terminator means the block is under construction.
362d4971199SAndrew Kaylor   if (!Term)
363d4971199SAndrew Kaylor     return true;
364d4971199SAndrew Kaylor 
365d4971199SAndrew Kaylor   // If the block has no successors, there can be no instructions to hoist.
366d4971199SAndrew Kaylor   assert(Term->getNumSuccessors() > 0);
367d4971199SAndrew Kaylor 
368d4971199SAndrew Kaylor   // Instructions should not be hoisted across exception handling boundaries.
369698fbe7bSChandler Carruth   return !Term->isExceptionalTerminator();
370d4971199SAndrew Kaylor }
371d4971199SAndrew Kaylor 
isEntryBlock() const372fb9ed197SNikita Popov bool BasicBlock::isEntryBlock() const {
373fb9ed197SNikita Popov   const Function *F = getParent();
374fb9ed197SNikita Popov   assert(F && "Block must have a parent function to use this API");
375fb9ed197SNikita Popov   return this == &F->getEntryBlock();
376fb9ed197SNikita Popov }
377fb9ed197SNikita Popov 
splitBasicBlock(iterator I,const Twine & BBName,bool Before)3782a814cd9SWhitney Tsang BasicBlock *BasicBlock::splitBasicBlock(iterator I, const Twine &BBName,
3792a814cd9SWhitney Tsang                                         bool Before) {
3802a814cd9SWhitney Tsang   if (Before)
3812a814cd9SWhitney Tsang     return splitBasicBlockBefore(I, BBName);
3822a814cd9SWhitney Tsang 
383ef860a24SChandler Carruth   assert(getTerminator() && "Can't use splitBasicBlock on degenerate BB!");
384ef860a24SChandler Carruth   assert(I != InstList.end() &&
385ef860a24SChandler Carruth          "Trying to get me to create degenerate basic block!");
386ef860a24SChandler Carruth 
387a848c471SDuncan P. N. Exon Smith   BasicBlock *New = BasicBlock::Create(getContext(), BBName, getParent(),
388a848c471SDuncan P. N. Exon Smith                                        this->getNextNode());
389ef860a24SChandler Carruth 
390770f65caSAlexey Samsonov   // Save DebugLoc of split point before invalidating iterator.
391770f65caSAlexey Samsonov   DebugLoc Loc = I->getDebugLoc();
392ef860a24SChandler Carruth   // Move all of the specified instructions from the original basic block into
393ef860a24SChandler Carruth   // the new basic block.
394ef860a24SChandler Carruth   New->getInstList().splice(New->end(), this->getInstList(), I, end());
395ef860a24SChandler Carruth 
396ef860a24SChandler Carruth   // Add a branch instruction to the newly formed basic block.
397770f65caSAlexey Samsonov   BranchInst *BI = BranchInst::Create(New, this);
398770f65caSAlexey Samsonov   BI->setDebugLoc(Loc);
399ef860a24SChandler Carruth 
400ef860a24SChandler Carruth   // Now we must loop through all of the successors of the New block (which
401ef860a24SChandler Carruth   // _were_ the successors of the 'this' block), and update any PHI nodes in
402ef860a24SChandler Carruth   // successors.  If there were PHI nodes in the successors, then they need to
40302569408SRoman Lebedev   // know that incoming branches will be from New, not from Old (this).
404ef860a24SChandler Carruth   //
40502569408SRoman Lebedev   New->replaceSuccessorsPhiUsesWith(this, New);
406ef860a24SChandler Carruth   return New;
407ef860a24SChandler Carruth }
408ef860a24SChandler Carruth 
splitBasicBlockBefore(iterator I,const Twine & BBName)4092a814cd9SWhitney Tsang BasicBlock *BasicBlock::splitBasicBlockBefore(iterator I, const Twine &BBName) {
4102a814cd9SWhitney Tsang   assert(getTerminator() &&
4112a814cd9SWhitney Tsang          "Can't use splitBasicBlockBefore on degenerate BB!");
4122a814cd9SWhitney Tsang   assert(I != InstList.end() &&
4132a814cd9SWhitney Tsang          "Trying to get me to create degenerate basic block!");
4142a814cd9SWhitney Tsang 
4152a814cd9SWhitney Tsang   assert((!isa<PHINode>(*I) || getSinglePredecessor()) &&
4162a814cd9SWhitney Tsang          "cannot split on multi incoming phis");
4172a814cd9SWhitney Tsang 
4182a814cd9SWhitney Tsang   BasicBlock *New = BasicBlock::Create(getContext(), BBName, getParent(), this);
4192a814cd9SWhitney Tsang   // Save DebugLoc of split point before invalidating iterator.
4202a814cd9SWhitney Tsang   DebugLoc Loc = I->getDebugLoc();
4212a814cd9SWhitney Tsang   // Move all of the specified instructions from the original basic block into
4222a814cd9SWhitney Tsang   // the new basic block.
4232a814cd9SWhitney Tsang   New->getInstList().splice(New->end(), this->getInstList(), begin(), I);
4242a814cd9SWhitney Tsang 
4252a814cd9SWhitney Tsang   // Loop through all of the predecessors of the 'this' block (which will be the
4262a814cd9SWhitney Tsang   // predecessors of the New block), replace the specified successor 'this'
4272a814cd9SWhitney Tsang   // block to point at the New block and update any PHI nodes in 'this' block.
4282a814cd9SWhitney Tsang   // If there were PHI nodes in 'this' block, the PHI nodes are updated
4292a814cd9SWhitney Tsang   // to reflect that the incoming branches will be from the New block and not
4302a814cd9SWhitney Tsang   // from predecessors of the 'this' block.
4312a814cd9SWhitney Tsang   for (BasicBlock *Pred : predecessors(this)) {
4322a814cd9SWhitney Tsang     Instruction *TI = Pred->getTerminator();
4332a814cd9SWhitney Tsang     TI->replaceSuccessorWith(this, New);
4342a814cd9SWhitney Tsang     this->replacePhiUsesWith(Pred, New);
4352a814cd9SWhitney Tsang   }
4362a814cd9SWhitney Tsang   // Add a branch instruction from  "New" to "this" Block.
4372a814cd9SWhitney Tsang   BranchInst *BI = BranchInst::Create(this, New);
4382a814cd9SWhitney Tsang   BI->setDebugLoc(Loc);
4392a814cd9SWhitney Tsang 
4402a814cd9SWhitney Tsang   return New;
4412a814cd9SWhitney Tsang }
4422a814cd9SWhitney Tsang 
replacePhiUsesWith(BasicBlock * Old,BasicBlock * New)4431a1b9221SRoman Lebedev void BasicBlock::replacePhiUsesWith(BasicBlock *Old, BasicBlock *New) {
4441a1b9221SRoman Lebedev   // N.B. This might not be a complete BasicBlock, so don't assume
4451a1b9221SRoman Lebedev   // that it ends with a non-phi instruction.
446c23ebf17SKazu Hirata   for (Instruction &I : *this) {
447c23ebf17SKazu Hirata     PHINode *PN = dyn_cast<PHINode>(&I);
44876f6b125SOliver Stannard     if (!PN)
44976f6b125SOliver Stannard       break;
45076f6b125SOliver Stannard     PN->replaceIncomingBlockWith(Old, New);
45176f6b125SOliver Stannard   }
4521a1b9221SRoman Lebedev }
4531a1b9221SRoman Lebedev 
replaceSuccessorsPhiUsesWith(BasicBlock * Old,BasicBlock * New)45402569408SRoman Lebedev void BasicBlock::replaceSuccessorsPhiUsesWith(BasicBlock *Old,
45502569408SRoman Lebedev                                               BasicBlock *New) {
456edb12a83SChandler Carruth   Instruction *TI = getTerminator();
457ef860a24SChandler Carruth   if (!TI)
458ef860a24SChandler Carruth     // Cope with being called on a BasicBlock that doesn't have a terminator
459ef860a24SChandler Carruth     // yet. Clang's CodeGenFunction::EmitReturnBlock() likes to do this.
460ef860a24SChandler Carruth     return;
4616a337f85SKazu Hirata   for (BasicBlock *Succ : successors(TI))
46202569408SRoman Lebedev     Succ->replacePhiUsesWith(Old, New);
463ef860a24SChandler Carruth }
464ef860a24SChandler Carruth 
replaceSuccessorsPhiUsesWith(BasicBlock * New)46502569408SRoman Lebedev void BasicBlock::replaceSuccessorsPhiUsesWith(BasicBlock *New) {
46602569408SRoman Lebedev   this->replaceSuccessorsPhiUsesWith(this, New);
46702569408SRoman Lebedev }
46802569408SRoman Lebedev 
isLandingPad() const469ef860a24SChandler Carruth bool BasicBlock::isLandingPad() const {
470ef860a24SChandler Carruth   return isa<LandingPadInst>(getFirstNonPHI());
471ef860a24SChandler Carruth }
472ef860a24SChandler Carruth 
getLandingPadInst() const473ef860a24SChandler Carruth const LandingPadInst *BasicBlock::getLandingPadInst() const {
474ef860a24SChandler Carruth   return dyn_cast<LandingPadInst>(getFirstNonPHI());
475ef860a24SChandler Carruth }
476dce9def3SHiroshi Yamauchi 
getIrrLoopHeaderWeight() const477dce9def3SHiroshi Yamauchi Optional<uint64_t> BasicBlock::getIrrLoopHeaderWeight() const {
478edb12a83SChandler Carruth   const Instruction *TI = getTerminator();
479dce9def3SHiroshi Yamauchi   if (MDNode *MDIrrLoopHeader =
480dce9def3SHiroshi Yamauchi       TI->getMetadata(LLVMContext::MD_irr_loop)) {
481dce9def3SHiroshi Yamauchi     MDString *MDName = cast<MDString>(MDIrrLoopHeader->getOperand(0));
482dce9def3SHiroshi Yamauchi     if (MDName->getString().equals("loop_header_weight")) {
483dce9def3SHiroshi Yamauchi       auto *CI = mdconst::extract<ConstantInt>(MDIrrLoopHeader->getOperand(1));
484dce9def3SHiroshi Yamauchi       return Optional<uint64_t>(CI->getValue().getZExtValue());
485dce9def3SHiroshi Yamauchi     }
486dce9def3SHiroshi Yamauchi   }
487dce9def3SHiroshi Yamauchi   return Optional<uint64_t>();
488dce9def3SHiroshi Yamauchi }
489f01827f2SVedant Kumar 
skipDebugIntrinsics(BasicBlock::iterator It)4901cb63dc2SVedant Kumar BasicBlock::iterator llvm::skipDebugIntrinsics(BasicBlock::iterator It) {
491f01827f2SVedant Kumar   while (isa<DbgInfoIntrinsic>(It))
492f01827f2SVedant Kumar     ++It;
493f01827f2SVedant Kumar   return It;
494f01827f2SVedant Kumar }
4950c2b09a9SReid Kleckner 
renumberInstructions()4960c2b09a9SReid Kleckner void BasicBlock::renumberInstructions() {
4970c2b09a9SReid Kleckner   unsigned Order = 0;
4980c2b09a9SReid Kleckner   for (Instruction &I : *this)
4990c2b09a9SReid Kleckner     I.Order = Order++;
5000c2b09a9SReid Kleckner 
5010c2b09a9SReid Kleckner   // Set the bit to indicate that the instruction order valid and cached.
5020c2b09a9SReid Kleckner   BasicBlockBits Bits = getBasicBlockBits();
5030c2b09a9SReid Kleckner   Bits.InstrOrderValid = true;
5040c2b09a9SReid Kleckner   setBasicBlockBits(Bits);
505de5477edSPhilip Reames 
506de5477edSPhilip Reames   NumInstrRenumberings++;
5070c2b09a9SReid Kleckner }
5080c2b09a9SReid Kleckner 
5090c2b09a9SReid Kleckner #ifndef NDEBUG
5100c2b09a9SReid Kleckner /// In asserts builds, this checks the numbering. In non-asserts builds, it
511446b1500SReid Kleckner /// is defined as a no-op inline function in BasicBlock.h.
validateInstrOrdering() const5120c2b09a9SReid Kleckner void BasicBlock::validateInstrOrdering() const {
5130c2b09a9SReid Kleckner   if (!isInstrOrderValid())
5140c2b09a9SReid Kleckner     return;
5150c2b09a9SReid Kleckner   const Instruction *Prev = nullptr;
5160c2b09a9SReid Kleckner   for (const Instruction &I : *this) {
5170c2b09a9SReid Kleckner     assert((!Prev || Prev->comesBefore(&I)) &&
5180c2b09a9SReid Kleckner            "cached instruction ordering is incorrect");
5190c2b09a9SReid Kleckner     Prev = &I;
5200c2b09a9SReid Kleckner   }
5210c2b09a9SReid Kleckner }
5220c2b09a9SReid Kleckner #endif
523