Debian Codegraph @

suite/synctools/tablegen/include/llvm/CodeGen/MachineBasicBlock.h

raw symbols SCIP
1 //===- llvm/CodeGen/MachineBasicBlock.h -------------------------*- C++ -*-===//
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 // Collect the sequence of machine instructions for a basic block.
10 //
11 //===----------------------------------------------------------------------===//
12
13 #ifndef LLVM_CODEGEN_MACHINEBASICBLOCK_H
14 #define LLVM_CODEGEN_MACHINEBASICBLOCK_H
15
16 #include "llvm/ADT/GraphTraits.h"
17 #include "llvm/ADT/ilist.h"
18 #include "llvm/ADT/iterator_range.h"
19 #include "llvm/ADT/SparseBitVector.h"
20 #include "llvm/CodeGen/MachineInstr.h"
21 #include "llvm/CodeGen/MachineInstrBundleIterator.h"
22 #include "llvm/IR/DebugLoc.h"
23 #include "llvm/MC/LaneBitmask.h"
24 #include "llvm/Support/BranchProbability.h"
25 #include <cassert>
26 #include <cstdint>
27 #include <functional>
28 #include <iterator>
29 #include <string>
30 #include <vector>
31
32 namespace llvm {
33
34 class BasicBlock;
35 class MachineFunction;
36 class MCSymbol;
37 class ModuleSlotTracker;
38 class Pass;
39 class Printable;
40 class SlotIndexes;
41 class StringRef;
42 class raw_ostream;
43 class LiveIntervals;
44 class TargetRegisterClass;
45 class TargetRegisterInfo;
46
47 // This structure uniquely identifies a basic block section.
48 // Possible values are
49 // {Type: Default, Number: (unsigned)} (These are regular section IDs)
50 // {Type: Exception, Number: 0} (ExceptionSectionID)
51 // {Type: Cold, Number: 0} (ColdSectionID)
52 struct MBBSectionID {
53 enum SectionType {
54 Default = 0, // Regular section (these sections are distinguished by the
55 // Number field).
56 Exception, // Special section type for exception handling blocks
57 Cold, // Special section type for cold blocks
58 } Type;
59 unsigned Number;
60
61 MBBSectionID(unsigned N) : Type(Default), Number(N) {}
62
63 // Special unique sections for cold and exception blocks.
64 const static MBBSectionID ColdSectionID;
65 const static MBBSectionID ExceptionSectionID;
66
67 bool operator==(const MBBSectionID &Other) const {
68 return Type == Other.Type && Number == Other.Number;
69 }
70
71 bool operator!=(const MBBSectionID &Other) const { return !(*this == Other); }
72
73 private:
74 // This is only used to construct the special cold and exception sections.
75 MBBSectionID(SectionType T) : Type(T), Number(0) {}
76 };
77
78 template <> struct ilist_traits<MachineInstr> {
79 private:
80 friend class MachineBasicBlock; // Set by the owning MachineBasicBlock.
81
82 MachineBasicBlock *Parent;
83
84 using instr_iterator =
85 simple_ilist<MachineInstr, ilist_sentinel_tracking<true>>::iterator;
86
87 public:
88 void addNodeToList(MachineInstr *N);
89 void removeNodeFromList(MachineInstr *N);
90 void transferNodesFromList(ilist_traits &FromList, instr_iterator First,
91 instr_iterator Last);
92 void deleteNode(MachineInstr *MI);
93 };
94
95 class MachineBasicBlock
96 : public ilist_node_with_parent<MachineBasicBlock, MachineFunction> {
97 public:
98 /// Pair of physical register and lane mask.
99 /// This is not simply a std::pair typedef because the members should be named
100 /// clearly as they both have an integer type.
101 struct RegisterMaskPair {
102 public:
103 MCPhysReg PhysReg;
104 LaneBitmask LaneMask;
105
106 RegisterMaskPair(MCPhysReg PhysReg, LaneBitmask LaneMask)
107 : PhysReg(PhysReg), LaneMask(LaneMask) {}
108 };
109
110 private:
111 using Instructions = ilist<MachineInstr, ilist_sentinel_tracking<true>>;
112
113 Instructions Insts;
114 const BasicBlock *BB;
115 int Number;
116 MachineFunction *xParent;
117
118 /// Keep track of the predecessor / successor basic blocks.
119 std::vector<MachineBasicBlock *> Predecessors;
120 std::vector<MachineBasicBlock *> Successors;
121
122 /// Keep track of the probabilities to the successors. This vector has the
123 /// same order as Successors, or it is empty if we don't use it (disable
124 /// optimization).
125 std::vector<BranchProbability> Probs;
126 using probability_iterator = std::vector<BranchProbability>::iterator;
127 using const_probability_iterator =
128 std::vector<BranchProbability>::const_iterator;
129
130 Optional<uint64_t> IrrLoopHeaderWeight;
131
132 /// Keep track of the physical registers that are livein of the basicblock.
133 using LiveInVector = std::vector<RegisterMaskPair>;
134 LiveInVector LiveIns;
135
136 /// Alignment of the basic block. One if the basic block does not need to be
137 /// aligned.
138 Align Alignment;
139 /// Maximum amount of bytes that can be added to align the basic block. If the
140 /// alignment cannot be reached in this many bytes, no bytes are emitted.
141 /// Zero to represent no maximum.
142 unsigned MaxBytesForAlignment = 0;
143
144 /// Indicate that this basic block is entered via an exception handler.
145 bool IsEHPad = false;
146
147 /// Indicate that this basic block is potentially the target of an indirect
148 /// branch.
149 bool AddressTaken = false;
150
151 /// Indicate that this basic block needs its symbol be emitted regardless of
152 /// whether the flow just falls-through to it.
153 bool LabelMustBeEmitted = false;
154
155 /// Indicate that this basic block is the entry block of an EH scope, i.e.,
156 /// the block that used to have a catchpad or cleanuppad instruction in the
157 /// LLVM IR.
158 bool IsEHScopeEntry = false;
159
160 /// Indicates if this is a target block of a catchret.
161 bool IsEHCatchretTarget = false;
162
163 /// Indicate that this basic block is the entry block of an EH funclet.
164 bool IsEHFuncletEntry = false;
165
166 /// Indicate that this basic block is the entry block of a cleanup funclet.
167 bool IsCleanupFuncletEntry = false;
168
169 /// With basic block sections, this stores the Section ID of the basic block.
170 MBBSectionID SectionID{0};
171
172 // Indicate that this basic block begins a section.
173 bool IsBeginSection = false;
174
175 // Indicate that this basic block ends a section.
176 bool IsEndSection = false;
177
178 /// Indicate that this basic block is the indirect dest of an INLINEASM_BR.
179 bool IsInlineAsmBrIndirectTarget = false;
180
181 /// since getSymbol is a relatively heavy-weight operation, the symbol
182 /// is only computed once and is cached.
183 mutable MCSymbol *CachedMCSymbol = nullptr;
184
185 /// Cached MCSymbol for this block (used if IsEHCatchRetTarget).
186 mutable MCSymbol *CachedEHCatchretMCSymbol = nullptr;
187
188 /// Marks the end of the basic block. Used during basic block sections to
189 /// calculate the size of the basic block, or the BB section ending with it.
190 mutable MCSymbol *CachedEndMCSymbol = nullptr;
191
192 // Intrusive list support
193 MachineBasicBlock() = default;
194
195 explicit MachineBasicBlock(MachineFunction &MF, const BasicBlock *BB);
196
197 ~MachineBasicBlock();
198
199 // MachineBasicBlocks are allocated and owned by MachineFunction.
200 friend class MachineFunction;
201
202 public:
203 /// Return the LLVM basic block that this instance corresponded to originally.
204 /// Note that this may be NULL if this instance does not correspond directly
205 /// to an LLVM basic block.
206 const BasicBlock *getBasicBlock() const { return BB; }
207
208 /// Return the name of the corresponding LLVM basic block, or an empty string.
209 StringRef getName() const;
210
211 /// Return a formatted string to identify this block and its parent function.
212 std::string getFullName() const;
213
214 /// Test whether this block is potentially the target of an indirect branch.
215 bool hasAddressTaken() const { return AddressTaken; }
216
217 /// Set this block to reflect that it potentially is the target of an indirect
218 /// branch.
219 void setHasAddressTaken() { AddressTaken = true; }
220
221 /// Test whether this block must have its label emitted.
222 bool hasLabelMustBeEmitted() const { return LabelMustBeEmitted; }
223
224 /// Set this block to reflect that, regardless how we flow to it, we need
225 /// its label be emitted.
226 void setLabelMustBeEmitted() { LabelMustBeEmitted = true; }
227
228 /// Return the MachineFunction containing this basic block.
229 const MachineFunction *getParent() const { return xParent; }
230 MachineFunction *getParent() { return xParent; }
231
232 using instr_iterator = Instructions::iterator;
233 using const_instr_iterator = Instructions::const_iterator;
234 using reverse_instr_iterator = Instructions::reverse_iterator;
235 using const_reverse_instr_iterator = Instructions::const_reverse_iterator;
236
237 using iterator = MachineInstrBundleIterator<MachineInstr>;
238 using const_iterator = MachineInstrBundleIterator<const MachineInstr>;
239 using reverse_iterator = MachineInstrBundleIterator<MachineInstr, true>;
240 using const_reverse_iterator =
241 MachineInstrBundleIterator<const MachineInstr, true>;
242
243 unsigned size() const { return (unsigned)Insts.size(); }
244 bool empty() const { return Insts.empty(); }
245
246 MachineInstr &instr_front() { return Insts.front(); }
247 MachineInstr &instr_back() { return Insts.back(); }
248 const MachineInstr &instr_front() const { return Insts.front(); }
249 const MachineInstr &instr_back() const { return Insts.back(); }
250
251 MachineInstr &front() { return Insts.front(); }
252 MachineInstr &back() { return *--end(); }
253 const MachineInstr &front() const { return Insts.front(); }
254 const MachineInstr &back() const { return *--end(); }
255
256 instr_iterator instr_begin() { return Insts.begin(); }
257 const_instr_iterator instr_begin() const { return Insts.begin(); }
258 instr_iterator instr_end() { return Insts.end(); }
259 const_instr_iterator instr_end() const { return Insts.end(); }
260 reverse_instr_iterator instr_rbegin() { return Insts.rbegin(); }
261 const_reverse_instr_iterator instr_rbegin() const { return Insts.rbegin(); }
262 reverse_instr_iterator instr_rend () { return Insts.rend(); }
263 const_reverse_instr_iterator instr_rend () const { return Insts.rend(); }
264
265 using instr_range = iterator_range<instr_iterator>;
266 using const_instr_range = iterator_range<const_instr_iterator>;
267 instr_range instrs() { return instr_range(instr_begin(), instr_end()); }
268 const_instr_range instrs() const {
269 return const_instr_range(instr_begin(), instr_end());
270 }
271
272 iterator begin() { return instr_begin(); }
273 const_iterator begin() const { return instr_begin(); }
274 iterator end () { return instr_end(); }
275 const_iterator end () const { return instr_end(); }
276 reverse_iterator rbegin() {
277 return reverse_iterator::getAtBundleBegin(instr_rbegin());
278 }
279 const_reverse_iterator rbegin() const {
280 return const_reverse_iterator::getAtBundleBegin(instr_rbegin());
281 }
282 reverse_iterator rend() { return reverse_iterator(instr_rend()); }
283 const_reverse_iterator rend() const {
284 return const_reverse_iterator(instr_rend());
285 }
286
287 /// Support for MachineInstr::getNextNode().
288 static Instructions MachineBasicBlock::*getSublistAccess(MachineInstr *) {
289 return &MachineBasicBlock::Insts;
290 }
291
292 inline iterator_range<iterator> terminators() {
293 return make_range(getFirstTerminator(), end());
294 }
295 inline iterator_range<const_iterator> terminators() const {
296 return make_range(getFirstTerminator(), end());
297 }
298
299 /// Returns a range that iterates over the phis in the basic block.
300 inline iterator_range<iterator> phis() {
301 return make_range(begin(), getFirstNonPHI());
302 }
303 inline iterator_range<const_iterator> phis() const {
304 return const_cast<MachineBasicBlock *>(this)->phis();
305 }
306
307 // Machine-CFG iterators
308 using pred_iterator = std::vector<MachineBasicBlock *>::iterator;
309 using const_pred_iterator = std::vector<MachineBasicBlock *>::const_iterator;
310 using succ_iterator = std::vector<MachineBasicBlock *>::iterator;
311 using const_succ_iterator = std::vector<MachineBasicBlock *>::const_iterator;
312 using pred_reverse_iterator =
313 std::vector<MachineBasicBlock *>::reverse_iterator;
314 using const_pred_reverse_iterator =
315 std::vector<MachineBasicBlock *>::const_reverse_iterator;
316 using succ_reverse_iterator =
317 std::vector<MachineBasicBlock *>::reverse_iterator;
318 using const_succ_reverse_iterator =
319 std::vector<MachineBasicBlock *>::const_reverse_iterator;
320 pred_iterator pred_begin() { return Predecessors.begin(); }
321 const_pred_iterator pred_begin() const { return Predecessors.begin(); }
322 pred_iterator pred_end() { return Predecessors.end(); }
323 const_pred_iterator pred_end() const { return Predecessors.end(); }
324 pred_reverse_iterator pred_rbegin()
325 { return Predecessors.rbegin();}
326 const_pred_reverse_iterator pred_rbegin() const
327 { return Predecessors.rbegin();}
328 pred_reverse_iterator pred_rend()
329 { return Predecessors.rend(); }
330 const_pred_reverse_iterator pred_rend() const
331 { return Predecessors.rend(); }
332 unsigned pred_size() const {
333 return (unsigned)Predecessors.size();
334 }
335 bool pred_empty() const { return Predecessors.empty(); }
336 succ_iterator succ_begin() { return Successors.begin(); }
337 const_succ_iterator succ_begin() const { return Successors.begin(); }
338 succ_iterator succ_end() { return Successors.end(); }
339 const_succ_iterator succ_end() const { return Successors.end(); }
340 succ_reverse_iterator succ_rbegin()
341 { return Successors.rbegin(); }
342 const_succ_reverse_iterator succ_rbegin() const
343 { return Successors.rbegin(); }
344 succ_reverse_iterator succ_rend()
345 { return Successors.rend(); }
346 const_succ_reverse_iterator succ_rend() const
347 { return Successors.rend(); }
348 unsigned succ_size() const {
349 return (unsigned)Successors.size();
350 }
351 bool succ_empty() const { return Successors.empty(); }
352
353 inline iterator_range<pred_iterator> predecessors() {
354 return make_range(pred_begin(), pred_end());
355 }
356 inline iterator_range<const_pred_iterator> predecessors() const {
357 return make_range(pred_begin(), pred_end());
358 }
359 inline iterator_range<succ_iterator> successors() {
360 return make_range(succ_begin(), succ_end());
361 }
362 inline iterator_range<const_succ_iterator> successors() const {
363 return make_range(succ_begin(), succ_end());
364 }
365
366 // LiveIn management methods.
367
368 /// Adds the specified register as a live in. Note that it is an error to add
369 /// the same register to the same set more than once unless the intention is
370 /// to call sortUniqueLiveIns after all registers are added.
371 void addLiveIn(MCRegister PhysReg,
372 LaneBitmask LaneMask = LaneBitmask::getAll()) {
373 LiveIns.push_back(RegisterMaskPair(PhysReg, LaneMask));
374 }
375 void addLiveIn(const RegisterMaskPair &RegMaskPair) {
376 LiveIns.push_back(RegMaskPair);
377 }
378
379 /// Sorts and uniques the LiveIns vector. It can be significantly faster to do
380 /// this than repeatedly calling isLiveIn before calling addLiveIn for every
381 /// LiveIn insertion.
382 void sortUniqueLiveIns();
383
384 /// Clear live in list.
385 void clearLiveIns();
386
387 /// Add PhysReg as live in to this block, and ensure that there is a copy of
388 /// PhysReg to a virtual register of class RC. Return the virtual register
389 /// that is a copy of the live in PhysReg.
390 Register addLiveIn(MCRegister PhysReg, const TargetRegisterClass *RC);
391
392 /// Remove the specified register from the live in set.
393 void removeLiveIn(MCPhysReg Reg,
394 LaneBitmask LaneMask = LaneBitmask::getAll());
395
396 /// Return true if the specified register is in the live in set.
397 bool isLiveIn(MCPhysReg Reg,
398 LaneBitmask LaneMask = LaneBitmask::getAll()) const;
399
400 // Iteration support for live in sets. These sets are kept in sorted
401 // order by their register number.
402 using livein_iterator = LiveInVector::const_iterator;
403 #ifndef NDEBUG
404 /// Unlike livein_begin, this method does not check that the liveness
405 /// information is accurate. Still for debug purposes it may be useful
406 /// to have iterators that won't assert if the liveness information
407 /// is not current.
408 livein_iterator livein_begin_dbg() const { return LiveIns.begin(); }
409 iterator_range<livein_iterator> liveins_dbg() const {
410 return make_range(livein_begin_dbg(), livein_end());
411 }
412 #endif
413 livein_iterator livein_begin() const;
414 livein_iterator livein_end() const { return LiveIns.end(); }
415 bool livein_empty() const { return LiveIns.empty(); }
416 iterator_range<livein_iterator> liveins() const {
417 return make_range(livein_begin(), livein_end());
418 }
419
420 /// Remove entry from the livein set and return iterator to the next.
421 livein_iterator removeLiveIn(livein_iterator I);
422
423 class liveout_iterator {
424 public:
425 using iterator_category = std::input_iterator_tag;
426 using difference_type = std::ptrdiff_t;
427 using value_type = RegisterMaskPair;
428 using pointer = const RegisterMaskPair *;
429 using reference = const RegisterMaskPair &;
430
431 liveout_iterator(const MachineBasicBlock &MBB, MCPhysReg ExceptionPointer,
432 MCPhysReg ExceptionSelector, bool End)
433 : ExceptionPointer(ExceptionPointer),
434 ExceptionSelector(ExceptionSelector), BlockI(MBB.succ_begin()),
435 BlockEnd(MBB.succ_end()) {
436 if (End)
437 BlockI = BlockEnd;
438 else if (BlockI != BlockEnd) {
439 LiveRegI = (*BlockI)->livein_begin();
440 if (!advanceToValidPosition())
441 return;
442 if (LiveRegI->PhysReg == ExceptionPointer ||
443 LiveRegI->PhysReg == ExceptionSelector)
444 ++(*this);
445 }
446 }
447
448 liveout_iterator &operator++() {
449 do {
450 ++LiveRegI;
451 if (!advanceToValidPosition())
452 return *this;
453 } while ((*BlockI)->isEHPad() &&
454 (LiveRegI->PhysReg == ExceptionPointer ||
455 LiveRegI->PhysReg == ExceptionSelector));
456 return *this;
457 }
458
459 liveout_iterator operator++(int) {
460 liveout_iterator Tmp = *this;
461 ++(*this);
462 return Tmp;
463 }
464
465 reference operator*() const {
466 return *LiveRegI;
467 }
468
469 pointer operator->() const {
470 return &*LiveRegI;
471 }
472
473 bool operator==(const liveout_iterator &RHS) const {
474 if (BlockI != BlockEnd)
475 return BlockI == RHS.BlockI && LiveRegI == RHS.LiveRegI;
476 return RHS.BlockI == BlockEnd;
477 }
478
479 bool operator!=(const liveout_iterator &RHS) const {
480 return !(*this == RHS);
481 }
482 private:
483 bool advanceToValidPosition() {
484 if (LiveRegI != (*BlockI)->livein_end())
485 return true;
486
487 do {
488 ++BlockI;
489 } while (BlockI != BlockEnd && (*BlockI)->livein_empty());
490 if (BlockI == BlockEnd)
491 return false;
492
493 LiveRegI = (*BlockI)->livein_begin();
494 return true;
495 }
496
497 MCPhysReg ExceptionPointer, ExceptionSelector;
498 const_succ_iterator BlockI;
499 const_succ_iterator BlockEnd;
500 livein_iterator LiveRegI;
501 };
502
503 /// Iterator scanning successor basic blocks' liveins to determine the
504 /// registers potentially live at the end of this block. There may be
505 /// duplicates or overlapping registers in the list returned.
506 liveout_iterator liveout_begin() const;
507 liveout_iterator liveout_end() const {
508 return liveout_iterator(*this, 0, 0, true);
509 }
510 iterator_range<liveout_iterator> liveouts() const {
511 return make_range(liveout_begin(), liveout_end());
512 }
513
514 /// Get the clobber mask for the start of this basic block. Funclets use this
515 /// to prevent register allocation across funclet transitions.
516 const uint32_t *getBeginClobberMask(const TargetRegisterInfo *TRI) const;
517
518 /// Get the clobber mask for the end of the basic block.
519 /// \see getBeginClobberMask()
520 const uint32_t *getEndClobberMask(const TargetRegisterInfo *TRI) const;
521
522 /// Return alignment of the basic block.
523 Align getAlignment() const { return Alignment; }
524
525 /// Set alignment of the basic block.
526 void setAlignment(Align A) { Alignment = A; }
527
528 void setAlignment(Align A, unsigned MaxBytes) {
529 setAlignment(A);
530 setMaxBytesForAlignment(MaxBytes);
531 }
532
533 /// Return the maximum amount of padding allowed for aligning the basic block.
534 unsigned getMaxBytesForAlignment() const { return MaxBytesForAlignment; }
535
536 /// Set the maximum amount of padding allowed for aligning the basic block
537 void setMaxBytesForAlignment(unsigned MaxBytes) {
538 MaxBytesForAlignment = MaxBytes;
539 }
540
541 /// Returns true if the block is a landing pad. That is this basic block is
542 /// entered via an exception handler.
543 bool isEHPad() const { return IsEHPad; }
544
545 /// Indicates the block is a landing pad. That is this basic block is entered
546 /// via an exception handler.
547 void setIsEHPad(bool V = true) { IsEHPad = V; }
548
549 bool hasEHPadSuccessor() const;
550
551 /// Returns true if this is the entry block of the function.
552 bool isEntryBlock() const;
553
554 /// Returns true if this is the entry block of an EH scope, i.e., the block
555 /// that used to have a catchpad or cleanuppad instruction in the LLVM IR.
556 bool isEHScopeEntry() const { return IsEHScopeEntry; }
557
558 /// Indicates if this is the entry block of an EH scope, i.e., the block that
559 /// that used to have a catchpad or cleanuppad instruction in the LLVM IR.
560 void setIsEHScopeEntry(bool V = true) { IsEHScopeEntry = V; }
561
562 /// Returns true if this is a target block of a catchret.
563 bool isEHCatchretTarget() const { return IsEHCatchretTarget; }
564
565 /// Indicates if this is a target block of a catchret.
566 void setIsEHCatchretTarget(bool V = true) { IsEHCatchretTarget = V; }
567
568 /// Returns true if this is the entry block of an EH funclet.
569 bool isEHFuncletEntry() const { return IsEHFuncletEntry; }
570
571 /// Indicates if this is the entry block of an EH funclet.
572 void setIsEHFuncletEntry(bool V = true) { IsEHFuncletEntry = V; }
573
574 /// Returns true if this is the entry block of a cleanup funclet.
575 bool isCleanupFuncletEntry() const { return IsCleanupFuncletEntry; }
576
577 /// Indicates if this is the entry block of a cleanup funclet.
578 void setIsCleanupFuncletEntry(bool V = true) { IsCleanupFuncletEntry = V; }
579
580 /// Returns true if this block begins any section.
581 bool isBeginSection() const { return IsBeginSection; }
582
583 /// Returns true if this block ends any section.
584 bool isEndSection() const { return IsEndSection; }
585
586 void setIsBeginSection(bool V = true) { IsBeginSection = V; }
587
588 void setIsEndSection(bool V = true) { IsEndSection = V; }
589
590 /// Returns the section ID of this basic block.
591 MBBSectionID getSectionID() const { return SectionID; }
592
593 /// Returns the unique section ID number of this basic block.
594 unsigned getSectionIDNum() const {
595 return ((unsigned)MBBSectionID::SectionType::Cold) -
596 ((unsigned)SectionID.Type) + SectionID.Number;
597 }
598
599 /// Sets the section ID for this basic block.
600 void setSectionID(MBBSectionID V) { SectionID = V; }
601
602 /// Returns the MCSymbol marking the end of this basic block.
603 MCSymbol *getEndSymbol() const;
604
605 /// Returns true if this block may have an INLINEASM_BR (overestimate, by
606 /// checking if any of the successors are indirect targets of any inlineasm_br
607 /// in the function).
608 bool mayHaveInlineAsmBr() const;
609
610 /// Returns true if this is the indirect dest of an INLINEASM_BR.
611 bool isInlineAsmBrIndirectTarget() const {
612 return IsInlineAsmBrIndirectTarget;
613 }
614
615 /// Indicates if this is the indirect dest of an INLINEASM_BR.
616 void setIsInlineAsmBrIndirectTarget(bool V = true) {
617 IsInlineAsmBrIndirectTarget = V;
618 }
619
620 /// Returns true if it is legal to hoist instructions into this block.
621 bool isLegalToHoistInto() const;
622
623 // Code Layout methods.
624
625 /// Move 'this' block before or after the specified block. This only moves
626 /// the block, it does not modify the CFG or adjust potential fall-throughs at
627 /// the end of the block.
628 void moveBefore(MachineBasicBlock *NewAfter);
629 void moveAfter(MachineBasicBlock *NewBefore);
630
631 /// Returns true if this and MBB belong to the same section.
632 bool sameSection(const MachineBasicBlock *MBB) const {
633 return getSectionID() == MBB->getSectionID();
634 }
635
636 /// Update the terminator instructions in block to account for changes to
637 /// block layout which may have been made. PreviousLayoutSuccessor should be
638 /// set to the block which may have been used as fallthrough before the block
639 /// layout was modified. If the block previously fell through to that block,
640 /// it may now need a branch. If it previously branched to another block, it
641 /// may now be able to fallthrough to the current layout successor.
642 void updateTerminator(MachineBasicBlock *PreviousLayoutSuccessor);
643
644 // Machine-CFG mutators
645
646 /// Add Succ as a successor of this MachineBasicBlock. The Predecessors list
647 /// of Succ is automatically updated. PROB parameter is stored in
648 /// Probabilities list. The default probability is set as unknown. Mixing
649 /// known and unknown probabilities in successor list is not allowed. When all
650 /// successors have unknown probabilities, 1 / N is returned as the
651 /// probability for each successor, where N is the number of successors.
652 ///
653 /// Note that duplicate Machine CFG edges are not allowed.
654 void addSuccessor(MachineBasicBlock *Succ,
655 BranchProbability Prob = BranchProbability::getUnknown());
656
657 /// Add Succ as a successor of this MachineBasicBlock. The Predecessors list
658 /// of Succ is automatically updated. The probability is not provided because
659 /// BPI is not available (e.g. -O0 is used), in which case edge probabilities
660 /// won't be used. Using this interface can save some space.
661 void addSuccessorWithoutProb(MachineBasicBlock *Succ);
662
663 /// Set successor probability of a given iterator.
664 void setSuccProbability(succ_iterator I, BranchProbability Prob);
665
666 /// Normalize probabilities of all successors so that the sum of them becomes
667 /// one. This is usually done when the current update on this MBB is done, and
668 /// the sum of its successors' probabilities is not guaranteed to be one. The
669 /// user is responsible for the correct use of this function.
670 /// MBB::removeSuccessor() has an option to do this automatically.
671 void normalizeSuccProbs() {
672 BranchProbability::normalizeProbabilities(Probs.begin(), Probs.end());
673 }
674
675 /// Validate successors' probabilities and check if the sum of them is
676 /// approximate one. This only works in DEBUG mode.
677 void validateSuccProbs() const;
678
679 /// Remove successor from the successors list of this MachineBasicBlock. The
680 /// Predecessors list of Succ is automatically updated.
681 /// If NormalizeSuccProbs is true, then normalize successors' probabilities
682 /// after the successor is removed.
683 void removeSuccessor(MachineBasicBlock *Succ,
684 bool NormalizeSuccProbs = false);
685
686 /// Remove specified successor from the successors list of this
687 /// MachineBasicBlock. The Predecessors list of Succ is automatically updated.
688 /// If NormalizeSuccProbs is true, then normalize successors' probabilities
689 /// after the successor is removed.
690 /// Return the iterator to the element after the one removed.
691 succ_iterator removeSuccessor(succ_iterator I,
692 bool NormalizeSuccProbs = false);
693
694 /// Replace successor OLD with NEW and update probability info.
695 void replaceSuccessor(MachineBasicBlock *Old, MachineBasicBlock *New);
696
697 /// Copy a successor (and any probability info) from original block to this
698 /// block's. Uses an iterator into the original blocks successors.
699 ///
700 /// This is useful when doing a partial clone of successors. Afterward, the
701 /// probabilities may need to be normalized.
702 void copySuccessor(MachineBasicBlock *Orig, succ_iterator I);
703
704 /// Split the old successor into old plus new and updates the probability
705 /// info.
706 void splitSuccessor(MachineBasicBlock *Old, MachineBasicBlock *New,
707 bool NormalizeSuccProbs = false);
708
709 /// Transfers all the successors from MBB to this machine basic block (i.e.,
710 /// copies all the successors FromMBB and remove all the successors from
711 /// FromMBB).
712 void transferSuccessors(MachineBasicBlock *FromMBB);
713
714 /// Transfers all the successors, as in transferSuccessors, and update PHI
715 /// operands in the successor blocks which refer to FromMBB to refer to this.
716 void transferSuccessorsAndUpdatePHIs(MachineBasicBlock *FromMBB);
717
718 /// Return true if any of the successors have probabilities attached to them.
719 bool hasSuccessorProbabilities() const { return !Probs.empty(); }
720
721 /// Return true if the specified MBB is a predecessor of this block.
722 bool isPredecessor(const MachineBasicBlock *MBB) const;
723
724 /// Return true if the specified MBB is a successor of this block.
725 bool isSuccessor(const MachineBasicBlock *MBB) const;
726
727 /// Return true if the specified MBB will be emitted immediately after this
728 /// block, such that if this block exits by falling through, control will
729 /// transfer to the specified MBB. Note that MBB need not be a successor at
730 /// all, for example if this block ends with an unconditional branch to some
731 /// other block.
732 bool isLayoutSuccessor(const MachineBasicBlock *MBB) const;
733
734 /// Return the fallthrough block if the block can implicitly
735 /// transfer control to the block after it by falling off the end of
736 /// it. This should return null if it can reach the block after
737 /// it, but it uses an explicit branch to do so (e.g., a table
738 /// jump). Non-null return is a conservative answer.
739 MachineBasicBlock *getFallThrough();
740
741 /// Return true if the block can implicitly transfer control to the
742 /// block after it by falling off the end of it. This should return
743 /// false if it can reach the block after it, but it uses an
744 /// explicit branch to do so (e.g., a table jump). True is a
745 /// conservative answer.
746 bool canFallThrough();
747
748 /// Returns a pointer to the first instruction in this block that is not a
749 /// PHINode instruction. When adding instructions to the beginning of the
750 /// basic block, they should be added before the returned value, not before
751 /// the first instruction, which might be PHI.
752 /// Returns end() is there's no non-PHI instruction.
753 iterator getFirstNonPHI();
754
755 /// Return the first instruction in MBB after I that is not a PHI or a label.
756 /// This is the correct point to insert lowered copies at the beginning of a
757 /// basic block that must be before any debugging information.
758 iterator SkipPHIsAndLabels(iterator I);
759
760 /// Return the first instruction in MBB after I that is not a PHI, label or
761 /// debug. This is the correct point to insert copies at the beginning of a
762 /// basic block.
763 iterator SkipPHIsLabelsAndDebug(iterator I, bool SkipPseudoOp = true);
764
765 /// Returns an iterator to the first terminator instruction of this basic
766 /// block. If a terminator does not exist, it returns end().
767 iterator getFirstTerminator();
768 const_iterator getFirstTerminator() const {
769 return const_cast<MachineBasicBlock *>(this)->getFirstTerminator();
770 }
771
772 /// Same getFirstTerminator but it ignores bundles and return an
773 /// instr_iterator instead.
774 instr_iterator getFirstInstrTerminator();
775
776 /// Returns an iterator to the first non-debug instruction in the basic block,
777 /// or end(). Skip any pseudo probe operation if \c SkipPseudoOp is true.
778 /// Pseudo probes are like debug instructions which do not turn into real
779 /// machine code. We try to use the function to skip both debug instructions
780 /// and pseudo probe operations to avoid API proliferation. This should work
781 /// most of the time when considering optimizing the rest of code in the
782 /// block, except for certain cases where pseudo probes are designed to block
783 /// the optimizations. For example, code merge like optimizations are supposed
784 /// to be blocked by pseudo probes for better AutoFDO profile quality.
785 /// Therefore, they should be considered as a valid instruction when this
786 /// function is called in a context of such optimizations. On the other hand,
787 /// \c SkipPseudoOp should be true when it's used in optimizations that
788 /// unlikely hurt profile quality, e.g., without block merging. The default
789 /// value of \c SkipPseudoOp is set to true to maximize code quality in
790 /// general, with an explict false value passed in in a few places like branch
791 /// folding and if-conversion to favor profile quality.
792 iterator getFirstNonDebugInstr(bool SkipPseudoOp = true);
793 const_iterator getFirstNonDebugInstr(bool SkipPseudoOp = true) const {
794 return const_cast<MachineBasicBlock *>(this)->getFirstNonDebugInstr(
795 SkipPseudoOp);
796 }
797
798 /// Returns an iterator to the last non-debug instruction in the basic block,
799 /// or end(). Skip any pseudo operation if \c SkipPseudoOp is true.
800 /// Pseudo probes are like debug instructions which do not turn into real
801 /// machine code. We try to use the function to skip both debug instructions
802 /// and pseudo probe operations to avoid API proliferation. This should work
803 /// most of the time when considering optimizing the rest of code in the
804 /// block, except for certain cases where pseudo probes are designed to block
805 /// the optimizations. For example, code merge like optimizations are supposed
806 /// to be blocked by pseudo probes for better AutoFDO profile quality.
807 /// Therefore, they should be considered as a valid instruction when this
808 /// function is called in a context of such optimizations. On the other hand,
809 /// \c SkipPseudoOp should be true when it's used in optimizations that
810 /// unlikely hurt profile quality, e.g., without block merging. The default
811 /// value of \c SkipPseudoOp is set to true to maximize code quality in
812 /// general, with an explict false value passed in in a few places like branch
813 /// folding and if-conversion to favor profile quality.
814 iterator getLastNonDebugInstr(bool SkipPseudoOp = true);
815 const_iterator getLastNonDebugInstr(bool SkipPseudoOp = true) const {
816 return const_cast<MachineBasicBlock *>(this)->getLastNonDebugInstr(
817 SkipPseudoOp);
818 }
819
820 /// Convenience function that returns true if the block ends in a return
821 /// instruction.
822 bool isReturnBlock() const {
823 return !empty() && back().isReturn();
824 }
825
826 /// Convenience function that returns true if the bock ends in a EH scope
827 /// return instruction.
828 bool isEHScopeReturnBlock() const {
829 return !empty() && back().isEHScopeReturn();
830 }
831
832 /// Split a basic block into 2 pieces at \p SplitPoint. A new block will be
833 /// inserted after this block, and all instructions after \p SplitInst moved
834 /// to it (\p SplitInst will be in the original block). If \p LIS is provided,
835 /// LiveIntervals will be appropriately updated. \return the newly inserted
836 /// block.
837 ///
838 /// If \p UpdateLiveIns is true, this will ensure the live ins list is
839 /// accurate, including for physreg uses/defs in the original block.
840 MachineBasicBlock *splitAt(MachineInstr &SplitInst, bool UpdateLiveIns = true,
841 LiveIntervals *LIS = nullptr);
842
843 /// Split the critical edge from this block to the given successor block, and
844 /// return the newly created block, or null if splitting is not possible.
845 ///
846 /// This function updates LiveVariables, MachineDominatorTree, and
847 /// MachineLoopInfo, as applicable.
848 MachineBasicBlock *
849 SplitCriticalEdge(MachineBasicBlock *Succ, Pass &P,
850 std::vector<SparseBitVector<>> *LiveInSets = nullptr);
851
852 /// Check if the edge between this block and the given successor \p
853 /// Succ, can be split. If this returns true a subsequent call to
854 /// SplitCriticalEdge is guaranteed to return a valid basic block if
855 /// no changes occurred in the meantime.
856 bool canSplitCriticalEdge(const MachineBasicBlock *Succ) const;
857
858 void pop_front() { Insts.pop_front(); }
859 void pop_back() { Insts.pop_back(); }
860 void push_back(MachineInstr *MI) { Insts.push_back(MI); }
861
862 /// Insert MI into the instruction list before I, possibly inside a bundle.
863 ///
864 /// If the insertion point is inside a bundle, MI will be added to the bundle,
865 /// otherwise MI will not be added to any bundle. That means this function
866 /// alone can't be used to prepend or append instructions to bundles. See
867 /// MIBundleBuilder::insert() for a more reliable way of doing that.
868 instr_iterator insert(instr_iterator I, MachineInstr *M);
869
870 /// Insert a range of instructions into the instruction list before I.
871 template<typename IT>
872 void insert(iterator I, IT S, IT E) {
873 assert((I == end() || I->getParent() == this) &&
874 "iterator points outside of basic block");
875 Insts.insert(I.getInstrIterator(), S, E);
876 }
877
878 /// Insert MI into the instruction list before I.
879 iterator insert(iterator I, MachineInstr *MI) {
880 assert((I == end() || I->getParent() == this) &&
881 "iterator points outside of basic block");
882 assert(!MI->isBundledWithPred() && !MI->isBundledWithSucc() &&
883 "Cannot insert instruction with bundle flags");
884 return Insts.insert(I.getInstrIterator(), MI);
885 }
886
887 /// Insert MI into the instruction list after I.
888 iterator insertAfter(iterator I, MachineInstr *MI) {
889 assert((I == end() || I->getParent() == this) &&
890 "iterator points outside of basic block");
891 assert(!MI->isBundledWithPred() && !MI->isBundledWithSucc() &&
892 "Cannot insert instruction with bundle flags");
893 return Insts.insertAfter(I.getInstrIterator(), MI);
894 }
895
896 /// If I is bundled then insert MI into the instruction list after the end of
897 /// the bundle, otherwise insert MI immediately after I.
898 instr_iterator insertAfterBundle(instr_iterator I, MachineInstr *MI) {
899 assert((I == instr_end() || I->getParent() == this) &&
900 "iterator points outside of basic block");
901 assert(!MI->isBundledWithPred() && !MI->isBundledWithSucc() &&
902 "Cannot insert instruction with bundle flags");
903 while (I->isBundledWithSucc())
904 ++I;
905 return Insts.insertAfter(I, MI);
906 }
907
908 /// Remove an instruction from the instruction list and delete it.
909 ///
910 /// If the instruction is part of a bundle, the other instructions in the
911 /// bundle will still be bundled after removing the single instruction.
912 instr_iterator erase(instr_iterator I);
913
914 /// Remove an instruction from the instruction list and delete it.
915 ///
916 /// If the instruction is part of a bundle, the other instructions in the
917 /// bundle will still be bundled after removing the single instruction.
918 instr_iterator erase_instr(MachineInstr *I) {
919 return erase(instr_iterator(I));
920 }
921
922 /// Remove a range of instructions from the instruction list and delete them.
923 iterator erase(iterator I, iterator E) {
924 return Insts.erase(I.getInstrIterator(), E.getInstrIterator());
925 }
926
927 /// Remove an instruction or bundle from the instruction list and delete it.
928 ///
929 /// If I points to a bundle of instructions, they are all erased.
930 iterator erase(iterator I) {
931 return erase(I, std::next(I));
932 }
933
934 /// Remove an instruction from the instruction list and delete it.
935 ///
936 /// If I is the head of a bundle of instructions, the whole bundle will be
937 /// erased.
938 iterator erase(MachineInstr *I) {
939 return erase(iterator(I));
940 }
941
942 /// Remove the unbundled instruction from the instruction list without
943 /// deleting it.
944 ///
945 /// This function can not be used to remove bundled instructions, use
946 /// remove_instr to remove individual instructions from a bundle.
947 MachineInstr *remove(MachineInstr *I) {
948 assert(!I->isBundled() && "Cannot remove bundled instructions");
949 return Insts.remove(instr_iterator(I));
950 }
951
952 /// Remove the possibly bundled instruction from the instruction list
953 /// without deleting it.
954 ///
955 /// If the instruction is part of a bundle, the other instructions in the
956 /// bundle will still be bundled after removing the single instruction.
957 MachineInstr *remove_instr(MachineInstr *I);
958
959 void clear() {
960 Insts.clear();
961 }
962
963 /// Take an instruction from MBB 'Other' at the position From, and insert it
964 /// into this MBB right before 'Where'.
965 ///
966 /// If From points to a bundle of instructions, the whole bundle is moved.
967 void splice(iterator Where, MachineBasicBlock *Other, iterator From) {
968 // The range splice() doesn't allow noop moves, but this one does.
969 if (Where != From)
970 splice(Where, Other, From, std::next(From));
971 }
972
973 /// Take a block of instructions from MBB 'Other' in the range [From, To),
974 /// and insert them into this MBB right before 'Where'.
975 ///
976 /// The instruction at 'Where' must not be included in the range of
977 /// instructions to move.
978 void splice(iterator Where, MachineBasicBlock *Other,
979 iterator From, iterator To) {
980 Insts.splice(Where.getInstrIterator(), Other->Insts,
981 From.getInstrIterator(), To.getInstrIterator());
982 }
983
984 /// This method unlinks 'this' from the containing function, and returns it,
985 /// but does not delete it.
986 MachineBasicBlock *removeFromParent();
987
988 /// This method unlinks 'this' from the containing function and deletes it.
989 void eraseFromParent();
990
991 /// Given a machine basic block that branched to 'Old', change the code and
992 /// CFG so that it branches to 'New' instead.
993 void ReplaceUsesOfBlockWith(MachineBasicBlock *Old, MachineBasicBlock *New);
994
995 /// Update all phi nodes in this basic block to refer to basic block \p New
996 /// instead of basic block \p Old.
997 void replacePhiUsesWith(MachineBasicBlock *Old, MachineBasicBlock *New);
998
999 /// Find the next valid DebugLoc starting at MBBI, skipping any DBG_VALUE
1000 /// and DBG_LABEL instructions. Return UnknownLoc if there is none.
1001 DebugLoc findDebugLoc(instr_iterator MBBI);
1002 DebugLoc findDebugLoc(iterator MBBI) {
1003 return findDebugLoc(MBBI.getInstrIterator());
1004 }
1005
1006 /// Has exact same behavior as @ref findDebugLoc (it also
1007 /// searches from the first to the last MI of this MBB) except
1008 /// that this takes reverse iterator.
1009 DebugLoc rfindDebugLoc(reverse_instr_iterator MBBI);
1010 DebugLoc rfindDebugLoc(reverse_iterator MBBI) {
1011 return rfindDebugLoc(MBBI.getInstrIterator());
1012 }
1013
1014 /// Find the previous valid DebugLoc preceding MBBI, skipping and DBG_VALUE
1015 /// instructions. Return UnknownLoc if there is none.
1016 DebugLoc findPrevDebugLoc(instr_iterator MBBI);
1017 DebugLoc findPrevDebugLoc(iterator MBBI) {
1018 return findPrevDebugLoc(MBBI.getInstrIterator());
1019 }
1020
1021 /// Has exact same behavior as @ref findPrevDebugLoc (it also
1022 /// searches from the last to the first MI of this MBB) except
1023 /// that this takes reverse iterator.
1024 DebugLoc rfindPrevDebugLoc(reverse_instr_iterator MBBI);
1025 DebugLoc rfindPrevDebugLoc(reverse_iterator MBBI) {
1026 return rfindPrevDebugLoc(MBBI.getInstrIterator());
1027 }
1028
1029 /// Find and return the merged DebugLoc of the branch instructions of the
1030 /// block. Return UnknownLoc if there is none.
1031 DebugLoc findBranchDebugLoc();
1032
1033 /// Possible outcome of a register liveness query to computeRegisterLiveness()
1034 enum LivenessQueryResult {
1035 LQR_Live, ///< Register is known to be (at least partially) live.
1036 LQR_Dead, ///< Register is known to be fully dead.
1037 LQR_Unknown ///< Register liveness not decidable from local neighborhood.
1038 };
1039
1040 /// Return whether (physical) register \p Reg has been defined and not
1041 /// killed as of just before \p Before.
1042 ///
1043 /// Search is localised to a neighborhood of \p Neighborhood instructions
1044 /// before (searching for defs or kills) and \p Neighborhood instructions
1045 /// after (searching just for defs) \p Before.
1046 ///
1047 /// \p Reg must be a physical register.
1048 LivenessQueryResult computeRegisterLiveness(const TargetRegisterInfo *TRI,
1049 MCRegister Reg,
1050 const_iterator Before,
1051 unsigned Neighborhood = 10) const;
1052
1053 // Debugging methods.
1054 void dump() const;
1055 void print(raw_ostream &OS, const SlotIndexes * = nullptr,
1056 bool IsStandalone = true) const;
1057 void print(raw_ostream &OS, ModuleSlotTracker &MST,
1058 const SlotIndexes * = nullptr, bool IsStandalone = true) const;
1059
1060 enum PrintNameFlag {
1061 PrintNameIr = (1 << 0), ///< Add IR name where available
1062 PrintNameAttributes = (1 << 1), ///< Print attributes
1063 };
1064
1065 void printName(raw_ostream &os, unsigned printNameFlags = PrintNameIr,
1066 ModuleSlotTracker *moduleSlotTracker = nullptr) const;
1067
1068 // Printing method used by LoopInfo.
1069 void printAsOperand(raw_ostream &OS, bool PrintType = true) const;
1070
1071 /// MachineBasicBlocks are uniquely numbered at the function level, unless
1072 /// they're not in a MachineFunction yet, in which case this will return -1.
1073 int getNumber() const { return Number; }
1074 void setNumber(int N) { Number = N; }
1075
1076 /// Return the MCSymbol for this basic block.
1077 MCSymbol *getSymbol() const;
1078
1079 /// Return the EHCatchret Symbol for this basic block.
1080 MCSymbol *getEHCatchretSymbol() const;
1081
1082 Optional<uint64_t> getIrrLoopHeaderWeight() const {
1083 return IrrLoopHeaderWeight;
1084 }
1085
1086 void setIrrLoopHeaderWeight(uint64_t Weight) {
1087 IrrLoopHeaderWeight = Weight;
1088 }
1089
1090 private:
1091 /// Return probability iterator corresponding to the I successor iterator.
1092 probability_iterator getProbabilityIterator(succ_iterator I);
1093 const_probability_iterator
1094 getProbabilityIterator(const_succ_iterator I) const;
1095
1096 friend class MachineBranchProbabilityInfo;
1097 friend class MIPrinter;
1098
1099 /// Return probability of the edge from this block to MBB. This method should
1100 /// NOT be called directly, but by using getEdgeProbability method from
1101 /// MachineBranchProbabilityInfo class.
1102 BranchProbability getSuccProbability(const_succ_iterator Succ) const;
1103
1104 // Methods used to maintain doubly linked list of blocks...
1105 friend struct ilist_callback_traits<MachineBasicBlock>;
1106
1107 // Machine-CFG mutators
1108
1109 /// Add Pred as a predecessor of this MachineBasicBlock. Don't do this
1110 /// unless you know what you're doing, because it doesn't update Pred's
1111 /// successors list. Use Pred->addSuccessor instead.
1112 void addPredecessor(MachineBasicBlock *Pred);
1113
1114 /// Remove Pred as a predecessor of this MachineBasicBlock. Don't do this
1115 /// unless you know what you're doing, because it doesn't update Pred's
1116 /// successors list. Use Pred->removeSuccessor instead.
1117 void removePredecessor(MachineBasicBlock *Pred);
1118 };
1119
1120 raw_ostream& operator<<(raw_ostream &OS, const MachineBasicBlock &MBB);
1121
1122 /// Prints a machine basic block reference.
1123 ///
1124 /// The format is:
1125 /// %bb.5 - a machine basic block with MBB.getNumber() == 5.
1126 ///
1127 /// Usage: OS << printMBBReference(MBB) << '\n';
1128 Printable printMBBReference(const MachineBasicBlock &MBB);
1129
1130 // This is useful when building IndexedMaps keyed on basic block pointers.
1131 struct MBB2NumberFunctor {
1132 using argument_type = const MachineBasicBlock *;
1133 unsigned operator()(const MachineBasicBlock *MBB) const {
1134 return MBB->getNumber();
1135 }
1136 };
1137
1138 //===--------------------------------------------------------------------===//
1139 // GraphTraits specializations for machine basic block graphs (machine-CFGs)
1140 //===--------------------------------------------------------------------===//
1141
1142 // Provide specializations of GraphTraits to be able to treat a
1143 // MachineFunction as a graph of MachineBasicBlocks.
1144 //
1145
1146 template <> struct GraphTraits<MachineBasicBlock *> {
1147 using NodeRef = MachineBasicBlock *;
1148 using ChildIteratorType = MachineBasicBlock::succ_iterator;
1149
1150 static NodeRef getEntryNode(MachineBasicBlock *BB) { return BB; }
1151 static ChildIteratorType child_begin(NodeRef N) { return N->succ_begin(); }
1152 static ChildIteratorType child_end(NodeRef N) { return N->succ_end(); }
1153 };
1154
1155 template <> struct GraphTraits<const MachineBasicBlock *> {
1156 using NodeRef = const MachineBasicBlock *;
1157 using ChildIteratorType = MachineBasicBlock::const_succ_iterator;
1158
1159 static NodeRef getEntryNode(const MachineBasicBlock *BB) { return BB; }
1160 static ChildIteratorType child_begin(NodeRef N) { return N->succ_begin(); }
1161 static ChildIteratorType child_end(NodeRef N) { return N->succ_end(); }
1162 };
1163
1164 // Provide specializations of GraphTraits to be able to treat a
1165 // MachineFunction as a graph of MachineBasicBlocks and to walk it
1166 // in inverse order. Inverse order for a function is considered
1167 // to be when traversing the predecessor edges of a MBB
1168 // instead of the successor edges.
1169 //
1170 template <> struct GraphTraits<Inverse<MachineBasicBlock*>> {
1171 using NodeRef = MachineBasicBlock *;
1172 using ChildIteratorType = MachineBasicBlock::pred_iterator;
1173
1174 static NodeRef getEntryNode(Inverse<MachineBasicBlock *> G) {
1175 return G.Graph;
1176 }
1177
1178 static ChildIteratorType child_begin(NodeRef N) { return N->pred_begin(); }
1179 static ChildIteratorType child_end(NodeRef N) { return N->pred_end(); }
1180 };
1181
1182 template <> struct GraphTraits<Inverse<const MachineBasicBlock*>> {
1183 using NodeRef = const MachineBasicBlock *;
1184 using ChildIteratorType = MachineBasicBlock::const_pred_iterator;
1185
1186 static NodeRef getEntryNode(Inverse<const MachineBasicBlock *> G) {
1187 return G.Graph;
1188 }
1189
1190 static ChildIteratorType child_begin(NodeRef N) { return N->pred_begin(); }
1191 static ChildIteratorType child_end(NodeRef N) { return N->pred_end(); }
1192 };
1193
1194 /// MachineInstrSpan provides an interface to get an iteration range
1195 /// containing the instruction it was initialized with, along with all
1196 /// those instructions inserted prior to or following that instruction
1197 /// at some point after the MachineInstrSpan is constructed.
1198 class MachineInstrSpan {
1199 MachineBasicBlock &MBB;
1200 MachineBasicBlock::iterator I, B, E;
1201
1202 public:
1203 MachineInstrSpan(MachineBasicBlock::iterator I, MachineBasicBlock *BB)
1204 : MBB(*BB), I(I), B(I == MBB.begin() ? MBB.end() : std::prev(I)),
1205 E(std::next(I)) {
1206 assert(I == BB->end() || I->getParent() == BB);
1207 }
1208
1209 MachineBasicBlock::iterator begin() {
1210 return B == MBB.end() ? MBB.begin() : std::next(B);
1211 }
1212 MachineBasicBlock::iterator end() { return E; }
1213 bool empty() { return begin() == end(); }
1214
1215 MachineBasicBlock::iterator getInitial() { return I; }
1216 };
1217
1218 /// Increment \p It until it points to a non-debug instruction or to \p End
1219 /// and return the resulting iterator. This function should only be used
1220 /// MachineBasicBlock::{iterator, const_iterator, instr_iterator,
1221 /// const_instr_iterator} and the respective reverse iterators.
1222 template <typename IterT>
1223 inline IterT skipDebugInstructionsForward(IterT It, IterT End,
1224 bool SkipPseudoOp = true) {
1225 while (It != End &&
1226 (It->isDebugInstr() || (SkipPseudoOp && It->isPseudoProbe())))
1227 ++It;
1228 return It;
1229 }
1230
1231 /// Decrement \p It until it points to a non-debug instruction or to \p Begin
1232 /// and return the resulting iterator. This function should only be used
1233 /// MachineBasicBlock::{iterator, const_iterator, instr_iterator,
1234 /// const_instr_iterator} and the respective reverse iterators.
1235 template <class IterT>
1236 inline IterT skipDebugInstructionsBackward(IterT It, IterT Begin,
1237 bool SkipPseudoOp = true) {
1238 while (It != Begin &&
1239 (It->isDebugInstr() || (SkipPseudoOp && It->isPseudoProbe())))
1240 --It;
1241 return It;
1242 }
1243
1244 /// Increment \p It, then continue incrementing it while it points to a debug
1245 /// instruction. A replacement for std::next.
1246 template <typename IterT>
1247 inline IterT next_nodbg(IterT It, IterT End, bool SkipPseudoOp = true) {
1248 return skipDebugInstructionsForward(std::next(It), End, SkipPseudoOp);
1249 }
1250
1251 /// Decrement \p It, then continue decrementing it while it points to a debug
1252 /// instruction. A replacement for std::prev.
1253 template <typename IterT>
1254 inline IterT prev_nodbg(IterT It, IterT Begin, bool SkipPseudoOp = true) {
1255 return skipDebugInstructionsBackward(std::prev(It), Begin, SkipPseudoOp);
1256 }
1257
1258 /// Construct a range iterator which begins at \p It and moves forwards until
1259 /// \p End is reached, skipping any debug instructions.
1260 template <typename IterT>
1261 inline auto instructionsWithoutDebug(IterT It, IterT End,
1262 bool SkipPseudoOp = true) {
1263 return make_filter_range(make_range(It, End), [=](const MachineInstr &MI) {
1264 return !MI.isDebugInstr() && !(SkipPseudoOp && MI.isPseudoProbe());
1265 });
1266 }
1267
1268 } // end namespace llvm
1269
1270 #endif // LLVM_CODEGEN_MACHINEBASICBLOCK_H