[LLVM][Alignment] Introduce Alignment In Attributes
[llvm-core.git] / lib / IR / BasicBlock.cpp
blob34410712645dad2e3645a48b8fc72b871028d517
1 //===-- BasicBlock.cpp - Implement BasicBlock related methods -------------===//
2 //
3 // 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
6 //
7 //===----------------------------------------------------------------------===//
8 //
9 // This file implements the BasicBlock class for the IR library.
11 //===----------------------------------------------------------------------===//
13 #include "llvm/IR/BasicBlock.h"
14 #include "SymbolTableListTraitsImpl.h"
15 #include "llvm/ADT/STLExtras.h"
16 #include "llvm/IR/CFG.h"
17 #include "llvm/IR/Constants.h"
18 #include "llvm/IR/Instructions.h"
19 #include "llvm/IR/IntrinsicInst.h"
20 #include "llvm/IR/LLVMContext.h"
21 #include "llvm/IR/Type.h"
22 #include <algorithm>
24 using namespace llvm;
26 ValueSymbolTable *BasicBlock::getValueSymbolTable() {
27 if (Function *F = getParent())
28 return F->getValueSymbolTable();
29 return nullptr;
32 LLVMContext &BasicBlock::getContext() const {
33 return getType()->getContext();
36 // Explicit instantiation of SymbolTableListTraits since some of the methods
37 // are not in the public header file...
38 template class llvm::SymbolTableListTraits<Instruction>;
40 BasicBlock::BasicBlock(LLVMContext &C, const Twine &Name, Function *NewParent,
41 BasicBlock *InsertBefore)
42 : Value(Type::getLabelTy(C), Value::BasicBlockVal), Parent(nullptr) {
44 if (NewParent)
45 insertInto(NewParent, InsertBefore);
46 else
47 assert(!InsertBefore &&
48 "Cannot insert block before another block with no function!");
50 setName(Name);
53 void BasicBlock::insertInto(Function *NewParent, BasicBlock *InsertBefore) {
54 assert(NewParent && "Expected a parent");
55 assert(!Parent && "Already has a parent");
57 if (InsertBefore)
58 NewParent->getBasicBlockList().insert(InsertBefore->getIterator(), this);
59 else
60 NewParent->getBasicBlockList().push_back(this);
63 BasicBlock::~BasicBlock() {
64 // If the address of the block is taken and it is being deleted (e.g. because
65 // it is dead), this means that there is either a dangling constant expr
66 // hanging off the block, or an undefined use of the block (source code
67 // expecting the address of a label to keep the block alive even though there
68 // is no indirect branch). Handle these cases by zapping the BlockAddress
69 // nodes. There are no other possible uses at this point.
70 if (hasAddressTaken()) {
71 assert(!use_empty() && "There should be at least one blockaddress!");
72 Constant *Replacement =
73 ConstantInt::get(llvm::Type::getInt32Ty(getContext()), 1);
74 while (!use_empty()) {
75 BlockAddress *BA = cast<BlockAddress>(user_back());
76 BA->replaceAllUsesWith(ConstantExpr::getIntToPtr(Replacement,
77 BA->getType()));
78 BA->destroyConstant();
82 assert(getParent() == nullptr && "BasicBlock still linked into the program!");
83 dropAllReferences();
84 InstList.clear();
87 void BasicBlock::setParent(Function *parent) {
88 // Set Parent=parent, updating instruction symtab entries as appropriate.
89 InstList.setSymTabObject(&Parent, parent);
92 iterator_range<filter_iterator<BasicBlock::const_iterator,
93 std::function<bool(const Instruction &)>>>
94 BasicBlock::instructionsWithoutDebug() const {
95 std::function<bool(const Instruction &)> Fn = [](const Instruction &I) {
96 return !isa<DbgInfoIntrinsic>(I);
98 return make_filter_range(*this, Fn);
101 iterator_range<filter_iterator<BasicBlock::iterator,
102 std::function<bool(Instruction &)>>>
103 BasicBlock::instructionsWithoutDebug() {
104 std::function<bool(Instruction &)> Fn = [](Instruction &I) {
105 return !isa<DbgInfoIntrinsic>(I);
107 return make_filter_range(*this, Fn);
110 void BasicBlock::removeFromParent() {
111 getParent()->getBasicBlockList().remove(getIterator());
114 iplist<BasicBlock>::iterator BasicBlock::eraseFromParent() {
115 return getParent()->getBasicBlockList().erase(getIterator());
118 /// Unlink this basic block from its current function and
119 /// insert it into the function that MovePos lives in, right before MovePos.
120 void BasicBlock::moveBefore(BasicBlock *MovePos) {
121 MovePos->getParent()->getBasicBlockList().splice(
122 MovePos->getIterator(), getParent()->getBasicBlockList(), getIterator());
125 /// Unlink this basic block from its current function and
126 /// insert it into the function that MovePos lives in, right after MovePos.
127 void BasicBlock::moveAfter(BasicBlock *MovePos) {
128 MovePos->getParent()->getBasicBlockList().splice(
129 ++MovePos->getIterator(), getParent()->getBasicBlockList(),
130 getIterator());
133 const Module *BasicBlock::getModule() const {
134 return getParent()->getParent();
137 const Instruction *BasicBlock::getTerminator() const {
138 if (InstList.empty() || !InstList.back().isTerminator())
139 return nullptr;
140 return &InstList.back();
143 const CallInst *BasicBlock::getTerminatingMustTailCall() const {
144 if (InstList.empty())
145 return nullptr;
146 const ReturnInst *RI = dyn_cast<ReturnInst>(&InstList.back());
147 if (!RI || RI == &InstList.front())
148 return nullptr;
150 const Instruction *Prev = RI->getPrevNode();
151 if (!Prev)
152 return nullptr;
154 if (Value *RV = RI->getReturnValue()) {
155 if (RV != Prev)
156 return nullptr;
158 // Look through the optional bitcast.
159 if (auto *BI = dyn_cast<BitCastInst>(Prev)) {
160 RV = BI->getOperand(0);
161 Prev = BI->getPrevNode();
162 if (!Prev || RV != Prev)
163 return nullptr;
167 if (auto *CI = dyn_cast<CallInst>(Prev)) {
168 if (CI->isMustTailCall())
169 return CI;
171 return nullptr;
174 const CallInst *BasicBlock::getTerminatingDeoptimizeCall() const {
175 if (InstList.empty())
176 return nullptr;
177 auto *RI = dyn_cast<ReturnInst>(&InstList.back());
178 if (!RI || RI == &InstList.front())
179 return nullptr;
181 if (auto *CI = dyn_cast_or_null<CallInst>(RI->getPrevNode()))
182 if (Function *F = CI->getCalledFunction())
183 if (F->getIntrinsicID() == Intrinsic::experimental_deoptimize)
184 return CI;
186 return nullptr;
189 const Instruction* BasicBlock::getFirstNonPHI() const {
190 for (const Instruction &I : *this)
191 if (!isa<PHINode>(I))
192 return &I;
193 return nullptr;
196 const Instruction* BasicBlock::getFirstNonPHIOrDbg() const {
197 for (const Instruction &I : *this)
198 if (!isa<PHINode>(I) && !isa<DbgInfoIntrinsic>(I))
199 return &I;
200 return nullptr;
203 const Instruction* BasicBlock::getFirstNonPHIOrDbgOrLifetime() const {
204 for (const Instruction &I : *this) {
205 if (isa<PHINode>(I) || isa<DbgInfoIntrinsic>(I))
206 continue;
208 if (I.isLifetimeStartOrEnd())
209 continue;
211 return &I;
213 return nullptr;
216 BasicBlock::const_iterator BasicBlock::getFirstInsertionPt() const {
217 const Instruction *FirstNonPHI = getFirstNonPHI();
218 if (!FirstNonPHI)
219 return end();
221 const_iterator InsertPt = FirstNonPHI->getIterator();
222 if (InsertPt->isEHPad()) ++InsertPt;
223 return InsertPt;
226 void BasicBlock::dropAllReferences() {
227 for (Instruction &I : *this)
228 I.dropAllReferences();
231 /// If this basic block has a single predecessor block,
232 /// return the block, otherwise return a null pointer.
233 const BasicBlock *BasicBlock::getSinglePredecessor() const {
234 const_pred_iterator PI = pred_begin(this), E = pred_end(this);
235 if (PI == E) return nullptr; // No preds.
236 const BasicBlock *ThePred = *PI;
237 ++PI;
238 return (PI == E) ? ThePred : nullptr /*multiple preds*/;
241 /// If this basic block has a unique predecessor block,
242 /// return the block, otherwise return a null pointer.
243 /// Note that unique predecessor doesn't mean single edge, there can be
244 /// multiple edges from the unique predecessor to this block (for example
245 /// a switch statement with multiple cases having the same destination).
246 const BasicBlock *BasicBlock::getUniquePredecessor() const {
247 const_pred_iterator PI = pred_begin(this), E = pred_end(this);
248 if (PI == E) return nullptr; // No preds.
249 const BasicBlock *PredBB = *PI;
250 ++PI;
251 for (;PI != E; ++PI) {
252 if (*PI != PredBB)
253 return nullptr;
254 // The same predecessor appears multiple times in the predecessor list.
255 // This is OK.
257 return PredBB;
260 bool BasicBlock::hasNPredecessors(unsigned N) const {
261 return hasNItems(pred_begin(this), pred_end(this), N);
264 bool BasicBlock::hasNPredecessorsOrMore(unsigned N) const {
265 return hasNItemsOrMore(pred_begin(this), pred_end(this), N);
268 const BasicBlock *BasicBlock::getSingleSuccessor() const {
269 succ_const_iterator SI = succ_begin(this), E = succ_end(this);
270 if (SI == E) return nullptr; // no successors
271 const BasicBlock *TheSucc = *SI;
272 ++SI;
273 return (SI == E) ? TheSucc : nullptr /* multiple successors */;
276 const BasicBlock *BasicBlock::getUniqueSuccessor() const {
277 succ_const_iterator SI = succ_begin(this), E = succ_end(this);
278 if (SI == E) return nullptr; // No successors
279 const BasicBlock *SuccBB = *SI;
280 ++SI;
281 for (;SI != E; ++SI) {
282 if (*SI != SuccBB)
283 return nullptr;
284 // The same successor appears multiple times in the successor list.
285 // This is OK.
287 return SuccBB;
290 iterator_range<BasicBlock::phi_iterator> BasicBlock::phis() {
291 PHINode *P = empty() ? nullptr : dyn_cast<PHINode>(&*begin());
292 return make_range<phi_iterator>(P, nullptr);
295 /// This method is used to notify a BasicBlock that the
296 /// specified Predecessor of the block is no longer able to reach it. This is
297 /// actually not used to update the Predecessor list, but is actually used to
298 /// update the PHI nodes that reside in the block. Note that this should be
299 /// called while the predecessor still refers to this block.
301 void BasicBlock::removePredecessor(BasicBlock *Pred,
302 bool KeepOneInputPHIs) {
303 assert((hasNUsesOrMore(16)||// Reduce cost of this assertion for complex CFGs.
304 find(pred_begin(this), pred_end(this), Pred) != pred_end(this)) &&
305 "removePredecessor: BB is not a predecessor!");
307 if (InstList.empty()) return;
308 PHINode *APN = dyn_cast<PHINode>(&front());
309 if (!APN) return; // Quick exit.
311 // If there are exactly two predecessors, then we want to nuke the PHI nodes
312 // altogether. However, we cannot do this, if this in this case:
314 // Loop:
315 // %x = phi [X, Loop]
316 // %x2 = add %x, 1 ;; This would become %x2 = add %x2, 1
317 // br Loop ;; %x2 does not dominate all uses
319 // This is because the PHI node input is actually taken from the predecessor
320 // basic block. The only case this can happen is with a self loop, so we
321 // check for this case explicitly now.
323 unsigned max_idx = APN->getNumIncomingValues();
324 assert(max_idx != 0 && "PHI Node in block with 0 predecessors!?!?!");
325 if (max_idx == 2) {
326 BasicBlock *Other = APN->getIncomingBlock(APN->getIncomingBlock(0) == Pred);
328 // Disable PHI elimination!
329 if (this == Other) max_idx = 3;
332 // <= Two predecessors BEFORE I remove one?
333 if (max_idx <= 2 && !KeepOneInputPHIs) {
334 // Yup, loop through and nuke the PHI nodes
335 while (PHINode *PN = dyn_cast<PHINode>(&front())) {
336 // Remove the predecessor first.
337 PN->removeIncomingValue(Pred, !KeepOneInputPHIs);
339 // If the PHI _HAD_ two uses, replace PHI node with its now *single* value
340 if (max_idx == 2) {
341 if (PN->getIncomingValue(0) != PN)
342 PN->replaceAllUsesWith(PN->getIncomingValue(0));
343 else
344 // We are left with an infinite loop with no entries: kill the PHI.
345 PN->replaceAllUsesWith(UndefValue::get(PN->getType()));
346 getInstList().pop_front(); // Remove the PHI node
349 // If the PHI node already only had one entry, it got deleted by
350 // removeIncomingValue.
352 } else {
353 // Okay, now we know that we need to remove predecessor #pred_idx from all
354 // PHI nodes. Iterate over each PHI node fixing them up
355 PHINode *PN;
356 for (iterator II = begin(); (PN = dyn_cast<PHINode>(II)); ) {
357 ++II;
358 PN->removeIncomingValue(Pred, false);
359 // If all incoming values to the Phi are the same, we can replace the Phi
360 // with that value.
361 Value* PNV = nullptr;
362 if (!KeepOneInputPHIs && (PNV = PN->hasConstantValue()))
363 if (PNV != PN) {
364 PN->replaceAllUsesWith(PNV);
365 PN->eraseFromParent();
371 bool BasicBlock::canSplitPredecessors() const {
372 const Instruction *FirstNonPHI = getFirstNonPHI();
373 if (isa<LandingPadInst>(FirstNonPHI))
374 return true;
375 // This is perhaps a little conservative because constructs like
376 // CleanupBlockInst are pretty easy to split. However, SplitBlockPredecessors
377 // cannot handle such things just yet.
378 if (FirstNonPHI->isEHPad())
379 return false;
380 return true;
383 bool BasicBlock::isLegalToHoistInto() const {
384 auto *Term = getTerminator();
385 // No terminator means the block is under construction.
386 if (!Term)
387 return true;
389 // If the block has no successors, there can be no instructions to hoist.
390 assert(Term->getNumSuccessors() > 0);
392 // Instructions should not be hoisted across exception handling boundaries.
393 return !Term->isExceptionalTerminator();
396 /// This splits a basic block into two at the specified
397 /// instruction. Note that all instructions BEFORE the specified iterator stay
398 /// as part of the original basic block, an unconditional branch is added to
399 /// the new BB, and the rest of the instructions in the BB are moved to the new
400 /// BB, including the old terminator. This invalidates the iterator.
402 /// Note that this only works on well formed basic blocks (must have a
403 /// terminator), and 'I' must not be the end of instruction list (which would
404 /// cause a degenerate basic block to be formed, having a terminator inside of
405 /// the basic block).
407 BasicBlock *BasicBlock::splitBasicBlock(iterator I, const Twine &BBName) {
408 assert(getTerminator() && "Can't use splitBasicBlock on degenerate BB!");
409 assert(I != InstList.end() &&
410 "Trying to get me to create degenerate basic block!");
412 BasicBlock *New = BasicBlock::Create(getContext(), BBName, getParent(),
413 this->getNextNode());
415 // Save DebugLoc of split point before invalidating iterator.
416 DebugLoc Loc = I->getDebugLoc();
417 // Move all of the specified instructions from the original basic block into
418 // the new basic block.
419 New->getInstList().splice(New->end(), this->getInstList(), I, end());
421 // Add a branch instruction to the newly formed basic block.
422 BranchInst *BI = BranchInst::Create(New, this);
423 BI->setDebugLoc(Loc);
425 // Now we must loop through all of the successors of the New block (which
426 // _were_ the successors of the 'this' block), and update any PHI nodes in
427 // successors. If there were PHI nodes in the successors, then they need to
428 // know that incoming branches will be from New, not from Old (this).
430 New->replaceSuccessorsPhiUsesWith(this, New);
431 return New;
434 void BasicBlock::replacePhiUsesWith(BasicBlock *Old, BasicBlock *New) {
435 // N.B. This might not be a complete BasicBlock, so don't assume
436 // that it ends with a non-phi instruction.
437 for (iterator II = begin(), IE = end(); II != IE; ++II) {
438 PHINode *PN = dyn_cast<PHINode>(II);
439 if (!PN)
440 break;
441 PN->replaceIncomingBlockWith(Old, New);
445 void BasicBlock::replaceSuccessorsPhiUsesWith(BasicBlock *Old,
446 BasicBlock *New) {
447 Instruction *TI = getTerminator();
448 if (!TI)
449 // Cope with being called on a BasicBlock that doesn't have a terminator
450 // yet. Clang's CodeGenFunction::EmitReturnBlock() likes to do this.
451 return;
452 llvm::for_each(successors(TI), [Old, New](BasicBlock *Succ) {
453 Succ->replacePhiUsesWith(Old, New);
457 void BasicBlock::replaceSuccessorsPhiUsesWith(BasicBlock *New) {
458 this->replaceSuccessorsPhiUsesWith(this, New);
461 /// Return true if this basic block is a landing pad. I.e., it's
462 /// the destination of the 'unwind' edge of an invoke instruction.
463 bool BasicBlock::isLandingPad() const {
464 return isa<LandingPadInst>(getFirstNonPHI());
467 /// Return the landingpad instruction associated with the landing pad.
468 const LandingPadInst *BasicBlock::getLandingPadInst() const {
469 return dyn_cast<LandingPadInst>(getFirstNonPHI());
472 Optional<uint64_t> BasicBlock::getIrrLoopHeaderWeight() const {
473 const Instruction *TI = getTerminator();
474 if (MDNode *MDIrrLoopHeader =
475 TI->getMetadata(LLVMContext::MD_irr_loop)) {
476 MDString *MDName = cast<MDString>(MDIrrLoopHeader->getOperand(0));
477 if (MDName->getString().equals("loop_header_weight")) {
478 auto *CI = mdconst::extract<ConstantInt>(MDIrrLoopHeader->getOperand(1));
479 return Optional<uint64_t>(CI->getValue().getZExtValue());
482 return Optional<uint64_t>();
485 BasicBlock::iterator llvm::skipDebugIntrinsics(BasicBlock::iterator It) {
486 while (isa<DbgInfoIntrinsic>(It))
487 ++It;
488 return It;