1 //===- llvm/CodeGen/MachineRegisterInfo.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 // This file defines the MachineRegisterInfo class.
10 //
11 //===----------------------------------------------------------------------===//
12 
13 #ifndef LLVM_CODEGEN_MACHINEREGISTERINFO_H
14 #define LLVM_CODEGEN_MACHINEREGISTERINFO_H
15 
16 #include "llvm/ADT/ArrayRef.h"
17 #include "llvm/ADT/BitVector.h"
18 #include "llvm/ADT/IndexedMap.h"
19 #include "llvm/ADT/PointerUnion.h"
20 #include "llvm/ADT/SmallVector.h"
21 #include "llvm/ADT/StringSet.h"
22 #include "llvm/ADT/iterator_range.h"
23 #include "llvm/CodeGen/MachineBasicBlock.h"
24 #include "llvm/CodeGen/MachineFunction.h"
25 #include "llvm/CodeGen/MachineInstrBundle.h"
26 #include "llvm/CodeGen/MachineOperand.h"
27 #include "llvm/CodeGen/RegisterBank.h"
28 #include "llvm/CodeGen/TargetRegisterInfo.h"
29 #include "llvm/CodeGen/TargetSubtargetInfo.h"
30 #include "llvm/MC/LaneBitmask.h"
31 #include <cassert>
32 #include <cstddef>
33 #include <cstdint>
34 #include <iterator>
35 #include <memory>
36 #include <utility>
37 #include <vector>
38 
39 namespace llvm {
40 
41 class PSetIterator;
42 
43 /// Convenient type to represent either a register class or a register bank.
44 using RegClassOrRegBank =
45     PointerUnion<const TargetRegisterClass *, const RegisterBank *>;
46 
47 /// MachineRegisterInfo - Keep track of information for virtual and physical
48 /// registers, including vreg register classes, use/def chains for registers,
49 /// etc.
50 class MachineRegisterInfo {
51 public:
52   class Delegate {
53     virtual void anchor();
54 
55   public:
56     virtual ~Delegate() = default;
57 
58     virtual void MRI_NoteNewVirtualRegister(Register Reg) = 0;
59   };
60 
61 private:
62   MachineFunction *MF;
63   Delegate *TheDelegate = nullptr;
64 
65   /// True if subregister liveness is tracked.
66   const bool TracksSubRegLiveness;
67 
68   /// VRegInfo - Information we keep for each virtual register.
69   ///
70   /// Each element in this list contains the register class of the vreg and the
71   /// start of the use/def list for the register.
72   IndexedMap<std::pair<RegClassOrRegBank, MachineOperand *>,
73              VirtReg2IndexFunctor>
74       VRegInfo;
75 
76   /// Map for recovering vreg name from vreg number.
77   /// This map is used by the MIR Printer.
78   IndexedMap<std::string, VirtReg2IndexFunctor> VReg2Name;
79 
80   /// StringSet that is used to unique vreg names.
81   StringSet<> VRegNames;
82 
83   /// The flag is true upon \p UpdatedCSRs initialization
84   /// and false otherwise.
85   bool IsUpdatedCSRsInitialized = false;
86 
87   /// Contains the updated callee saved register list.
88   /// As opposed to the static list defined in register info,
89   /// all registers that were disabled are removed from the list.
90   SmallVector<MCPhysReg, 16> UpdatedCSRs;
91 
92   /// RegAllocHints - This vector records register allocation hints for
93   /// virtual registers. For each virtual register, it keeps a pair of hint
94   /// type and hints vector making up the allocation hints. Only the first
95   /// hint may be target specific, and in that case this is reflected by the
96   /// first member of the pair being non-zero. If the hinted register is
97   /// virtual, it means the allocator should prefer the physical register
98   /// allocated to it if any.
99   IndexedMap<std::pair<Register, SmallVector<Register, 4>>,
100              VirtReg2IndexFunctor> RegAllocHints;
101 
102   /// PhysRegUseDefLists - This is an array of the head of the use/def list for
103   /// physical registers.
104   std::unique_ptr<MachineOperand *[]> PhysRegUseDefLists;
105 
106   /// getRegUseDefListHead - Return the head pointer for the register use/def
107   /// list for the specified virtual or physical register.
108   MachineOperand *&getRegUseDefListHead(Register RegNo) {
109     if (RegNo.isVirtual())
110       return VRegInfo[RegNo.id()].second;
111     return PhysRegUseDefLists[RegNo.id()];
112   }
113 
114   MachineOperand *getRegUseDefListHead(Register RegNo) const {
115     if (RegNo.isVirtual())
116       return VRegInfo[RegNo.id()].second;
117     return PhysRegUseDefLists[RegNo.id()];
118   }
119 
120   /// Get the next element in the use-def chain.
121   static MachineOperand *getNextOperandForReg(const MachineOperand *MO) {
122     assert(MO && MO->isReg() && "This is not a register operand!");
123     return MO->Contents.Reg.Next;
124   }
125 
126   /// UsedPhysRegMask - Additional used physregs including aliases.
127   /// This bit vector represents all the registers clobbered by function calls.
128   BitVector UsedPhysRegMask;
129 
130   /// ReservedRegs - This is a bit vector of reserved registers.  The target
131   /// may change its mind about which registers should be reserved.  This
132   /// vector is the frozen set of reserved registers when register allocation
133   /// started.
134   BitVector ReservedRegs;
135 
136   using VRegToTypeMap = IndexedMap<LLT, VirtReg2IndexFunctor>;
137   /// Map generic virtual registers to their low-level type.
138   VRegToTypeMap VRegToType;
139 
140   /// Keep track of the physical registers that are live in to the function.
141   /// Live in values are typically arguments in registers.  LiveIn values are
142   /// allowed to have virtual registers associated with them, stored in the
143   /// second element.
144   std::vector<std::pair<MCRegister, Register>> LiveIns;
145 
146 public:
147   explicit MachineRegisterInfo(MachineFunction *MF);
148   MachineRegisterInfo(const MachineRegisterInfo &) = delete;
149   MachineRegisterInfo &operator=(const MachineRegisterInfo &) = delete;
150 
151   const TargetRegisterInfo *getTargetRegisterInfo() const {
152     return MF->getSubtarget().getRegisterInfo();
153   }
154 
155   void resetDelegate(Delegate *delegate) {
156     // Ensure another delegate does not take over unless the current
157     // delegate first unattaches itself. If we ever need to multicast
158     // notifications, we will need to change to using a list.
159     assert(TheDelegate == delegate &&
160            "Only the current delegate can perform reset!");
161     TheDelegate = nullptr;
162   }
163 
164   void setDelegate(Delegate *delegate) {
165     assert(delegate && !TheDelegate &&
166            "Attempted to set delegate to null, or to change it without "
167            "first resetting it!");
168 
169     TheDelegate = delegate;
170   }
171 
172   //===--------------------------------------------------------------------===//
173   // Function State
174   //===--------------------------------------------------------------------===//
175 
176   // isSSA - Returns true when the machine function is in SSA form. Early
177   // passes require the machine function to be in SSA form where every virtual
178   // register has a single defining instruction.
179   //
180   // The TwoAddressInstructionPass and PHIElimination passes take the machine
181   // function out of SSA form when they introduce multiple defs per virtual
182   // register.
183   bool isSSA() const {
184     return MF->getProperties().hasProperty(
185         MachineFunctionProperties::Property::IsSSA);
186   }
187 
188   // leaveSSA - Indicates that the machine function is no longer in SSA form.
189   void leaveSSA() {
190     MF->getProperties().reset(MachineFunctionProperties::Property::IsSSA);
191   }
192 
193   /// tracksLiveness - Returns true when tracking register liveness accurately.
194   /// (see MachineFUnctionProperties::Property description for details)
195   bool tracksLiveness() const {
196     return MF->getProperties().hasProperty(
197         MachineFunctionProperties::Property::TracksLiveness);
198   }
199 
200   /// invalidateLiveness - Indicates that register liveness is no longer being
201   /// tracked accurately.
202   ///
203   /// This should be called by late passes that invalidate the liveness
204   /// information.
205   void invalidateLiveness() {
206     MF->getProperties().reset(
207         MachineFunctionProperties::Property::TracksLiveness);
208   }
209 
210   /// Returns true if liveness for register class @p RC should be tracked at
211   /// the subregister level.
212   bool shouldTrackSubRegLiveness(const TargetRegisterClass &RC) const {
213     return subRegLivenessEnabled() && RC.HasDisjunctSubRegs;
214   }
215   bool shouldTrackSubRegLiveness(Register VReg) const {
216     assert(VReg.isVirtual() && "Must pass a VReg");
217     return shouldTrackSubRegLiveness(*getRegClass(VReg));
218   }
219   bool subRegLivenessEnabled() const {
220     return TracksSubRegLiveness;
221   }
222 
223   //===--------------------------------------------------------------------===//
224   // Register Info
225   //===--------------------------------------------------------------------===//
226 
227   /// Returns true if the updated CSR list was initialized and false otherwise.
228   bool isUpdatedCSRsInitialized() const { return IsUpdatedCSRsInitialized; }
229 
230   /// Returns true if a register can be used as an argument to a function.
231   bool isArgumentRegister(const MachineFunction &MF, MCRegister Reg) const;
232 
233   /// Returns true if a register is a fixed register.
234   bool isFixedRegister(const MachineFunction &MF, MCRegister Reg) const;
235 
236   /// Returns true if a register is a general purpose register.
237   bool isGeneralPurposeRegister(const MachineFunction &MF,
238                                 MCRegister Reg) const;
239 
240   /// Disables the register from the list of CSRs.
241   /// I.e. the register will not appear as part of the CSR mask.
242   /// \see UpdatedCalleeSavedRegs.
243   void disableCalleeSavedRegister(MCRegister Reg);
244 
245   /// Returns list of callee saved registers.
246   /// The function returns the updated CSR list (after taking into account
247   /// registers that are disabled from the CSR list).
248   const MCPhysReg *getCalleeSavedRegs() const;
249 
250   /// Sets the updated Callee Saved Registers list.
251   /// Notice that it will override ant previously disabled/saved CSRs.
252   void setCalleeSavedRegs(ArrayRef<MCPhysReg> CSRs);
253 
254   // Strictly for use by MachineInstr.cpp.
255   void addRegOperandToUseList(MachineOperand *MO);
256 
257   // Strictly for use by MachineInstr.cpp.
258   void removeRegOperandFromUseList(MachineOperand *MO);
259 
260   // Strictly for use by MachineInstr.cpp.
261   void moveOperands(MachineOperand *Dst, MachineOperand *Src, unsigned NumOps);
262 
263   /// Verify the sanity of the use list for Reg.
264   void verifyUseList(Register Reg) const;
265 
266   /// Verify the use list of all registers.
267   void verifyUseLists() const;
268 
269   /// reg_begin/reg_end - Provide iteration support to walk over all definitions
270   /// and uses of a register within the MachineFunction that corresponds to this
271   /// MachineRegisterInfo object.
272   template<bool Uses, bool Defs, bool SkipDebug,
273            bool ByOperand, bool ByInstr, bool ByBundle>
274   class defusechain_iterator;
275   template<bool Uses, bool Defs, bool SkipDebug,
276            bool ByOperand, bool ByInstr, bool ByBundle>
277   class defusechain_instr_iterator;
278 
279   // Make it a friend so it can access getNextOperandForReg().
280   template<bool, bool, bool, bool, bool, bool>
281     friend class defusechain_iterator;
282   template<bool, bool, bool, bool, bool, bool>
283     friend class defusechain_instr_iterator;
284 
285   /// reg_iterator/reg_begin/reg_end - Walk all defs and uses of the specified
286   /// register.
287   using reg_iterator =
288       defusechain_iterator<true, true, false, true, false, false>;
289   reg_iterator reg_begin(Register RegNo) const {
290     return reg_iterator(getRegUseDefListHead(RegNo));
291   }
292   static reg_iterator reg_end() { return reg_iterator(nullptr); }
293 
294   inline iterator_range<reg_iterator> reg_operands(Register Reg) const {
295     return make_range(reg_begin(Reg), reg_end());
296   }
297 
298   /// reg_instr_iterator/reg_instr_begin/reg_instr_end - Walk all defs and uses
299   /// of the specified register, stepping by MachineInstr.
300   using reg_instr_iterator =
301       defusechain_instr_iterator<true, true, false, false, true, false>;
302   reg_instr_iterator reg_instr_begin(Register RegNo) const {
303     return reg_instr_iterator(getRegUseDefListHead(RegNo));
304   }
305   static reg_instr_iterator reg_instr_end() {
306     return reg_instr_iterator(nullptr);
307   }
308 
309   inline iterator_range<reg_instr_iterator>
310   reg_instructions(Register Reg) const {
311     return make_range(reg_instr_begin(Reg), reg_instr_end());
312   }
313 
314   /// reg_bundle_iterator/reg_bundle_begin/reg_bundle_end - Walk all defs and uses
315   /// of the specified register, stepping by bundle.
316   using reg_bundle_iterator =
317       defusechain_instr_iterator<true, true, false, false, false, true>;
318   reg_bundle_iterator reg_bundle_begin(Register RegNo) const {
319     return reg_bundle_iterator(getRegUseDefListHead(RegNo));
320   }
321   static reg_bundle_iterator reg_bundle_end() {
322     return reg_bundle_iterator(nullptr);
323   }
324 
325   inline iterator_range<reg_bundle_iterator> reg_bundles(Register Reg) const {
326     return make_range(reg_bundle_begin(Reg), reg_bundle_end());
327   }
328 
329   /// reg_empty - Return true if there are no instructions using or defining the
330   /// specified register (it may be live-in).
331   bool reg_empty(Register RegNo) const { return reg_begin(RegNo) == reg_end(); }
332 
333   /// reg_nodbg_iterator/reg_nodbg_begin/reg_nodbg_end - Walk all defs and uses
334   /// of the specified register, skipping those marked as Debug.
335   using reg_nodbg_iterator =
336       defusechain_iterator<true, true, true, true, false, false>;
337   reg_nodbg_iterator reg_nodbg_begin(Register RegNo) const {
338     return reg_nodbg_iterator(getRegUseDefListHead(RegNo));
339   }
340   static reg_nodbg_iterator reg_nodbg_end() {
341     return reg_nodbg_iterator(nullptr);
342   }
343 
344   inline iterator_range<reg_nodbg_iterator>
345   reg_nodbg_operands(Register Reg) const {
346     return make_range(reg_nodbg_begin(Reg), reg_nodbg_end());
347   }
348 
349   /// reg_instr_nodbg_iterator/reg_instr_nodbg_begin/reg_instr_nodbg_end - Walk
350   /// all defs and uses of the specified register, stepping by MachineInstr,
351   /// skipping those marked as Debug.
352   using reg_instr_nodbg_iterator =
353       defusechain_instr_iterator<true, true, true, false, true, false>;
354   reg_instr_nodbg_iterator reg_instr_nodbg_begin(Register RegNo) const {
355     return reg_instr_nodbg_iterator(getRegUseDefListHead(RegNo));
356   }
357   static reg_instr_nodbg_iterator reg_instr_nodbg_end() {
358     return reg_instr_nodbg_iterator(nullptr);
359   }
360 
361   inline iterator_range<reg_instr_nodbg_iterator>
362   reg_nodbg_instructions(Register Reg) const {
363     return make_range(reg_instr_nodbg_begin(Reg), reg_instr_nodbg_end());
364   }
365 
366   /// reg_bundle_nodbg_iterator/reg_bundle_nodbg_begin/reg_bundle_nodbg_end - Walk
367   /// all defs and uses of the specified register, stepping by bundle,
368   /// skipping those marked as Debug.
369   using reg_bundle_nodbg_iterator =
370       defusechain_instr_iterator<true, true, true, false, false, true>;
371   reg_bundle_nodbg_iterator reg_bundle_nodbg_begin(Register RegNo) const {
372     return reg_bundle_nodbg_iterator(getRegUseDefListHead(RegNo));
373   }
374   static reg_bundle_nodbg_iterator reg_bundle_nodbg_end() {
375     return reg_bundle_nodbg_iterator(nullptr);
376   }
377 
378   inline iterator_range<reg_bundle_nodbg_iterator>
379   reg_nodbg_bundles(Register Reg) const {
380     return make_range(reg_bundle_nodbg_begin(Reg), reg_bundle_nodbg_end());
381   }
382 
383   /// reg_nodbg_empty - Return true if the only instructions using or defining
384   /// Reg are Debug instructions.
385   bool reg_nodbg_empty(Register RegNo) const {
386     return reg_nodbg_begin(RegNo) == reg_nodbg_end();
387   }
388 
389   /// def_iterator/def_begin/def_end - Walk all defs of the specified register.
390   using def_iterator =
391       defusechain_iterator<false, true, false, true, false, false>;
392   def_iterator def_begin(Register RegNo) const {
393     return def_iterator(getRegUseDefListHead(RegNo));
394   }
395   static def_iterator def_end() { return def_iterator(nullptr); }
396 
397   inline iterator_range<def_iterator> def_operands(Register Reg) const {
398     return make_range(def_begin(Reg), def_end());
399   }
400 
401   /// def_instr_iterator/def_instr_begin/def_instr_end - Walk all defs of the
402   /// specified register, stepping by MachineInst.
403   using def_instr_iterator =
404       defusechain_instr_iterator<false, true, false, false, true, false>;
405   def_instr_iterator def_instr_begin(Register RegNo) const {
406     return def_instr_iterator(getRegUseDefListHead(RegNo));
407   }
408   static def_instr_iterator def_instr_end() {
409     return def_instr_iterator(nullptr);
410   }
411 
412   inline iterator_range<def_instr_iterator>
413   def_instructions(Register Reg) const {
414     return make_range(def_instr_begin(Reg), def_instr_end());
415   }
416 
417   /// def_bundle_iterator/def_bundle_begin/def_bundle_end - Walk all defs of the
418   /// specified register, stepping by bundle.
419   using def_bundle_iterator =
420       defusechain_instr_iterator<false, true, false, false, false, true>;
421   def_bundle_iterator def_bundle_begin(Register RegNo) const {
422     return def_bundle_iterator(getRegUseDefListHead(RegNo));
423   }
424   static def_bundle_iterator def_bundle_end() {
425     return def_bundle_iterator(nullptr);
426   }
427 
428   inline iterator_range<def_bundle_iterator> def_bundles(Register Reg) const {
429     return make_range(def_bundle_begin(Reg), def_bundle_end());
430   }
431 
432   /// def_empty - Return true if there are no instructions defining the
433   /// specified register (it may be live-in).
434   bool def_empty(Register RegNo) const { return def_begin(RegNo) == def_end(); }
435 
436   StringRef getVRegName(Register Reg) const {
437     return VReg2Name.inBounds(Reg) ? StringRef(VReg2Name[Reg]) : "";
438   }
439 
440   void insertVRegByName(StringRef Name, Register Reg) {
441     assert((Name.empty() || VRegNames.find(Name) == VRegNames.end()) &&
442            "Named VRegs Must be Unique.");
443     if (!Name.empty()) {
444       VRegNames.insert(Name);
445       VReg2Name.grow(Reg);
446       VReg2Name[Reg] = Name.str();
447     }
448   }
449 
450   /// Return true if there is exactly one operand defining the specified
451   /// register.
452   bool hasOneDef(Register RegNo) const {
453     return hasSingleElement(def_operands(RegNo));
454   }
455 
456   /// Returns the defining operand if there is exactly one operand defining the
457   /// specified register, otherwise nullptr.
458   MachineOperand *getOneDef(Register Reg) const {
459     def_iterator DI = def_begin(Reg);
460     if (DI == def_end()) // No defs.
461       return nullptr;
462 
463     def_iterator OneDef = DI;
464     if (++DI == def_end())
465       return &*OneDef;
466     return nullptr; // Multiple defs.
467   }
468 
469   /// use_iterator/use_begin/use_end - Walk all uses of the specified register.
470   using use_iterator =
471       defusechain_iterator<true, false, false, true, false, false>;
472   use_iterator use_begin(Register RegNo) const {
473     return use_iterator(getRegUseDefListHead(RegNo));
474   }
475   static use_iterator use_end() { return use_iterator(nullptr); }
476 
477   inline iterator_range<use_iterator> use_operands(Register Reg) const {
478     return make_range(use_begin(Reg), use_end());
479   }
480 
481   /// use_instr_iterator/use_instr_begin/use_instr_end - Walk all uses of the
482   /// specified register, stepping by MachineInstr.
483   using use_instr_iterator =
484       defusechain_instr_iterator<true, false, false, false, true, false>;
485   use_instr_iterator use_instr_begin(Register RegNo) const {
486     return use_instr_iterator(getRegUseDefListHead(RegNo));
487   }
488   static use_instr_iterator use_instr_end() {
489     return use_instr_iterator(nullptr);
490   }
491 
492   inline iterator_range<use_instr_iterator>
493   use_instructions(Register Reg) const {
494     return make_range(use_instr_begin(Reg), use_instr_end());
495   }
496 
497   /// use_bundle_iterator/use_bundle_begin/use_bundle_end - Walk all uses of the
498   /// specified register, stepping by bundle.
499   using use_bundle_iterator =
500       defusechain_instr_iterator<true, false, false, false, false, true>;
501   use_bundle_iterator use_bundle_begin(Register RegNo) const {
502     return use_bundle_iterator(getRegUseDefListHead(RegNo));
503   }
504   static use_bundle_iterator use_bundle_end() {
505     return use_bundle_iterator(nullptr);
506   }
507 
508   inline iterator_range<use_bundle_iterator> use_bundles(Register Reg) const {
509     return make_range(use_bundle_begin(Reg), use_bundle_end());
510   }
511 
512   /// use_empty - Return true if there are no instructions using the specified
513   /// register.
514   bool use_empty(Register RegNo) const { return use_begin(RegNo) == use_end(); }
515 
516   /// hasOneUse - Return true if there is exactly one instruction using the
517   /// specified register.
518   bool hasOneUse(Register RegNo) const {
519     return hasSingleElement(use_operands(RegNo));
520   }
521 
522   /// use_nodbg_iterator/use_nodbg_begin/use_nodbg_end - Walk all uses of the
523   /// specified register, skipping those marked as Debug.
524   using use_nodbg_iterator =
525       defusechain_iterator<true, false, true, true, false, false>;
526   use_nodbg_iterator use_nodbg_begin(Register RegNo) const {
527     return use_nodbg_iterator(getRegUseDefListHead(RegNo));
528   }
529   static use_nodbg_iterator use_nodbg_end() {
530     return use_nodbg_iterator(nullptr);
531   }
532 
533   inline iterator_range<use_nodbg_iterator>
534   use_nodbg_operands(Register Reg) const {
535     return make_range(use_nodbg_begin(Reg), use_nodbg_end());
536   }
537 
538   /// use_instr_nodbg_iterator/use_instr_nodbg_begin/use_instr_nodbg_end - Walk
539   /// all uses of the specified register, stepping by MachineInstr, skipping
540   /// those marked as Debug.
541   using use_instr_nodbg_iterator =
542       defusechain_instr_iterator<true, false, true, false, true, false>;
543   use_instr_nodbg_iterator use_instr_nodbg_begin(Register RegNo) const {
544     return use_instr_nodbg_iterator(getRegUseDefListHead(RegNo));
545   }
546   static use_instr_nodbg_iterator use_instr_nodbg_end() {
547     return use_instr_nodbg_iterator(nullptr);
548   }
549 
550   inline iterator_range<use_instr_nodbg_iterator>
551   use_nodbg_instructions(Register Reg) const {
552     return make_range(use_instr_nodbg_begin(Reg), use_instr_nodbg_end());
553   }
554 
555   /// use_bundle_nodbg_iterator/use_bundle_nodbg_begin/use_bundle_nodbg_end - Walk
556   /// all uses of the specified register, stepping by bundle, skipping
557   /// those marked as Debug.
558   using use_bundle_nodbg_iterator =
559       defusechain_instr_iterator<true, false, true, false, false, true>;
560   use_bundle_nodbg_iterator use_bundle_nodbg_begin(Register RegNo) const {
561     return use_bundle_nodbg_iterator(getRegUseDefListHead(RegNo));
562   }
563   static use_bundle_nodbg_iterator use_bundle_nodbg_end() {
564     return use_bundle_nodbg_iterator(nullptr);
565   }
566 
567   inline iterator_range<use_bundle_nodbg_iterator>
568   use_nodbg_bundles(Register Reg) const {
569     return make_range(use_bundle_nodbg_begin(Reg), use_bundle_nodbg_end());
570   }
571 
572   /// use_nodbg_empty - Return true if there are no non-Debug instructions
573   /// using the specified register.
574   bool use_nodbg_empty(Register RegNo) const {
575     return use_nodbg_begin(RegNo) == use_nodbg_end();
576   }
577 
578   /// hasOneNonDBGUse - Return true if there is exactly one non-Debug
579   /// use of the specified register.
580   bool hasOneNonDBGUse(Register RegNo) const;
581 
582   /// hasOneNonDBGUse - Return true if there is exactly one non-Debug
583   /// instruction using the specified register. Said instruction may have
584   /// multiple uses.
585   bool hasOneNonDBGUser(Register RegNo) const;
586 
587   /// replaceRegWith - Replace all instances of FromReg with ToReg in the
588   /// machine function.  This is like llvm-level X->replaceAllUsesWith(Y),
589   /// except that it also changes any definitions of the register as well.
590   ///
591   /// Note that it is usually necessary to first constrain ToReg's register
592   /// class and register bank to match the FromReg constraints using one of the
593   /// methods:
594   ///
595   ///   constrainRegClass(ToReg, getRegClass(FromReg))
596   ///   constrainRegAttrs(ToReg, FromReg)
597   ///   RegisterBankInfo::constrainGenericRegister(ToReg,
598   ///       *MRI.getRegClass(FromReg), MRI)
599   ///
600   /// These functions will return a falsy result if the virtual registers have
601   /// incompatible constraints.
602   ///
603   /// Note that if ToReg is a physical register the function will replace and
604   /// apply sub registers to ToReg in order to obtain a final/proper physical
605   /// register.
606   void replaceRegWith(Register FromReg, Register ToReg);
607 
608   /// getVRegDef - Return the machine instr that defines the specified virtual
609   /// register or null if none is found.  This assumes that the code is in SSA
610   /// form, so there should only be one definition.
611   MachineInstr *getVRegDef(Register Reg) const;
612 
613   /// getUniqueVRegDef - Return the unique machine instr that defines the
614   /// specified virtual register or null if none is found.  If there are
615   /// multiple definitions or no definition, return null.
616   MachineInstr *getUniqueVRegDef(Register Reg) const;
617 
618   /// clearKillFlags - Iterate over all the uses of the given register and
619   /// clear the kill flag from the MachineOperand. This function is used by
620   /// optimization passes which extend register lifetimes and need only
621   /// preserve conservative kill flag information.
622   void clearKillFlags(Register Reg) const;
623 
624   void dumpUses(Register RegNo) const;
625 
626   /// Returns true if PhysReg is unallocatable and constant throughout the
627   /// function. Writing to a constant register has no effect.
628   bool isConstantPhysReg(MCRegister PhysReg) const;
629 
630   /// Get an iterator over the pressure sets affected by the given physical or
631   /// virtual register. If RegUnit is physical, it must be a register unit (from
632   /// MCRegUnitIterator).
633   PSetIterator getPressureSets(Register RegUnit) const;
634 
635   //===--------------------------------------------------------------------===//
636   // Virtual Register Info
637   //===--------------------------------------------------------------------===//
638 
639   /// Return the register class of the specified virtual register.
640   /// This shouldn't be used directly unless \p Reg has a register class.
641   /// \see getRegClassOrNull when this might happen.
642   const TargetRegisterClass *getRegClass(Register Reg) const {
643     assert(VRegInfo[Reg.id()].first.is<const TargetRegisterClass *>() &&
644            "Register class not set, wrong accessor");
645     return VRegInfo[Reg.id()].first.get<const TargetRegisterClass *>();
646   }
647 
648   /// Return the register class of \p Reg, or null if Reg has not been assigned
649   /// a register class yet.
650   ///
651   /// \note A null register class can only happen when these two
652   /// conditions are met:
653   /// 1. Generic virtual registers are created.
654   /// 2. The machine function has not completely been through the
655   ///    instruction selection process.
656   /// None of this condition is possible without GlobalISel for now.
657   /// In other words, if GlobalISel is not used or if the query happens after
658   /// the select pass, using getRegClass is safe.
659   const TargetRegisterClass *getRegClassOrNull(Register Reg) const {
660     const RegClassOrRegBank &Val = VRegInfo[Reg].first;
661     return Val.dyn_cast<const TargetRegisterClass *>();
662   }
663 
664   /// Return the register bank of \p Reg, or null if Reg has not been assigned
665   /// a register bank or has been assigned a register class.
666   /// \note It is possible to get the register bank from the register class via
667   /// RegisterBankInfo::getRegBankFromRegClass.
668   const RegisterBank *getRegBankOrNull(Register Reg) const {
669     const RegClassOrRegBank &Val = VRegInfo[Reg].first;
670     return Val.dyn_cast<const RegisterBank *>();
671   }
672 
673   /// Return the register bank or register class of \p Reg.
674   /// \note Before the register bank gets assigned (i.e., before the
675   /// RegBankSelect pass) \p Reg may not have either.
676   const RegClassOrRegBank &getRegClassOrRegBank(Register Reg) const {
677     return VRegInfo[Reg].first;
678   }
679 
680   /// setRegClass - Set the register class of the specified virtual register.
681   void setRegClass(Register Reg, const TargetRegisterClass *RC);
682 
683   /// Set the register bank to \p RegBank for \p Reg.
684   void setRegBank(Register Reg, const RegisterBank &RegBank);
685 
686   void setRegClassOrRegBank(Register Reg,
687                             const RegClassOrRegBank &RCOrRB){
688     VRegInfo[Reg].first = RCOrRB;
689   }
690 
691   /// constrainRegClass - Constrain the register class of the specified virtual
692   /// register to be a common subclass of RC and the current register class,
693   /// but only if the new class has at least MinNumRegs registers.  Return the
694   /// new register class, or NULL if no such class exists.
695   /// This should only be used when the constraint is known to be trivial, like
696   /// GR32 -> GR32_NOSP. Beware of increasing register pressure.
697   ///
698   /// \note Assumes that the register has a register class assigned.
699   /// Use RegisterBankInfo::constrainGenericRegister in GlobalISel's
700   /// InstructionSelect pass and constrainRegAttrs in every other pass,
701   /// including non-select passes of GlobalISel, instead.
702   const TargetRegisterClass *constrainRegClass(Register Reg,
703                                                const TargetRegisterClass *RC,
704                                                unsigned MinNumRegs = 0);
705 
706   /// Constrain the register class or the register bank of the virtual register
707   /// \p Reg (and low-level type) to be a common subclass or a common bank of
708   /// both registers provided respectively (and a common low-level type). Do
709   /// nothing if any of the attributes (classes, banks, or low-level types) of
710   /// the registers are deemed incompatible, or if the resulting register will
711   /// have a class smaller than before and of size less than \p MinNumRegs.
712   /// Return true if such register attributes exist, false otherwise.
713   ///
714   /// \note Use this method instead of constrainRegClass and
715   /// RegisterBankInfo::constrainGenericRegister everywhere but SelectionDAG
716   /// ISel / FastISel and GlobalISel's InstructionSelect pass respectively.
717   bool constrainRegAttrs(Register Reg, Register ConstrainingReg,
718                          unsigned MinNumRegs = 0);
719 
720   /// recomputeRegClass - Try to find a legal super-class of Reg's register
721   /// class that still satisfies the constraints from the instructions using
722   /// Reg.  Returns true if Reg was upgraded.
723   ///
724   /// This method can be used after constraints have been removed from a
725   /// virtual register, for example after removing instructions or splitting
726   /// the live range.
727   bool recomputeRegClass(Register Reg);
728 
729   /// createVirtualRegister - Create and return a new virtual register in the
730   /// function with the specified register class.
731   Register createVirtualRegister(const TargetRegisterClass *RegClass,
732                                  StringRef Name = "");
733 
734   /// Create and return a new virtual register in the function with the same
735   /// attributes as the given register.
736   Register cloneVirtualRegister(Register VReg, StringRef Name = "");
737 
738   /// Get the low-level type of \p Reg or LLT{} if Reg is not a generic
739   /// (target independent) virtual register.
740   LLT getType(Register Reg) const {
741     if (Register::isVirtualRegister(Reg) && VRegToType.inBounds(Reg))
742       return VRegToType[Reg];
743     return LLT{};
744   }
745 
746   /// Set the low-level type of \p VReg to \p Ty.
747   void setType(Register VReg, LLT Ty);
748 
749   /// Create and return a new generic virtual register with low-level
750   /// type \p Ty.
751   Register createGenericVirtualRegister(LLT Ty, StringRef Name = "");
752 
753   /// Remove all types associated to virtual registers (after instruction
754   /// selection and constraining of all generic virtual registers).
755   void clearVirtRegTypes();
756 
757   /// Creates a new virtual register that has no register class, register bank
758   /// or size assigned yet. This is only allowed to be used
759   /// temporarily while constructing machine instructions. Most operations are
760   /// undefined on an incomplete register until one of setRegClass(),
761   /// setRegBank() or setSize() has been called on it.
762   Register createIncompleteVirtualRegister(StringRef Name = "");
763 
764   /// getNumVirtRegs - Return the number of virtual registers created.
765   unsigned getNumVirtRegs() const { return VRegInfo.size(); }
766 
767   /// clearVirtRegs - Remove all virtual registers (after physreg assignment).
768   void clearVirtRegs();
769 
770   /// setRegAllocationHint - Specify a register allocation hint for the
771   /// specified virtual register. This is typically used by target, and in case
772   /// of an earlier hint it will be overwritten.
773   void setRegAllocationHint(Register VReg, unsigned Type, Register PrefReg) {
774     assert(VReg.isVirtual());
775     RegAllocHints[VReg].first  = Type;
776     RegAllocHints[VReg].second.clear();
777     RegAllocHints[VReg].second.push_back(PrefReg);
778   }
779 
780   /// addRegAllocationHint - Add a register allocation hint to the hints
781   /// vector for VReg.
782   void addRegAllocationHint(Register VReg, Register PrefReg) {
783     assert(Register::isVirtualRegister(VReg));
784     RegAllocHints[VReg].second.push_back(PrefReg);
785   }
786 
787   /// Specify the preferred (target independent) register allocation hint for
788   /// the specified virtual register.
789   void setSimpleHint(Register VReg, Register PrefReg) {
790     setRegAllocationHint(VReg, /*Type=*/0, PrefReg);
791   }
792 
793   void clearSimpleHint(Register VReg) {
794     assert (!RegAllocHints[VReg].first &&
795             "Expected to clear a non-target hint!");
796     RegAllocHints[VReg].second.clear();
797   }
798 
799   /// getRegAllocationHint - Return the register allocation hint for the
800   /// specified virtual register. If there are many hints, this returns the
801   /// one with the greatest weight.
802   std::pair<Register, Register>
803   getRegAllocationHint(Register VReg) const {
804     assert(VReg.isVirtual());
805     Register BestHint = (RegAllocHints[VReg.id()].second.size() ?
806                          RegAllocHints[VReg.id()].second[0] : Register());
807     return std::pair<Register, Register>(RegAllocHints[VReg.id()].first,
808                                          BestHint);
809   }
810 
811   /// getSimpleHint - same as getRegAllocationHint except it will only return
812   /// a target independent hint.
813   Register getSimpleHint(Register VReg) const {
814     assert(VReg.isVirtual());
815     std::pair<Register, Register> Hint = getRegAllocationHint(VReg);
816     return Hint.first ? Register() : Hint.second;
817   }
818 
819   /// getRegAllocationHints - Return a reference to the vector of all
820   /// register allocation hints for VReg.
821   const std::pair<Register, SmallVector<Register, 4>>
822   &getRegAllocationHints(Register VReg) const {
823     assert(VReg.isVirtual());
824     return RegAllocHints[VReg];
825   }
826 
827   /// markUsesInDebugValueAsUndef - Mark every DBG_VALUE referencing the
828   /// specified register as undefined which causes the DBG_VALUE to be
829   /// deleted during LiveDebugVariables analysis.
830   void markUsesInDebugValueAsUndef(Register Reg) const;
831 
832   /// updateDbgUsersToReg - Update a collection of debug instructions
833   /// to refer to the designated register.
834   void updateDbgUsersToReg(MCRegister OldReg, MCRegister NewReg,
835                            ArrayRef<MachineInstr *> Users) const {
836     // If this operand is a register, check whether it overlaps with OldReg.
837     // If it does, replace with NewReg.
838     auto UpdateOp = [this, &NewReg, &OldReg](MachineOperand &Op) {
839       if (Op.isReg() &&
840           getTargetRegisterInfo()->regsOverlap(Op.getReg(), OldReg))
841         Op.setReg(NewReg);
842     };
843 
844     // Iterate through (possibly several) operands to DBG_VALUEs and update
845     // each. For DBG_PHIs, only one operand will be present.
846     for (MachineInstr *MI : Users) {
847       if (MI->isDebugValue()) {
848         for (auto &Op : MI->debug_operands())
849           UpdateOp(Op);
850         assert(MI->hasDebugOperandForReg(NewReg) &&
851                "Expected debug value to have some overlap with OldReg");
852       } else if (MI->isDebugPHI()) {
853         UpdateOp(MI->getOperand(0));
854       } else {
855         llvm_unreachable("Non-DBG_VALUE, Non-DBG_PHI debug instr updated");
856       }
857     }
858   }
859 
860   /// Return true if the specified register is modified in this function.
861   /// This checks that no defining machine operands exist for the register or
862   /// any of its aliases. Definitions found on functions marked noreturn are
863   /// ignored, to consider them pass 'true' for optional parameter
864   /// SkipNoReturnDef. The register is also considered modified when it is set
865   /// in the UsedPhysRegMask.
866   bool isPhysRegModified(MCRegister PhysReg, bool SkipNoReturnDef = false) const;
867 
868   /// Return true if the specified register is modified or read in this
869   /// function. This checks that no machine operands exist for the register or
870   /// any of its aliases. If SkipRegMaskTest is false, the register is
871   /// considered used when it is set in the UsedPhysRegMask.
872   bool isPhysRegUsed(MCRegister PhysReg, bool SkipRegMaskTest = false) const;
873 
874   /// addPhysRegsUsedFromRegMask - Mark any registers not in RegMask as used.
875   /// This corresponds to the bit mask attached to register mask operands.
876   void addPhysRegsUsedFromRegMask(const uint32_t *RegMask) {
877     UsedPhysRegMask.setBitsNotInMask(RegMask);
878   }
879 
880   const BitVector &getUsedPhysRegsMask() const { return UsedPhysRegMask; }
881 
882   //===--------------------------------------------------------------------===//
883   // Reserved Register Info
884   //===--------------------------------------------------------------------===//
885   //
886   // The set of reserved registers must be invariant during register
887   // allocation.  For example, the target cannot suddenly decide it needs a
888   // frame pointer when the register allocator has already used the frame
889   // pointer register for something else.
890   //
891   // These methods can be used by target hooks like hasFP() to avoid changing
892   // the reserved register set during register allocation.
893 
894   /// freezeReservedRegs - Called by the register allocator to freeze the set
895   /// of reserved registers before allocation begins.
896   void freezeReservedRegs(const MachineFunction&);
897 
898   /// reservedRegsFrozen - Returns true after freezeReservedRegs() was called
899   /// to ensure the set of reserved registers stays constant.
900   bool reservedRegsFrozen() const {
901     return !ReservedRegs.empty();
902   }
903 
904   /// canReserveReg - Returns true if PhysReg can be used as a reserved
905   /// register.  Any register can be reserved before freezeReservedRegs() is
906   /// called.
907   bool canReserveReg(MCRegister PhysReg) const {
908     return !reservedRegsFrozen() || ReservedRegs.test(PhysReg);
909   }
910 
911   /// getReservedRegs - Returns a reference to the frozen set of reserved
912   /// registers. This method should always be preferred to calling
913   /// TRI::getReservedRegs() when possible.
914   const BitVector &getReservedRegs() const {
915     assert(reservedRegsFrozen() &&
916            "Reserved registers haven't been frozen yet. "
917            "Use TRI::getReservedRegs().");
918     return ReservedRegs;
919   }
920 
921   /// isReserved - Returns true when PhysReg is a reserved register.
922   ///
923   /// Reserved registers may belong to an allocatable register class, but the
924   /// target has explicitly requested that they are not used.
925   bool isReserved(MCRegister PhysReg) const {
926     return getReservedRegs().test(PhysReg.id());
927   }
928 
929   /// Returns true when the given register unit is considered reserved.
930   ///
931   /// Register units are considered reserved when for at least one of their
932   /// root registers, the root register and all super registers are reserved.
933   /// This currently iterates the register hierarchy and may be slower than
934   /// expected.
935   bool isReservedRegUnit(unsigned Unit) const;
936 
937   /// isAllocatable - Returns true when PhysReg belongs to an allocatable
938   /// register class and it hasn't been reserved.
939   ///
940   /// Allocatable registers may show up in the allocation order of some virtual
941   /// register, so a register allocator needs to track its liveness and
942   /// availability.
943   bool isAllocatable(MCRegister PhysReg) const {
944     return getTargetRegisterInfo()->isInAllocatableClass(PhysReg) &&
945       !isReserved(PhysReg);
946   }
947 
948   //===--------------------------------------------------------------------===//
949   // LiveIn Management
950   //===--------------------------------------------------------------------===//
951 
952   /// addLiveIn - Add the specified register as a live-in.  Note that it
953   /// is an error to add the same register to the same set more than once.
954   void addLiveIn(MCRegister Reg, Register vreg = Register()) {
955     LiveIns.push_back(std::make_pair(Reg, vreg));
956   }
957 
958   // Iteration support for the live-ins set.  It's kept in sorted order
959   // by register number.
960   using livein_iterator =
961       std::vector<std::pair<MCRegister,Register>>::const_iterator;
962   livein_iterator livein_begin() const { return LiveIns.begin(); }
963   livein_iterator livein_end()   const { return LiveIns.end(); }
964   bool            livein_empty() const { return LiveIns.empty(); }
965 
966   ArrayRef<std::pair<MCRegister, Register>> liveins() const {
967     return LiveIns;
968   }
969 
970   bool isLiveIn(Register Reg) const;
971 
972   /// getLiveInPhysReg - If VReg is a live-in virtual register, return the
973   /// corresponding live-in physical register.
974   MCRegister getLiveInPhysReg(Register VReg) const;
975 
976   /// getLiveInVirtReg - If PReg is a live-in physical register, return the
977   /// corresponding live-in virtual register.
978   Register getLiveInVirtReg(MCRegister PReg) const;
979 
980   /// EmitLiveInCopies - Emit copies to initialize livein virtual registers
981   /// into the given entry block.
982   void EmitLiveInCopies(MachineBasicBlock *EntryMBB,
983                         const TargetRegisterInfo &TRI,
984                         const TargetInstrInfo &TII);
985 
986   /// Returns a mask covering all bits that can appear in lane masks of
987   /// subregisters of the virtual register @p Reg.
988   LaneBitmask getMaxLaneMaskForVReg(Register Reg) const;
989 
990   /// defusechain_iterator - This class provides iterator support for machine
991   /// operands in the function that use or define a specific register.  If
992   /// ReturnUses is true it returns uses of registers, if ReturnDefs is true it
993   /// returns defs.  If neither are true then you are silly and it always
994   /// returns end().  If SkipDebug is true it skips uses marked Debug
995   /// when incrementing.
996   template <bool ReturnUses, bool ReturnDefs, bool SkipDebug, bool ByOperand,
997             bool ByInstr, bool ByBundle>
998   class defusechain_iterator {
999     friend class MachineRegisterInfo;
1000 
1001   public:
1002     using iterator_category = std::forward_iterator_tag;
1003     using value_type = MachineOperand;
1004     using difference_type = std::ptrdiff_t;
1005     using pointer = value_type *;
1006     using reference = value_type &;
1007 
1008   private:
1009     MachineOperand *Op = nullptr;
1010 
1011     explicit defusechain_iterator(MachineOperand *op) : Op(op) {
1012       // If the first node isn't one we're interested in, advance to one that
1013       // we are interested in.
1014       if (op) {
1015         if ((!ReturnUses && op->isUse()) ||
1016             (!ReturnDefs && op->isDef()) ||
1017             (SkipDebug && op->isDebug()))
1018           advance();
1019       }
1020     }
1021 
1022     void advance() {
1023       assert(Op && "Cannot increment end iterator!");
1024       Op = getNextOperandForReg(Op);
1025 
1026       // All defs come before the uses, so stop def_iterator early.
1027       if (!ReturnUses) {
1028         if (Op) {
1029           if (Op->isUse())
1030             Op = nullptr;
1031           else
1032             assert(!Op->isDebug() && "Can't have debug defs");
1033         }
1034       } else {
1035         // If this is an operand we don't care about, skip it.
1036         while (Op && ((!ReturnDefs && Op->isDef()) ||
1037                       (SkipDebug && Op->isDebug())))
1038           Op = getNextOperandForReg(Op);
1039       }
1040     }
1041 
1042   public:
1043     defusechain_iterator() = default;
1044 
1045     bool operator==(const defusechain_iterator &x) const {
1046       return Op == x.Op;
1047     }
1048     bool operator!=(const defusechain_iterator &x) const {
1049       return !operator==(x);
1050     }
1051 
1052     /// atEnd - return true if this iterator is equal to reg_end() on the value.
1053     bool atEnd() const { return Op == nullptr; }
1054 
1055     // Iterator traversal: forward iteration only
1056     defusechain_iterator &operator++() {          // Preincrement
1057       assert(Op && "Cannot increment end iterator!");
1058       if (ByOperand)
1059         advance();
1060       else if (ByInstr) {
1061         MachineInstr *P = Op->getParent();
1062         do {
1063           advance();
1064         } while (Op && Op->getParent() == P);
1065       } else if (ByBundle) {
1066         MachineBasicBlock::instr_iterator P =
1067             getBundleStart(Op->getParent()->getIterator());
1068         do {
1069           advance();
1070         } while (Op && getBundleStart(Op->getParent()->getIterator()) == P);
1071       }
1072 
1073       return *this;
1074     }
1075     defusechain_iterator operator++(int) {        // Postincrement
1076       defusechain_iterator tmp = *this; ++*this; return tmp;
1077     }
1078 
1079     /// getOperandNo - Return the operand # of this MachineOperand in its
1080     /// MachineInstr.
1081     unsigned getOperandNo() const {
1082       assert(Op && "Cannot dereference end iterator!");
1083       return Op - &Op->getParent()->getOperand(0);
1084     }
1085 
1086     // Retrieve a reference to the current operand.
1087     MachineOperand &operator*() const {
1088       assert(Op && "Cannot dereference end iterator!");
1089       return *Op;
1090     }
1091 
1092     MachineOperand *operator->() const {
1093       assert(Op && "Cannot dereference end iterator!");
1094       return Op;
1095     }
1096   };
1097 
1098   /// defusechain_iterator - This class provides iterator support for machine
1099   /// operands in the function that use or define a specific register.  If
1100   /// ReturnUses is true it returns uses of registers, if ReturnDefs is true it
1101   /// returns defs.  If neither are true then you are silly and it always
1102   /// returns end().  If SkipDebug is true it skips uses marked Debug
1103   /// when incrementing.
1104   template <bool ReturnUses, bool ReturnDefs, bool SkipDebug, bool ByOperand,
1105             bool ByInstr, bool ByBundle>
1106   class defusechain_instr_iterator {
1107     friend class MachineRegisterInfo;
1108 
1109   public:
1110     using iterator_category = std::forward_iterator_tag;
1111     using value_type = MachineInstr;
1112     using difference_type = std::ptrdiff_t;
1113     using pointer = value_type *;
1114     using reference = value_type &;
1115 
1116   private:
1117     MachineOperand *Op = nullptr;
1118 
1119     explicit defusechain_instr_iterator(MachineOperand *op) : Op(op) {
1120       // If the first node isn't one we're interested in, advance to one that
1121       // we are interested in.
1122       if (op) {
1123         if ((!ReturnUses && op->isUse()) ||
1124             (!ReturnDefs && op->isDef()) ||
1125             (SkipDebug && op->isDebug()))
1126           advance();
1127       }
1128     }
1129 
1130     void advance() {
1131       assert(Op && "Cannot increment end iterator!");
1132       Op = getNextOperandForReg(Op);
1133 
1134       // All defs come before the uses, so stop def_iterator early.
1135       if (!ReturnUses) {
1136         if (Op) {
1137           if (Op->isUse())
1138             Op = nullptr;
1139           else
1140             assert(!Op->isDebug() && "Can't have debug defs");
1141         }
1142       } else {
1143         // If this is an operand we don't care about, skip it.
1144         while (Op && ((!ReturnDefs && Op->isDef()) ||
1145                       (SkipDebug && Op->isDebug())))
1146           Op = getNextOperandForReg(Op);
1147       }
1148     }
1149 
1150   public:
1151     defusechain_instr_iterator() = default;
1152 
1153     bool operator==(const defusechain_instr_iterator &x) const {
1154       return Op == x.Op;
1155     }
1156     bool operator!=(const defusechain_instr_iterator &x) const {
1157       return !operator==(x);
1158     }
1159 
1160     /// atEnd - return true if this iterator is equal to reg_end() on the value.
1161     bool atEnd() const { return Op == nullptr; }
1162 
1163     // Iterator traversal: forward iteration only
1164     defusechain_instr_iterator &operator++() {          // Preincrement
1165       assert(Op && "Cannot increment end iterator!");
1166       if (ByOperand)
1167         advance();
1168       else if (ByInstr) {
1169         MachineInstr *P = Op->getParent();
1170         do {
1171           advance();
1172         } while (Op && Op->getParent() == P);
1173       } else if (ByBundle) {
1174         MachineBasicBlock::instr_iterator P =
1175             getBundleStart(Op->getParent()->getIterator());
1176         do {
1177           advance();
1178         } while (Op && getBundleStart(Op->getParent()->getIterator()) == P);
1179       }
1180 
1181       return *this;
1182     }
1183     defusechain_instr_iterator operator++(int) {        // Postincrement
1184       defusechain_instr_iterator tmp = *this; ++*this; return tmp;
1185     }
1186 
1187     // Retrieve a reference to the current operand.
1188     MachineInstr &operator*() const {
1189       assert(Op && "Cannot dereference end iterator!");
1190       if (ByBundle)
1191         return *getBundleStart(Op->getParent()->getIterator());
1192       return *Op->getParent();
1193     }
1194 
1195     MachineInstr *operator->() const { return &operator*(); }
1196   };
1197 };
1198 
1199 /// Iterate over the pressure sets affected by the given physical or virtual
1200 /// register. If Reg is physical, it must be a register unit (from
1201 /// MCRegUnitIterator).
1202 class PSetIterator {
1203   const int *PSet = nullptr;
1204   unsigned Weight = 0;
1205 
1206 public:
1207   PSetIterator() = default;
1208 
1209   PSetIterator(Register RegUnit, const MachineRegisterInfo *MRI) {
1210     const TargetRegisterInfo *TRI = MRI->getTargetRegisterInfo();
1211     if (RegUnit.isVirtual()) {
1212       const TargetRegisterClass *RC = MRI->getRegClass(RegUnit);
1213       PSet = TRI->getRegClassPressureSets(RC);
1214       Weight = TRI->getRegClassWeight(RC).RegWeight;
1215     } else {
1216       PSet = TRI->getRegUnitPressureSets(RegUnit);
1217       Weight = TRI->getRegUnitWeight(RegUnit);
1218     }
1219     if (*PSet == -1)
1220       PSet = nullptr;
1221   }
1222 
1223   bool isValid() const { return PSet; }
1224 
1225   unsigned getWeight() const { return Weight; }
1226 
1227   unsigned operator*() const { return *PSet; }
1228 
1229   void operator++() {
1230     assert(isValid() && "Invalid PSetIterator.");
1231     ++PSet;
1232     if (*PSet == -1)
1233       PSet = nullptr;
1234   }
1235 };
1236 
1237 inline PSetIterator
1238 MachineRegisterInfo::getPressureSets(Register RegUnit) const {
1239   return PSetIterator(RegUnit, this);
1240 }
1241 
1242 } // end namespace llvm
1243 
1244 #endif // LLVM_CODEGEN_MACHINEREGISTERINFO_H
1245