1 //===- llvm/CodeGen/MachineBasicBlock.h -------------------------*- C++ -*-===//
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
7 //===----------------------------------------------------------------------===//
9 // Collect the sequence of machine instructions for a basic block.
11 //===----------------------------------------------------------------------===//
13 #ifndef LLVM_CODEGEN_MACHINEBASICBLOCK_H
14 #define LLVM_CODEGEN_MACHINEBASICBLOCK_H
16 #include "llvm/ADT/GraphTraits.h"
17 #include "llvm/ADT/ilist.h"
18 #include "llvm/ADT/ilist_node.h"
19 #include "llvm/ADT/iterator_range.h"
20 #include "llvm/ADT/simple_ilist.h"
21 #include "llvm/CodeGen/MachineInstr.h"
22 #include "llvm/CodeGen/MachineInstrBundleIterator.h"
23 #include "llvm/IR/DebugLoc.h"
24 #include "llvm/MC/LaneBitmask.h"
25 #include "llvm/MC/MCRegisterInfo.h"
26 #include "llvm/Support/BranchProbability.h"
27 #include "llvm/Support/Printable.h"
38 class MachineFunction
;
40 class ModuleSlotTracker
;
45 class TargetRegisterClass
;
46 class TargetRegisterInfo
;
48 template <> struct ilist_traits
<MachineInstr
> {
50 friend class MachineBasicBlock
; // Set by the owning MachineBasicBlock.
52 MachineBasicBlock
*Parent
;
54 using instr_iterator
=
55 simple_ilist
<MachineInstr
, ilist_sentinel_tracking
<true>>::iterator
;
58 void addNodeToList(MachineInstr
*N
);
59 void removeNodeFromList(MachineInstr
*N
);
60 void transferNodesFromList(ilist_traits
&FromList
, instr_iterator First
,
62 void deleteNode(MachineInstr
*MI
);
65 class MachineBasicBlock
66 : public ilist_node_with_parent
<MachineBasicBlock
, MachineFunction
> {
68 /// Pair of physical register and lane mask.
69 /// This is not simply a std::pair typedef because the members should be named
70 /// clearly as they both have an integer type.
71 struct RegisterMaskPair
{
76 RegisterMaskPair(MCPhysReg PhysReg
, LaneBitmask LaneMask
)
77 : PhysReg(PhysReg
), LaneMask(LaneMask
) {}
81 using Instructions
= ilist
<MachineInstr
, ilist_sentinel_tracking
<true>>;
86 MachineFunction
*xParent
;
88 /// Keep track of the predecessor / successor basic blocks.
89 std::vector
<MachineBasicBlock
*> Predecessors
;
90 std::vector
<MachineBasicBlock
*> Successors
;
92 /// Keep track of the probabilities to the successors. This vector has the
93 /// same order as Successors, or it is empty if we don't use it (disable
95 std::vector
<BranchProbability
> Probs
;
96 using probability_iterator
= std::vector
<BranchProbability
>::iterator
;
97 using const_probability_iterator
=
98 std::vector
<BranchProbability
>::const_iterator
;
100 Optional
<uint64_t> IrrLoopHeaderWeight
;
102 /// Keep track of the physical registers that are livein of the basicblock.
103 using LiveInVector
= std::vector
<RegisterMaskPair
>;
104 LiveInVector LiveIns
;
106 /// Alignment of the basic block. One if the basic block does not need to be
108 llvm::Align Alignment
;
110 /// Indicate that this basic block is entered via an exception handler.
111 bool IsEHPad
= false;
113 /// Indicate that this basic block is potentially the target of an indirect
115 bool AddressTaken
= false;
117 /// Indicate that this basic block needs its symbol be emitted regardless of
118 /// whether the flow just falls-through to it.
119 bool LabelMustBeEmitted
= false;
121 /// Indicate that this basic block is the entry block of an EH scope, i.e.,
122 /// the block that used to have a catchpad or cleanuppad instruction in the
124 bool IsEHScopeEntry
= false;
126 /// Indicate that this basic block is the entry block of an EH funclet.
127 bool IsEHFuncletEntry
= false;
129 /// Indicate that this basic block is the entry block of a cleanup funclet.
130 bool IsCleanupFuncletEntry
= false;
132 /// since getSymbol is a relatively heavy-weight operation, the symbol
133 /// is only computed once and is cached.
134 mutable MCSymbol
*CachedMCSymbol
= nullptr;
136 // Intrusive list support
137 MachineBasicBlock() = default;
139 explicit MachineBasicBlock(MachineFunction
&MF
, const BasicBlock
*BB
);
141 ~MachineBasicBlock();
143 // MachineBasicBlocks are allocated and owned by MachineFunction.
144 friend class MachineFunction
;
147 /// Return the LLVM basic block that this instance corresponded to originally.
148 /// Note that this may be NULL if this instance does not correspond directly
149 /// to an LLVM basic block.
150 const BasicBlock
*getBasicBlock() const { return BB
; }
152 /// Return the name of the corresponding LLVM basic block, or an empty string.
153 StringRef
getName() const;
155 /// Return a formatted string to identify this block and its parent function.
156 std::string
getFullName() const;
158 /// Test whether this block is potentially the target of an indirect branch.
159 bool hasAddressTaken() const { return AddressTaken
; }
161 /// Set this block to reflect that it potentially is the target of an indirect
163 void setHasAddressTaken() { AddressTaken
= true; }
165 /// Test whether this block must have its label emitted.
166 bool hasLabelMustBeEmitted() const { return LabelMustBeEmitted
; }
168 /// Set this block to reflect that, regardless how we flow to it, we need
169 /// its label be emitted.
170 void setLabelMustBeEmitted() { LabelMustBeEmitted
= true; }
172 /// Return the MachineFunction containing this basic block.
173 const MachineFunction
*getParent() const { return xParent
; }
174 MachineFunction
*getParent() { return xParent
; }
176 using instr_iterator
= Instructions::iterator
;
177 using const_instr_iterator
= Instructions::const_iterator
;
178 using reverse_instr_iterator
= Instructions::reverse_iterator
;
179 using const_reverse_instr_iterator
= Instructions::const_reverse_iterator
;
181 using iterator
= MachineInstrBundleIterator
<MachineInstr
>;
182 using const_iterator
= MachineInstrBundleIterator
<const MachineInstr
>;
183 using reverse_iterator
= MachineInstrBundleIterator
<MachineInstr
, true>;
184 using const_reverse_iterator
=
185 MachineInstrBundleIterator
<const MachineInstr
, true>;
187 unsigned size() const { return (unsigned)Insts
.size(); }
188 bool empty() const { return Insts
.empty(); }
190 MachineInstr
&instr_front() { return Insts
.front(); }
191 MachineInstr
&instr_back() { return Insts
.back(); }
192 const MachineInstr
&instr_front() const { return Insts
.front(); }
193 const MachineInstr
&instr_back() const { return Insts
.back(); }
195 MachineInstr
&front() { return Insts
.front(); }
196 MachineInstr
&back() { return *--end(); }
197 const MachineInstr
&front() const { return Insts
.front(); }
198 const MachineInstr
&back() const { return *--end(); }
200 instr_iterator
instr_begin() { return Insts
.begin(); }
201 const_instr_iterator
instr_begin() const { return Insts
.begin(); }
202 instr_iterator
instr_end() { return Insts
.end(); }
203 const_instr_iterator
instr_end() const { return Insts
.end(); }
204 reverse_instr_iterator
instr_rbegin() { return Insts
.rbegin(); }
205 const_reverse_instr_iterator
instr_rbegin() const { return Insts
.rbegin(); }
206 reverse_instr_iterator
instr_rend () { return Insts
.rend(); }
207 const_reverse_instr_iterator
instr_rend () const { return Insts
.rend(); }
209 using instr_range
= iterator_range
<instr_iterator
>;
210 using const_instr_range
= iterator_range
<const_instr_iterator
>;
211 instr_range
instrs() { return instr_range(instr_begin(), instr_end()); }
212 const_instr_range
instrs() const {
213 return const_instr_range(instr_begin(), instr_end());
216 iterator
begin() { return instr_begin(); }
217 const_iterator
begin() const { return instr_begin(); }
218 iterator
end () { return instr_end(); }
219 const_iterator
end () const { return instr_end(); }
220 reverse_iterator
rbegin() {
221 return reverse_iterator::getAtBundleBegin(instr_rbegin());
223 const_reverse_iterator
rbegin() const {
224 return const_reverse_iterator::getAtBundleBegin(instr_rbegin());
226 reverse_iterator
rend() { return reverse_iterator(instr_rend()); }
227 const_reverse_iterator
rend() const {
228 return const_reverse_iterator(instr_rend());
231 /// Support for MachineInstr::getNextNode().
232 static Instructions
MachineBasicBlock::*getSublistAccess(MachineInstr
*) {
233 return &MachineBasicBlock::Insts
;
236 inline iterator_range
<iterator
> terminators() {
237 return make_range(getFirstTerminator(), end());
239 inline iterator_range
<const_iterator
> terminators() const {
240 return make_range(getFirstTerminator(), end());
243 /// Returns a range that iterates over the phis in the basic block.
244 inline iterator_range
<iterator
> phis() {
245 return make_range(begin(), getFirstNonPHI());
247 inline iterator_range
<const_iterator
> phis() const {
248 return const_cast<MachineBasicBlock
*>(this)->phis();
251 // Machine-CFG iterators
252 using pred_iterator
= std::vector
<MachineBasicBlock
*>::iterator
;
253 using const_pred_iterator
= std::vector
<MachineBasicBlock
*>::const_iterator
;
254 using succ_iterator
= std::vector
<MachineBasicBlock
*>::iterator
;
255 using const_succ_iterator
= std::vector
<MachineBasicBlock
*>::const_iterator
;
256 using pred_reverse_iterator
=
257 std::vector
<MachineBasicBlock
*>::reverse_iterator
;
258 using const_pred_reverse_iterator
=
259 std::vector
<MachineBasicBlock
*>::const_reverse_iterator
;
260 using succ_reverse_iterator
=
261 std::vector
<MachineBasicBlock
*>::reverse_iterator
;
262 using const_succ_reverse_iterator
=
263 std::vector
<MachineBasicBlock
*>::const_reverse_iterator
;
264 pred_iterator
pred_begin() { return Predecessors
.begin(); }
265 const_pred_iterator
pred_begin() const { return Predecessors
.begin(); }
266 pred_iterator
pred_end() { return Predecessors
.end(); }
267 const_pred_iterator
pred_end() const { return Predecessors
.end(); }
268 pred_reverse_iterator
pred_rbegin()
269 { return Predecessors
.rbegin();}
270 const_pred_reverse_iterator
pred_rbegin() const
271 { return Predecessors
.rbegin();}
272 pred_reverse_iterator
pred_rend()
273 { return Predecessors
.rend(); }
274 const_pred_reverse_iterator
pred_rend() const
275 { return Predecessors
.rend(); }
276 unsigned pred_size() const {
277 return (unsigned)Predecessors
.size();
279 bool pred_empty() const { return Predecessors
.empty(); }
280 succ_iterator
succ_begin() { return Successors
.begin(); }
281 const_succ_iterator
succ_begin() const { return Successors
.begin(); }
282 succ_iterator
succ_end() { return Successors
.end(); }
283 const_succ_iterator
succ_end() const { return Successors
.end(); }
284 succ_reverse_iterator
succ_rbegin()
285 { return Successors
.rbegin(); }
286 const_succ_reverse_iterator
succ_rbegin() const
287 { return Successors
.rbegin(); }
288 succ_reverse_iterator
succ_rend()
289 { return Successors
.rend(); }
290 const_succ_reverse_iterator
succ_rend() const
291 { return Successors
.rend(); }
292 unsigned succ_size() const {
293 return (unsigned)Successors
.size();
295 bool succ_empty() const { return Successors
.empty(); }
297 inline iterator_range
<pred_iterator
> predecessors() {
298 return make_range(pred_begin(), pred_end());
300 inline iterator_range
<const_pred_iterator
> predecessors() const {
301 return make_range(pred_begin(), pred_end());
303 inline iterator_range
<succ_iterator
> successors() {
304 return make_range(succ_begin(), succ_end());
306 inline iterator_range
<const_succ_iterator
> successors() const {
307 return make_range(succ_begin(), succ_end());
310 // LiveIn management methods.
312 /// Adds the specified register as a live in. Note that it is an error to add
313 /// the same register to the same set more than once unless the intention is
314 /// to call sortUniqueLiveIns after all registers are added.
315 void addLiveIn(MCRegister PhysReg
,
316 LaneBitmask LaneMask
= LaneBitmask::getAll()) {
317 LiveIns
.push_back(RegisterMaskPair(PhysReg
, LaneMask
));
319 void addLiveIn(const RegisterMaskPair
&RegMaskPair
) {
320 LiveIns
.push_back(RegMaskPair
);
323 /// Sorts and uniques the LiveIns vector. It can be significantly faster to do
324 /// this than repeatedly calling isLiveIn before calling addLiveIn for every
325 /// LiveIn insertion.
326 void sortUniqueLiveIns();
328 /// Clear live in list.
331 /// Add PhysReg as live in to this block, and ensure that there is a copy of
332 /// PhysReg to a virtual register of class RC. Return the virtual register
333 /// that is a copy of the live in PhysReg.
334 unsigned addLiveIn(MCRegister PhysReg
, const TargetRegisterClass
*RC
);
336 /// Remove the specified register from the live in set.
337 void removeLiveIn(MCPhysReg Reg
,
338 LaneBitmask LaneMask
= LaneBitmask::getAll());
340 /// Return true if the specified register is in the live in set.
341 bool isLiveIn(MCPhysReg Reg
,
342 LaneBitmask LaneMask
= LaneBitmask::getAll()) const;
344 // Iteration support for live in sets. These sets are kept in sorted
345 // order by their register number.
346 using livein_iterator
= LiveInVector::const_iterator
;
348 /// Unlike livein_begin, this method does not check that the liveness
349 /// information is accurate. Still for debug purposes it may be useful
350 /// to have iterators that won't assert if the liveness information
352 livein_iterator
livein_begin_dbg() const { return LiveIns
.begin(); }
353 iterator_range
<livein_iterator
> liveins_dbg() const {
354 return make_range(livein_begin_dbg(), livein_end());
357 livein_iterator
livein_begin() const;
358 livein_iterator
livein_end() const { return LiveIns
.end(); }
359 bool livein_empty() const { return LiveIns
.empty(); }
360 iterator_range
<livein_iterator
> liveins() const {
361 return make_range(livein_begin(), livein_end());
364 /// Remove entry from the livein set and return iterator to the next.
365 livein_iterator
removeLiveIn(livein_iterator I
);
367 /// Get the clobber mask for the start of this basic block. Funclets use this
368 /// to prevent register allocation across funclet transitions.
369 const uint32_t *getBeginClobberMask(const TargetRegisterInfo
*TRI
) const;
371 /// Get the clobber mask for the end of the basic block.
372 /// \see getBeginClobberMask()
373 const uint32_t *getEndClobberMask(const TargetRegisterInfo
*TRI
) const;
375 /// Return alignment of the basic block. The alignment is specified as
377 /// FIXME: Remove the Log versions once migration to llvm::Align is over.
378 unsigned getLogAlignment() const { return Log2(Alignment
); }
379 llvm::Align
getAlignment() const { return Alignment
; }
381 /// Set alignment of the basic block. The alignment is specified as
383 /// FIXME: Remove the Log versions once migration to llvm::Align is over.
384 void setLogAlignment(unsigned A
) { Alignment
= llvm::Align(1ULL << A
); }
385 void setAlignment(llvm::Align A
) { Alignment
= A
; }
387 /// Returns true if the block is a landing pad. That is this basic block is
388 /// entered via an exception handler.
389 bool isEHPad() const { return IsEHPad
; }
391 /// Indicates the block is a landing pad. That is this basic block is entered
392 /// via an exception handler.
393 void setIsEHPad(bool V
= true) { IsEHPad
= V
; }
395 bool hasEHPadSuccessor() const;
397 /// Returns true if this is the entry block of an EH scope, i.e., the block
398 /// that used to have a catchpad or cleanuppad instruction in the LLVM IR.
399 bool isEHScopeEntry() const { return IsEHScopeEntry
; }
401 /// Indicates if this is the entry block of an EH scope, i.e., the block that
402 /// that used to have a catchpad or cleanuppad instruction in the LLVM IR.
403 void setIsEHScopeEntry(bool V
= true) { IsEHScopeEntry
= V
; }
405 /// Returns true if this is the entry block of an EH funclet.
406 bool isEHFuncletEntry() const { return IsEHFuncletEntry
; }
408 /// Indicates if this is the entry block of an EH funclet.
409 void setIsEHFuncletEntry(bool V
= true) { IsEHFuncletEntry
= V
; }
411 /// Returns true if this is the entry block of a cleanup funclet.
412 bool isCleanupFuncletEntry() const { return IsCleanupFuncletEntry
; }
414 /// Indicates if this is the entry block of a cleanup funclet.
415 void setIsCleanupFuncletEntry(bool V
= true) { IsCleanupFuncletEntry
= V
; }
417 /// Returns true if it is legal to hoist instructions into this block.
418 bool isLegalToHoistInto() const;
420 // Code Layout methods.
422 /// Move 'this' block before or after the specified block. This only moves
423 /// the block, it does not modify the CFG or adjust potential fall-throughs at
424 /// the end of the block.
425 void moveBefore(MachineBasicBlock
*NewAfter
);
426 void moveAfter(MachineBasicBlock
*NewBefore
);
428 /// Update the terminator instructions in block to account for changes to the
429 /// layout. If the block previously used a fallthrough, it may now need a
430 /// branch, and if it previously used branching it may now be able to use a
432 void updateTerminator();
434 // Machine-CFG mutators
436 /// Add Succ as a successor of this MachineBasicBlock. The Predecessors list
437 /// of Succ is automatically updated. PROB parameter is stored in
438 /// Probabilities list. The default probability is set as unknown. Mixing
439 /// known and unknown probabilities in successor list is not allowed. When all
440 /// successors have unknown probabilities, 1 / N is returned as the
441 /// probability for each successor, where N is the number of successors.
443 /// Note that duplicate Machine CFG edges are not allowed.
444 void addSuccessor(MachineBasicBlock
*Succ
,
445 BranchProbability Prob
= BranchProbability::getUnknown());
447 /// Add Succ as a successor of this MachineBasicBlock. The Predecessors list
448 /// of Succ is automatically updated. The probability is not provided because
449 /// BPI is not available (e.g. -O0 is used), in which case edge probabilities
450 /// won't be used. Using this interface can save some space.
451 void addSuccessorWithoutProb(MachineBasicBlock
*Succ
);
453 /// Set successor probability of a given iterator.
454 void setSuccProbability(succ_iterator I
, BranchProbability Prob
);
456 /// Normalize probabilities of all successors so that the sum of them becomes
457 /// one. This is usually done when the current update on this MBB is done, and
458 /// the sum of its successors' probabilities is not guaranteed to be one. The
459 /// user is responsible for the correct use of this function.
460 /// MBB::removeSuccessor() has an option to do this automatically.
461 void normalizeSuccProbs() {
462 BranchProbability::normalizeProbabilities(Probs
.begin(), Probs
.end());
465 /// Validate successors' probabilities and check if the sum of them is
466 /// approximate one. This only works in DEBUG mode.
467 void validateSuccProbs() const;
469 /// Remove successor from the successors list of this MachineBasicBlock. The
470 /// Predecessors list of Succ is automatically updated.
471 /// If NormalizeSuccProbs is true, then normalize successors' probabilities
472 /// after the successor is removed.
473 void removeSuccessor(MachineBasicBlock
*Succ
,
474 bool NormalizeSuccProbs
= false);
476 /// Remove specified successor from the successors list of this
477 /// MachineBasicBlock. The Predecessors list of Succ is automatically updated.
478 /// If NormalizeSuccProbs is true, then normalize successors' probabilities
479 /// after the successor is removed.
480 /// Return the iterator to the element after the one removed.
481 succ_iterator
removeSuccessor(succ_iterator I
,
482 bool NormalizeSuccProbs
= false);
484 /// Replace successor OLD with NEW and update probability info.
485 void replaceSuccessor(MachineBasicBlock
*Old
, MachineBasicBlock
*New
);
487 /// Copy a successor (and any probability info) from original block to this
488 /// block's. Uses an iterator into the original blocks successors.
490 /// This is useful when doing a partial clone of successors. Afterward, the
491 /// probabilities may need to be normalized.
492 void copySuccessor(MachineBasicBlock
*Orig
, succ_iterator I
);
494 /// Split the old successor into old plus new and updates the probability
496 void splitSuccessor(MachineBasicBlock
*Old
, MachineBasicBlock
*New
,
497 bool NormalizeSuccProbs
= false);
499 /// Transfers all the successors from MBB to this machine basic block (i.e.,
500 /// copies all the successors FromMBB and remove all the successors from
502 void transferSuccessors(MachineBasicBlock
*FromMBB
);
504 /// Transfers all the successors, as in transferSuccessors, and update PHI
505 /// operands in the successor blocks which refer to FromMBB to refer to this.
506 void transferSuccessorsAndUpdatePHIs(MachineBasicBlock
*FromMBB
);
508 /// Return true if any of the successors have probabilities attached to them.
509 bool hasSuccessorProbabilities() const { return !Probs
.empty(); }
511 /// Return true if the specified MBB is a predecessor of this block.
512 bool isPredecessor(const MachineBasicBlock
*MBB
) const;
514 /// Return true if the specified MBB is a successor of this block.
515 bool isSuccessor(const MachineBasicBlock
*MBB
) const;
517 /// Return true if the specified MBB will be emitted immediately after this
518 /// block, such that if this block exits by falling through, control will
519 /// transfer to the specified MBB. Note that MBB need not be a successor at
520 /// all, for example if this block ends with an unconditional branch to some
522 bool isLayoutSuccessor(const MachineBasicBlock
*MBB
) const;
524 /// Return the fallthrough block if the block can implicitly
525 /// transfer control to the block after it by falling off the end of
526 /// it. This should return null if it can reach the block after
527 /// it, but it uses an explicit branch to do so (e.g., a table
528 /// jump). Non-null return is a conservative answer.
529 MachineBasicBlock
*getFallThrough();
531 /// Return true if the block can implicitly transfer control to the
532 /// block after it by falling off the end of it. This should return
533 /// false if it can reach the block after it, but it uses an
534 /// explicit branch to do so (e.g., a table jump). True is a
535 /// conservative answer.
536 bool canFallThrough();
538 /// Returns a pointer to the first instruction in this block that is not a
539 /// PHINode instruction. When adding instructions to the beginning of the
540 /// basic block, they should be added before the returned value, not before
541 /// the first instruction, which might be PHI.
542 /// Returns end() is there's no non-PHI instruction.
543 iterator
getFirstNonPHI();
545 /// Return the first instruction in MBB after I that is not a PHI or a label.
546 /// This is the correct point to insert lowered copies at the beginning of a
547 /// basic block that must be before any debugging information.
548 iterator
SkipPHIsAndLabels(iterator I
);
550 /// Return the first instruction in MBB after I that is not a PHI, label or
551 /// debug. This is the correct point to insert copies at the beginning of a
553 iterator
SkipPHIsLabelsAndDebug(iterator I
);
555 /// Returns an iterator to the first terminator instruction of this basic
556 /// block. If a terminator does not exist, it returns end().
557 iterator
getFirstTerminator();
558 const_iterator
getFirstTerminator() const {
559 return const_cast<MachineBasicBlock
*>(this)->getFirstTerminator();
562 /// Same getFirstTerminator but it ignores bundles and return an
563 /// instr_iterator instead.
564 instr_iterator
getFirstInstrTerminator();
566 /// Returns an iterator to the first non-debug instruction in the basic block,
568 iterator
getFirstNonDebugInstr();
569 const_iterator
getFirstNonDebugInstr() const {
570 return const_cast<MachineBasicBlock
*>(this)->getFirstNonDebugInstr();
573 /// Returns an iterator to the last non-debug instruction in the basic block,
575 iterator
getLastNonDebugInstr();
576 const_iterator
getLastNonDebugInstr() const {
577 return const_cast<MachineBasicBlock
*>(this)->getLastNonDebugInstr();
580 /// Convenience function that returns true if the block ends in a return
582 bool isReturnBlock() const {
583 return !empty() && back().isReturn();
586 /// Convenience function that returns true if the bock ends in a EH scope
587 /// return instruction.
588 bool isEHScopeReturnBlock() const {
589 return !empty() && back().isEHScopeReturn();
592 /// Split the critical edge from this block to the given successor block, and
593 /// return the newly created block, or null if splitting is not possible.
595 /// This function updates LiveVariables, MachineDominatorTree, and
596 /// MachineLoopInfo, as applicable.
597 MachineBasicBlock
*SplitCriticalEdge(MachineBasicBlock
*Succ
, Pass
&P
);
599 /// Check if the edge between this block and the given successor \p
600 /// Succ, can be split. If this returns true a subsequent call to
601 /// SplitCriticalEdge is guaranteed to return a valid basic block if
602 /// no changes occurred in the meantime.
603 bool canSplitCriticalEdge(const MachineBasicBlock
*Succ
) const;
605 void pop_front() { Insts
.pop_front(); }
606 void pop_back() { Insts
.pop_back(); }
607 void push_back(MachineInstr
*MI
) { Insts
.push_back(MI
); }
609 /// Insert MI into the instruction list before I, possibly inside a bundle.
611 /// If the insertion point is inside a bundle, MI will be added to the bundle,
612 /// otherwise MI will not be added to any bundle. That means this function
613 /// alone can't be used to prepend or append instructions to bundles. See
614 /// MIBundleBuilder::insert() for a more reliable way of doing that.
615 instr_iterator
insert(instr_iterator I
, MachineInstr
*M
);
617 /// Insert a range of instructions into the instruction list before I.
618 template<typename IT
>
619 void insert(iterator I
, IT S
, IT E
) {
620 assert((I
== end() || I
->getParent() == this) &&
621 "iterator points outside of basic block");
622 Insts
.insert(I
.getInstrIterator(), S
, E
);
625 /// Insert MI into the instruction list before I.
626 iterator
insert(iterator I
, MachineInstr
*MI
) {
627 assert((I
== end() || I
->getParent() == this) &&
628 "iterator points outside of basic block");
629 assert(!MI
->isBundledWithPred() && !MI
->isBundledWithSucc() &&
630 "Cannot insert instruction with bundle flags");
631 return Insts
.insert(I
.getInstrIterator(), MI
);
634 /// Insert MI into the instruction list after I.
635 iterator
insertAfter(iterator I
, MachineInstr
*MI
) {
636 assert((I
== end() || I
->getParent() == this) &&
637 "iterator points outside of basic block");
638 assert(!MI
->isBundledWithPred() && !MI
->isBundledWithSucc() &&
639 "Cannot insert instruction with bundle flags");
640 return Insts
.insertAfter(I
.getInstrIterator(), MI
);
643 /// If I is bundled then insert MI into the instruction list after the end of
644 /// the bundle, otherwise insert MI immediately after I.
645 instr_iterator
insertAfterBundle(instr_iterator I
, MachineInstr
*MI
) {
646 assert((I
== instr_end() || I
->getParent() == this) &&
647 "iterator points outside of basic block");
648 assert(!MI
->isBundledWithPred() && !MI
->isBundledWithSucc() &&
649 "Cannot insert instruction with bundle flags");
650 while (I
->isBundledWithSucc())
652 return Insts
.insertAfter(I
, MI
);
655 /// Remove an instruction from the instruction list and delete it.
657 /// If the instruction is part of a bundle, the other instructions in the
658 /// bundle will still be bundled after removing the single instruction.
659 instr_iterator
erase(instr_iterator I
);
661 /// Remove an instruction from the instruction list and delete it.
663 /// If the instruction is part of a bundle, the other instructions in the
664 /// bundle will still be bundled after removing the single instruction.
665 instr_iterator
erase_instr(MachineInstr
*I
) {
666 return erase(instr_iterator(I
));
669 /// Remove a range of instructions from the instruction list and delete them.
670 iterator
erase(iterator I
, iterator E
) {
671 return Insts
.erase(I
.getInstrIterator(), E
.getInstrIterator());
674 /// Remove an instruction or bundle from the instruction list and delete it.
676 /// If I points to a bundle of instructions, they are all erased.
677 iterator
erase(iterator I
) {
678 return erase(I
, std::next(I
));
681 /// Remove an instruction from the instruction list and delete it.
683 /// If I is the head of a bundle of instructions, the whole bundle will be
685 iterator
erase(MachineInstr
*I
) {
686 return erase(iterator(I
));
689 /// Remove the unbundled instruction from the instruction list without
692 /// This function can not be used to remove bundled instructions, use
693 /// remove_instr to remove individual instructions from a bundle.
694 MachineInstr
*remove(MachineInstr
*I
) {
695 assert(!I
->isBundled() && "Cannot remove bundled instructions");
696 return Insts
.remove(instr_iterator(I
));
699 /// Remove the possibly bundled instruction from the instruction list
700 /// without deleting it.
702 /// If the instruction is part of a bundle, the other instructions in the
703 /// bundle will still be bundled after removing the single instruction.
704 MachineInstr
*remove_instr(MachineInstr
*I
);
710 /// Take an instruction from MBB 'Other' at the position From, and insert it
711 /// into this MBB right before 'Where'.
713 /// If From points to a bundle of instructions, the whole bundle is moved.
714 void splice(iterator Where
, MachineBasicBlock
*Other
, iterator From
) {
715 // The range splice() doesn't allow noop moves, but this one does.
717 splice(Where
, Other
, From
, std::next(From
));
720 /// Take a block of instructions from MBB 'Other' in the range [From, To),
721 /// and insert them into this MBB right before 'Where'.
723 /// The instruction at 'Where' must not be included in the range of
724 /// instructions to move.
725 void splice(iterator Where
, MachineBasicBlock
*Other
,
726 iterator From
, iterator To
) {
727 Insts
.splice(Where
.getInstrIterator(), Other
->Insts
,
728 From
.getInstrIterator(), To
.getInstrIterator());
731 /// This method unlinks 'this' from the containing function, and returns it,
732 /// but does not delete it.
733 MachineBasicBlock
*removeFromParent();
735 /// This method unlinks 'this' from the containing function and deletes it.
736 void eraseFromParent();
738 /// Given a machine basic block that branched to 'Old', change the code and
739 /// CFG so that it branches to 'New' instead.
740 void ReplaceUsesOfBlockWith(MachineBasicBlock
*Old
, MachineBasicBlock
*New
);
742 /// Update all phi nodes in this basic block to refer to basic block \p New
743 /// instead of basic block \p Old.
744 void replacePhiUsesWith(MachineBasicBlock
*Old
, MachineBasicBlock
*New
);
746 /// Various pieces of code can cause excess edges in the CFG to be inserted.
747 /// If we have proven that MBB can only branch to DestA and DestB, remove any
748 /// other MBB successors from the CFG. DestA and DestB can be null. Besides
749 /// DestA and DestB, retain other edges leading to LandingPads (currently
750 /// there can be only one; we don't check or require that here). Note it is
751 /// possible that DestA and/or DestB are LandingPads.
752 bool CorrectExtraCFGEdges(MachineBasicBlock
*DestA
,
753 MachineBasicBlock
*DestB
,
756 /// Find the next valid DebugLoc starting at MBBI, skipping any DBG_VALUE
757 /// and DBG_LABEL instructions. Return UnknownLoc if there is none.
758 DebugLoc
findDebugLoc(instr_iterator MBBI
);
759 DebugLoc
findDebugLoc(iterator MBBI
) {
760 return findDebugLoc(MBBI
.getInstrIterator());
763 /// Find the previous valid DebugLoc preceding MBBI, skipping and DBG_VALUE
764 /// instructions. Return UnknownLoc if there is none.
765 DebugLoc
findPrevDebugLoc(instr_iterator MBBI
);
766 DebugLoc
findPrevDebugLoc(iterator MBBI
) {
767 return findPrevDebugLoc(MBBI
.getInstrIterator());
770 /// Find and return the merged DebugLoc of the branch instructions of the
771 /// block. Return UnknownLoc if there is none.
772 DebugLoc
findBranchDebugLoc();
774 /// Possible outcome of a register liveness query to computeRegisterLiveness()
775 enum LivenessQueryResult
{
776 LQR_Live
, ///< Register is known to be (at least partially) live.
777 LQR_Dead
, ///< Register is known to be fully dead.
778 LQR_Unknown
///< Register liveness not decidable from local neighborhood.
781 /// Return whether (physical) register \p Reg has been defined and not
782 /// killed as of just before \p Before.
784 /// Search is localised to a neighborhood of \p Neighborhood instructions
785 /// before (searching for defs or kills) and \p Neighborhood instructions
786 /// after (searching just for defs) \p Before.
788 /// \p Reg must be a physical register.
789 LivenessQueryResult
computeRegisterLiveness(const TargetRegisterInfo
*TRI
,
791 const_iterator Before
,
792 unsigned Neighborhood
= 10) const;
794 // Debugging methods.
796 void print(raw_ostream
&OS
, const SlotIndexes
* = nullptr,
797 bool IsStandalone
= true) const;
798 void print(raw_ostream
&OS
, ModuleSlotTracker
&MST
,
799 const SlotIndexes
* = nullptr, bool IsStandalone
= true) const;
801 // Printing method used by LoopInfo.
802 void printAsOperand(raw_ostream
&OS
, bool PrintType
= true) const;
804 /// MachineBasicBlocks are uniquely numbered at the function level, unless
805 /// they're not in a MachineFunction yet, in which case this will return -1.
806 int getNumber() const { return Number
; }
807 void setNumber(int N
) { Number
= N
; }
809 /// Return the MCSymbol for this basic block.
810 MCSymbol
*getSymbol() const;
812 Optional
<uint64_t> getIrrLoopHeaderWeight() const {
813 return IrrLoopHeaderWeight
;
816 void setIrrLoopHeaderWeight(uint64_t Weight
) {
817 IrrLoopHeaderWeight
= Weight
;
821 /// Return probability iterator corresponding to the I successor iterator.
822 probability_iterator
getProbabilityIterator(succ_iterator I
);
823 const_probability_iterator
824 getProbabilityIterator(const_succ_iterator I
) const;
826 friend class MachineBranchProbabilityInfo
;
827 friend class MIPrinter
;
829 /// Return probability of the edge from this block to MBB. This method should
830 /// NOT be called directly, but by using getEdgeProbability method from
831 /// MachineBranchProbabilityInfo class.
832 BranchProbability
getSuccProbability(const_succ_iterator Succ
) const;
834 // Methods used to maintain doubly linked list of blocks...
835 friend struct ilist_callback_traits
<MachineBasicBlock
>;
837 // Machine-CFG mutators
839 /// Add Pred as a predecessor of this MachineBasicBlock. Don't do this
840 /// unless you know what you're doing, because it doesn't update Pred's
841 /// successors list. Use Pred->addSuccessor instead.
842 void addPredecessor(MachineBasicBlock
*Pred
);
844 /// Remove Pred as a predecessor of this MachineBasicBlock. Don't do this
845 /// unless you know what you're doing, because it doesn't update Pred's
846 /// successors list. Use Pred->removeSuccessor instead.
847 void removePredecessor(MachineBasicBlock
*Pred
);
850 raw_ostream
& operator<<(raw_ostream
&OS
, const MachineBasicBlock
&MBB
);
852 /// Prints a machine basic block reference.
855 /// %bb.5 - a machine basic block with MBB.getNumber() == 5.
857 /// Usage: OS << printMBBReference(MBB) << '\n';
858 Printable
printMBBReference(const MachineBasicBlock
&MBB
);
860 // This is useful when building IndexedMaps keyed on basic block pointers.
861 struct MBB2NumberFunctor
{
862 using argument_type
= const MachineBasicBlock
*;
863 unsigned operator()(const MachineBasicBlock
*MBB
) const {
864 return MBB
->getNumber();
868 //===--------------------------------------------------------------------===//
869 // GraphTraits specializations for machine basic block graphs (machine-CFGs)
870 //===--------------------------------------------------------------------===//
872 // Provide specializations of GraphTraits to be able to treat a
873 // MachineFunction as a graph of MachineBasicBlocks.
876 template <> struct GraphTraits
<MachineBasicBlock
*> {
877 using NodeRef
= MachineBasicBlock
*;
878 using ChildIteratorType
= MachineBasicBlock::succ_iterator
;
880 static NodeRef
getEntryNode(MachineBasicBlock
*BB
) { return BB
; }
881 static ChildIteratorType
child_begin(NodeRef N
) { return N
->succ_begin(); }
882 static ChildIteratorType
child_end(NodeRef N
) { return N
->succ_end(); }
885 template <> struct GraphTraits
<const MachineBasicBlock
*> {
886 using NodeRef
= const MachineBasicBlock
*;
887 using ChildIteratorType
= MachineBasicBlock::const_succ_iterator
;
889 static NodeRef
getEntryNode(const MachineBasicBlock
*BB
) { return BB
; }
890 static ChildIteratorType
child_begin(NodeRef N
) { return N
->succ_begin(); }
891 static ChildIteratorType
child_end(NodeRef N
) { return N
->succ_end(); }
894 // Provide specializations of GraphTraits to be able to treat a
895 // MachineFunction as a graph of MachineBasicBlocks and to walk it
896 // in inverse order. Inverse order for a function is considered
897 // to be when traversing the predecessor edges of a MBB
898 // instead of the successor edges.
900 template <> struct GraphTraits
<Inverse
<MachineBasicBlock
*>> {
901 using NodeRef
= MachineBasicBlock
*;
902 using ChildIteratorType
= MachineBasicBlock::pred_iterator
;
904 static NodeRef
getEntryNode(Inverse
<MachineBasicBlock
*> G
) {
908 static ChildIteratorType
child_begin(NodeRef N
) { return N
->pred_begin(); }
909 static ChildIteratorType
child_end(NodeRef N
) { return N
->pred_end(); }
912 template <> struct GraphTraits
<Inverse
<const MachineBasicBlock
*>> {
913 using NodeRef
= const MachineBasicBlock
*;
914 using ChildIteratorType
= MachineBasicBlock::const_pred_iterator
;
916 static NodeRef
getEntryNode(Inverse
<const MachineBasicBlock
*> G
) {
920 static ChildIteratorType
child_begin(NodeRef N
) { return N
->pred_begin(); }
921 static ChildIteratorType
child_end(NodeRef N
) { return N
->pred_end(); }
924 /// MachineInstrSpan provides an interface to get an iteration range
925 /// containing the instruction it was initialized with, along with all
926 /// those instructions inserted prior to or following that instruction
927 /// at some point after the MachineInstrSpan is constructed.
928 class MachineInstrSpan
{
929 MachineBasicBlock
&MBB
;
930 MachineBasicBlock::iterator I
, B
, E
;
933 MachineInstrSpan(MachineBasicBlock::iterator I
, MachineBasicBlock
*BB
)
934 : MBB(*BB
), I(I
), B(I
== MBB
.begin() ? MBB
.end() : std::prev(I
)),
936 assert(I
== BB
->end() || I
->getParent() == BB
);
939 MachineBasicBlock::iterator
begin() {
940 return B
== MBB
.end() ? MBB
.begin() : std::next(B
);
942 MachineBasicBlock::iterator
end() { return E
; }
943 bool empty() { return begin() == end(); }
945 MachineBasicBlock::iterator
getInitial() { return I
; }
948 /// Increment \p It until it points to a non-debug instruction or to \p End
949 /// and return the resulting iterator. This function should only be used
950 /// MachineBasicBlock::{iterator, const_iterator, instr_iterator,
951 /// const_instr_iterator} and the respective reverse iterators.
952 template<typename IterT
>
953 inline IterT
skipDebugInstructionsForward(IterT It
, IterT End
) {
954 while (It
!= End
&& It
->isDebugInstr())
959 /// Decrement \p It until it points to a non-debug instruction or to \p Begin
960 /// and return the resulting iterator. This function should only be used
961 /// MachineBasicBlock::{iterator, const_iterator, instr_iterator,
962 /// const_instr_iterator} and the respective reverse iterators.
963 template<class IterT
>
964 inline IterT
skipDebugInstructionsBackward(IterT It
, IterT Begin
) {
965 while (It
!= Begin
&& It
->isDebugInstr())
970 } // end namespace llvm
972 #endif // LLVM_CODEGEN_MACHINEBASICBLOCK_H