LLVM 24.0.0git
RegisterCoalescer.cpp
Go to the documentation of this file.
1//===- RegisterCoalescer.cpp - Generic Register Coalescing Interface ------===//
2//
3// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4// See https://llvm.org/LICENSE.txt for license information.
5// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6//
7//===----------------------------------------------------------------------===//
8//
9// This file implements the generic RegisterCoalescer interface which
10// is used as the common interface used by all clients and
11// implementations of register coalescing.
12//
13//===----------------------------------------------------------------------===//
14
15#include "RegisterCoalescer.h"
16#include "llvm/ADT/ArrayRef.h"
17#include "llvm/ADT/BitVector.h"
18#include "llvm/ADT/DenseSet.h"
19#include "llvm/ADT/STLExtras.h"
22#include "llvm/ADT/Statistic.h"
37#include "llvm/CodeGen/Passes.h"
45#include "llvm/IR/DebugLoc.h"
47#include "llvm/MC/LaneBitmask.h"
48#include "llvm/MC/MCInstrDesc.h"
50#include "llvm/Pass.h"
53#include "llvm/Support/Debug.h"
56#include <algorithm>
57#include <cassert>
58#include <iterator>
59#include <limits>
60#include <tuple>
61#include <utility>
62#include <vector>
63
64using namespace llvm;
65
66#define DEBUG_TYPE "regalloc"
67
68STATISTIC(numJoins, "Number of interval joins performed");
69STATISTIC(numCrossRCs, "Number of cross class joins performed");
70STATISTIC(numCommutes, "Number of instruction commuting performed");
71STATISTIC(numExtends, "Number of copies extended");
72STATISTIC(NumReMats, "Number of instructions re-materialized");
73STATISTIC(NumInflated, "Number of register classes inflated");
74STATISTIC(NumLaneConflicts, "Number of dead lane conflicts tested");
75STATISTIC(NumLaneResolves, "Number of dead lane conflicts resolved");
76STATISTIC(NumShrinkToUses, "Number of shrinkToUses called");
77
78static cl::opt<bool> EnableJoining("join-liveintervals",
79 cl::desc("Coalesce copies (default=true)"),
80 cl::init(true), cl::Hidden);
81
82static cl::opt<bool> UseTerminalRule("terminal-rule",
83 cl::desc("Apply the terminal rule"),
84 cl::init(true), cl::Hidden);
85
86/// Temporary flag to test critical edge unsplitting.
88 "join-splitedges",
89 cl::desc("Coalesce copies on split edges (default=subtarget)"), cl::Hidden);
90
91/// Temporary flag to test global copy optimization.
93 "join-globalcopies",
94 cl::desc("Coalesce copies that span blocks (default=subtarget)"),
96
98 "verify-coalescing",
99 cl::desc("Verify machine instrs before and after register coalescing"),
100 cl::Hidden);
101
103 "late-remat-update-threshold", cl::Hidden,
104 cl::desc("During rematerialization for a copy, if the def instruction has "
105 "many other copy uses to be rematerialized, delay the multiple "
106 "separate live interval update work and do them all at once after "
107 "all those rematerialization are done. It will save a lot of "
108 "repeated work. "),
109 cl::init(100));
110
112 "large-interval-size-threshold", cl::Hidden,
113 cl::desc("If the valnos size of an interval is larger than the threshold, "
114 "it is regarded as a large interval. "),
115 cl::init(100));
116
118 "large-interval-freq-threshold", cl::Hidden,
119 cl::desc("For a large interval, if it is coalesced with other live "
120 "intervals many times more than the threshold, stop its "
121 "coalescing to control the compile time. "),
122 cl::init(256));
123
124namespace {
125
126class JoinVals;
127
128class RegisterCoalescer : private LiveRangeEdit::Delegate {
129 MachineFunction *MF = nullptr;
130 MachineRegisterInfo *MRI = nullptr;
131 const TargetRegisterInfo *TRI = nullptr;
132 const TargetInstrInfo *TII = nullptr;
133 LiveIntervals *LIS = nullptr;
134 SlotIndexes *SI = nullptr;
135 const MachineLoopInfo *Loops = nullptr;
136 const RegisterClassInfo *RegClassInfo = nullptr;
137
138 /// Position and VReg of a PHI instruction during coalescing.
139 struct PHIValPos {
140 SlotIndex SI; ///< Slot where this PHI occurs.
141 Register Reg; ///< VReg the PHI occurs in.
142 unsigned SubReg; ///< Qualifying subregister for Reg.
143 };
144
145 /// Map from debug instruction number to PHI position during coalescing.
146 DenseMap<unsigned, PHIValPos> PHIValToPos;
147 /// Index of, for each VReg, which debug instruction numbers and
148 /// corresponding PHIs are sensitive to coalescing. Each VReg may have
149 /// multiple PHI defs, at different positions.
150 DenseMap<Register, SmallVector<unsigned, 2>> RegToPHIIdx;
151
152 /// Debug variable location tracking -- for each VReg, maintain an
153 /// ordered-by-slot-index set of DBG_VALUEs, to help quick
154 /// identification of whether coalescing may change location validity.
155 using DbgValueLoc = std::pair<SlotIndex, MachineInstr *>;
156 DenseMap<Register, std::vector<DbgValueLoc>> DbgVRegToValues;
157
158 /// A LaneMask to remember on which subregister live ranges we need to call
159 /// shrinkToUses() later.
160 LaneBitmask ShrinkMask;
161
162 /// True if the main range of the currently coalesced intervals should be
163 /// checked for smaller live intervals.
164 bool ShrinkMainRange = false;
165
166 /// True if the coalescer should aggressively coalesce global copies
167 /// in favor of keeping local copies.
168 bool JoinGlobalCopies = false;
169
170 /// True if the coalescer should aggressively coalesce fall-thru
171 /// blocks exclusively containing copies.
172 bool JoinSplitEdges = false;
173
174 /// Copy instructions yet to be coalesced.
175 SmallVector<MachineInstr *, 8> WorkList;
176 SmallVector<MachineInstr *, 8> LocalWorkList;
177
178 /// Set of instruction pointers that have been erased, and
179 /// that may be present in WorkList.
180 SmallPtrSet<MachineInstr *, 8> ErasedInstrs;
181
182 /// Dead instructions that are about to be deleted.
183 SmallVector<MachineInstr *, 8> DeadDefs;
184
185 /// Virtual registers to be considered for register class inflation.
186 SmallVector<Register, 8> InflateRegs;
187
188 /// The collection of live intervals which should have been updated
189 /// immediately after rematerialiation but delayed until
190 /// lateLiveIntervalUpdate is called.
191 DenseSet<Register> ToBeUpdated;
192
193 /// Record how many times the large live interval with many valnos
194 /// has been tried to join with other live interval.
195 DenseMap<Register, unsigned long> LargeLIVisitCounter;
196
197 /// Recursively eliminate dead defs in DeadDefs.
198 void eliminateDeadDefs(LiveRangeEdit *Edit = nullptr);
199
200 /// LiveRangeEdit callback for eliminateDeadDefs().
201 void LRE_WillEraseInstruction(MachineInstr *MI) override;
202
203 /// Coalesce the LocalWorkList.
204 void coalesceLocals();
205
206 /// Join compatible live intervals
207 void joinAllIntervals();
208
209 /// Coalesce copies in the specified MBB, putting
210 /// copies that cannot yet be coalesced into WorkList.
211 void copyCoalesceInMBB(MachineBasicBlock *MBB);
212
213 /// Tries to coalesce all copies in CurrList. Returns true if any progress
214 /// was made.
215 bool copyCoalesceWorkList(MutableArrayRef<MachineInstr *> CurrList);
216
217 /// If one def has many copy like uses, and those copy uses are all
218 /// rematerialized, the live interval update needed for those
219 /// rematerializations will be delayed and done all at once instead
220 /// of being done multiple times. This is to save compile cost because
221 /// live interval update is costly.
222 void lateLiveIntervalUpdate();
223
224 /// Check if the incoming value defined by a COPY at \p SLRQ in the subrange
225 /// has no value defined in the predecessors. If the incoming value is the
226 /// same as defined by the copy itself, the value is considered undefined.
227 bool copyValueUndefInPredecessors(LiveRange &S, const MachineBasicBlock *MBB,
228 LiveQueryResult SLRQ);
229
230 /// Set necessary undef flags on subregister uses after pruning out undef
231 /// lane segments from the subrange.
232 void setUndefOnPrunedSubRegUses(LiveInterval &LI, Register Reg,
233 LaneBitmask PrunedLanes);
234
235 /// Result of attempting to coalesce a copy.
236 /// - Joined: the copy was removed or otherwise fully handled.
237 /// - Deferred: retry after other coalescing may make progress.
238 /// - Rejected: do not retry, either because the copy is not a coalescing
239 /// candidate or because the join was intentionally rejected.
240 enum class JoinResult { Joined, Deferred, Rejected };
241
242 /// Attempt to join intervals corresponding to SrcReg/DstReg, which are the
243 /// src/dst of the copy instruction CopyMI.
244 JoinResult joinCopy(MachineInstr *CopyMI,
245 SmallPtrSetImpl<MachineInstr *> &CurrentErasedInstrs);
246
247 /// Attempt to join these two intervals. On failure, the output "SrcInt"
248 /// will not have been modified, so we can use this information below to
249 /// update aliases. Returns Deferred when it may be possible to join later,
250 /// or Rejected when retrying should be avoided.
251 JoinResult joinIntervals(CoalescerPair &CP);
252
253 /// Attempt joining two virtual registers.
254 JoinResult joinVirtRegs(CoalescerPair &CP);
255
256 /// If a live interval has many valnos and is coalesced with other
257 /// live intervals many times, we regard such live interval as having
258 /// high compile time cost.
259 bool isHighCostLiveInterval(LiveInterval &LI);
260
261 /// Attempt joining with a reserved physreg.
262 bool joinReservedPhysReg(CoalescerPair &CP);
263
264 /// Add the LiveRange @p ToMerge as a subregister liverange of @p LI.
265 /// Subranges in @p LI which only partially interfere with the desired
266 /// LaneMask are split as necessary. @p LaneMask are the lanes that
267 /// @p ToMerge will occupy in the coalescer register. @p LI has its subrange
268 /// lanemasks already adjusted to the coalesced register.
269 void mergeSubRangeInto(LiveInterval &LI, const LiveRange &ToMerge,
270 LaneBitmask LaneMask, CoalescerPair &CP,
271 unsigned DstIdx);
272
273 /// Join the liveranges of two subregisters. Joins @p RRange into
274 /// @p LRange, @p RRange may be invalid afterwards.
275 void joinSubRegRanges(LiveRange &LRange, LiveRange &RRange,
276 LaneBitmask LaneMask, const CoalescerPair &CP);
277
278 /// We found a non-trivially-coalescable copy. If the source value number is
279 /// defined by a copy from the destination reg see if we can merge these two
280 /// destination reg valno# into a single value number, eliminating a copy.
281 /// This returns true if an interval was modified.
282 bool adjustCopiesBackFrom(const CoalescerPair &CP, MachineInstr *CopyMI);
283
284 /// Return true if there are definitions of IntB
285 /// other than BValNo val# that can reach uses of AValno val# of IntA.
286 bool hasOtherReachingDefs(LiveInterval &IntA, LiveInterval &IntB,
287 VNInfo *AValNo, VNInfo *BValNo);
288
289 /// We found a non-trivially-coalescable copy.
290 /// If the source value number is defined by a commutable instruction and
291 /// its other operand is coalesced to the copy dest register, see if we
292 /// can transform the copy into a noop by commuting the definition.
293 /// This returns a pair of two flags:
294 /// - the first element is true if an interval was modified,
295 /// - the second element is true if the destination interval needs
296 /// to be shrunk after deleting the copy.
297 std::pair<bool, bool> removeCopyByCommutingDef(const CoalescerPair &CP,
298 MachineInstr *CopyMI);
299
300 /// We found a copy which can be moved to its less frequent predecessor.
301 bool removePartialRedundancy(const CoalescerPair &CP, MachineInstr &CopyMI);
302
303 /// If the source of a copy is defined by a CheapAsAMove computation,
304 /// replace the copy by rematerialize the definition.
305 bool reMaterializeDef(const CoalescerPair &CP, MachineInstr *CopyMI,
306 bool &IsDefCopy);
307
308 /// Return true if a copy involving a physreg should be joined.
309 bool canJoinPhys(const CoalescerPair &CP);
310
311 /// Replace all defs and uses of SrcReg to DstReg and update the subregister
312 /// number if it is not zero. If DstReg is a physical register and the
313 /// existing subregister number of the def / use being updated is not zero,
314 /// make sure to set it to the correct physical subregister.
315 void updateRegDefsUses(Register SrcReg, Register DstReg, unsigned SubIdx);
316
317 /// If the given machine operand reads only undefined lanes add an undef
318 /// flag.
319 /// This can happen when undef uses were previously concealed by a copy
320 /// which we coalesced. Example:
321 /// %0:sub0<def,read-undef> = ...
322 /// %1 = COPY %0 <-- Coalescing COPY reveals undef
323 /// = use %1:sub1 <-- hidden undef use
324 void addUndefFlag(const LiveInterval &Int, SlotIndex UseIdx,
325 MachineOperand &MO, unsigned SubRegIdx);
326
327 /// Handle copies of undef values. If the undef value is an incoming
328 /// PHI value, it will convert @p CopyMI to an IMPLICIT_DEF.
329 /// Returns nullptr if @p CopyMI was not in any way eliminable. Otherwise,
330 /// it returns @p CopyMI (which could be an IMPLICIT_DEF at this point).
331 MachineInstr *eliminateUndefCopy(MachineInstr *CopyMI);
332
333 /// Check whether or not we should apply the terminal rule on the
334 /// destination (Dst) of \p Copy.
335 /// When the terminal rule applies, Copy is not profitable to
336 /// coalesce.
337 /// Dst is terminal if it has exactly one affinity (Dst, Src) and
338 /// at least one interference (Dst, Dst2). If Dst is terminal, the
339 /// terminal rule consists in checking that at least one of
340 /// interfering node, say Dst2, has an affinity of equal or greater
341 /// weight with Src.
342 /// In that case, Dst2 and Dst will not be able to be both coalesced
343 /// with Src. Since Dst2 exposes more coalescing opportunities than
344 /// Dst, we can drop \p Copy.
345 bool applyTerminalRule(const MachineInstr &Copy) const;
346
347 /// Wrapper method for \see LiveIntervals::shrinkToUses.
348 /// This method does the proper fixing of the live-ranges when the afore
349 /// mentioned method returns true.
350 void shrinkToUses(LiveInterval *LI,
351 SmallVectorImpl<MachineInstr *> *Dead = nullptr) {
352 NumShrinkToUses++;
353 if (LIS->shrinkToUses(LI, Dead)) {
354 /// Check whether or not \p LI is composed by multiple connected
355 /// components and if that is the case, fix that.
357 LIS->splitSeparateComponents(*LI, SplitLIs);
358 }
359 }
360
361 /// Wrapper Method to do all the necessary work when an Instruction is
362 /// deleted.
363 /// Optimizations should use this to make sure that deleted instructions
364 /// are always accounted for.
365 void deleteInstr(MachineInstr *MI) {
366 ErasedInstrs.insert(MI);
367 LIS->RemoveMachineInstrFromMaps(*MI);
368 MI->eraseFromParent();
369 }
370
371 /// Walk over function and initialize the DbgVRegToValues map.
373
374 /// Test whether, after merging, any DBG_VALUEs would refer to a
375 /// different value number than before merging, and whether this can
376 /// be resolved. If not, mark the DBG_VALUE as being undef.
377 void checkMergingChangesDbgValues(CoalescerPair &CP, LiveRange &LHS,
378 JoinVals &LHSVals, LiveRange &RHS,
379 JoinVals &RHSVals);
380
381 void checkMergingChangesDbgValuesImpl(Register Reg, LiveRange &OtherRange,
382 LiveRange &RegRange, JoinVals &Vals2);
383
384public:
385 // For legacy pass only.
386 RegisterCoalescer() = default;
387 RegisterCoalescer &operator=(RegisterCoalescer &&Other) = default;
388
389 RegisterCoalescer(LiveIntervals *LIS, SlotIndexes *SI,
390 const MachineLoopInfo *Loops,
391 const RegisterClassInfo *RegClassInfo)
392 : LIS(LIS), SI(SI), Loops(Loops), RegClassInfo(RegClassInfo) {}
393
394 bool run(MachineFunction &MF);
395};
396
397class RegisterCoalescerLegacy : public MachineFunctionPass {
398public:
399 static char ID; ///< Class identification, replacement for typeinfo
400
401 RegisterCoalescerLegacy() : MachineFunctionPass(ID) {}
402
403 void getAnalysisUsage(AnalysisUsage &AU) const override;
404
405 MachineFunctionProperties getClearedProperties() const override {
406 return MachineFunctionProperties().setIsSSA();
407 }
408
409 /// This is the pass entry point.
410 bool runOnMachineFunction(MachineFunction &) override;
411};
412
413} // end anonymous namespace
414
415char RegisterCoalescerLegacy::ID = 0;
416
417char &llvm::RegisterCoalescerID = RegisterCoalescerLegacy::ID;
418
419INITIALIZE_PASS_BEGIN(RegisterCoalescerLegacy, "register-coalescer",
420 "Register Coalescer", false, false)
425INITIALIZE_PASS_END(RegisterCoalescerLegacy, "register-coalescer",
426 "Register Coalescer", false, false)
427
428[[nodiscard]] static bool isMoveInstr(const TargetRegisterInfo &tri,
430 Register &Dst, unsigned &SrcSub,
431 unsigned &DstSub) {
432 if (MI->isCopy()) {
433 Dst = MI->getOperand(0).getReg();
434 DstSub = MI->getOperand(0).getSubReg();
435 Src = MI->getOperand(1).getReg();
436 SrcSub = MI->getOperand(1).getSubReg();
437 } else if (MI->isSubregToReg()) {
438 Dst = MI->getOperand(0).getReg();
439 DstSub = tri.composeSubRegIndices(MI->getOperand(0).getSubReg(),
440 MI->getOperand(2).getImm());
441 Src = MI->getOperand(1).getReg();
442 SrcSub = MI->getOperand(1).getSubReg();
443 } else
444 return false;
445 return true;
446}
447
448/// Return true if this block should be vacated by the coalescer to eliminate
449/// branches. The important cases to handle in the coalescer are critical edges
450/// split during phi elimination which contain only copies. Simple blocks that
451/// contain non-branches should also be vacated, but this can be handled by an
452/// earlier pass similar to early if-conversion.
453static bool isSplitEdge(const MachineBasicBlock *MBB) {
454 if (MBB->pred_size() != 1 || MBB->succ_size() != 1)
455 return false;
456
457 for (const auto &MI : *MBB) {
458 if (!MI.isCopyLike() && !MI.isUnconditionalBranch())
459 return false;
460 }
461 return true;
462}
463
465 SrcReg = DstReg = Register();
466 SrcIdx = DstIdx = 0;
467 NewRC = nullptr;
468 Flipped = CrossClass = false;
469
470 Register Src, Dst;
471 unsigned SrcSub = 0, DstSub = 0;
472 if (!isMoveInstr(TRI, MI, Src, Dst, SrcSub, DstSub))
473 return false;
474 Partial = SrcSub || DstSub;
475
476 // If one register is a physreg, it must be Dst.
477 if (Src.isPhysical()) {
478 if (Dst.isPhysical())
479 return false;
480 std::swap(Src, Dst);
481 std::swap(SrcSub, DstSub);
482 Flipped = true;
483 }
484
485 const MachineRegisterInfo &MRI = MI->getMF()->getRegInfo();
486 const TargetRegisterClass *SrcRC = MRI.getRegClass(Src);
487
488 if (Dst.isPhysical()) {
489 // Eliminate DstSub on a physreg.
490 if (DstSub) {
491 Dst = TRI.getSubReg(Dst, DstSub);
492 if (!Dst)
493 return false;
494 DstSub = 0;
495 }
496
497 // Eliminate SrcSub by picking a corresponding Dst superregister.
498 if (SrcSub) {
499 Dst = TRI.getMatchingSuperReg(Dst, SrcSub, SrcRC);
500 if (!Dst)
501 return false;
502 } else if (!SrcRC->contains(Dst)) {
503 return false;
504 }
505 } else {
506 // Both registers are virtual.
507 const TargetRegisterClass *DstRC = MRI.getRegClass(Dst);
508
509 // Both registers have subreg indices.
510 if (SrcSub && DstSub) {
511 // Copies between different sub-registers are never coalescable.
512 if (Src == Dst && SrcSub != DstSub)
513 return false;
514
515 NewRC = TRI.getCommonSuperRegClass(SrcRC, SrcSub, DstRC, DstSub, SrcIdx,
516 DstIdx);
517 if (!NewRC)
518 return false;
519 } else if (DstSub) {
520 // SrcReg will be merged with a sub-register of DstReg.
521 SrcIdx = DstSub;
522 NewRC = TRI.getMatchingSuperRegClass(DstRC, SrcRC, DstSub);
523 } else if (SrcSub) {
524 // DstReg will be merged with a sub-register of SrcReg.
525 DstIdx = SrcSub;
526 NewRC = TRI.getMatchingSuperRegClass(SrcRC, DstRC, SrcSub);
527 } else {
528 // This is a straight copy without sub-registers.
529 NewRC = TRI.getCommonSubClass(DstRC, SrcRC);
530 }
531
532 // The combined constraint may be impossible to satisfy.
533 if (!NewRC)
534 return false;
535
536 // Prefer SrcReg to be a sub-register of DstReg.
537 // FIXME: Coalescer should support subregs symmetrically.
538 if (DstIdx && !SrcIdx) {
539 std::swap(Src, Dst);
540 std::swap(SrcIdx, DstIdx);
541 Flipped = !Flipped;
542 }
543
544 CrossClass = NewRC != DstRC || NewRC != SrcRC;
545 }
546 // Check our invariants
547 assert(Src.isVirtual() && "Src must be virtual");
548 assert(!(Dst.isPhysical() && DstSub) && "Cannot have a physical SubIdx");
549 SrcReg = Src;
550 DstReg = Dst;
551 return true;
552}
553
555 if (DstReg.isPhysical())
556 return false;
557 std::swap(SrcReg, DstReg);
558 std::swap(SrcIdx, DstIdx);
559 Flipped = !Flipped;
560 return true;
561}
562
564 if (!MI)
565 return false;
566 Register Src, Dst;
567 unsigned SrcSub = 0, DstSub = 0;
568 if (!isMoveInstr(TRI, MI, Src, Dst, SrcSub, DstSub))
569 return false;
570
571 // Find the virtual register that is SrcReg.
572 if (Dst == SrcReg) {
573 std::swap(Src, Dst);
574 std::swap(SrcSub, DstSub);
575 } else if (Src != SrcReg) {
576 return false;
577 }
578
579 // Now check that Dst matches DstReg.
580 if (DstReg.isPhysical()) {
581 if (!Dst.isPhysical())
582 return false;
583 assert(!DstIdx && !SrcIdx && "Inconsistent CoalescerPair state.");
584 // DstSub could be set for a physreg from INSERT_SUBREG.
585 if (DstSub)
586 Dst = TRI.getSubReg(Dst, DstSub);
587 // Full copy of Src.
588 if (!SrcSub)
589 return DstReg == Dst;
590 // This is a partial register copy. Check that the parts match.
591 return Register(TRI.getSubReg(DstReg, SrcSub)) == Dst;
592 }
593
594 // DstReg is virtual.
595 if (DstReg != Dst)
596 return false;
597 // Registers match, do the subregisters line up?
598 return TRI.composeSubRegIndices(SrcIdx, SrcSub) ==
599 TRI.composeSubRegIndices(DstIdx, DstSub);
600}
601
602void RegisterCoalescerLegacy::getAnalysisUsage(AnalysisUsage &AU) const {
603 AU.setPreservesCFG();
611}
612
613void RegisterCoalescer::eliminateDeadDefs(LiveRangeEdit *Edit) {
614 if (Edit) {
615 Edit->eliminateDeadDefs(DeadDefs);
616 return;
617 }
619 LiveRangeEdit(nullptr, NewRegs, *MF, *LIS, nullptr, this)
620 .eliminateDeadDefs(DeadDefs);
621}
622
623void RegisterCoalescer::LRE_WillEraseInstruction(MachineInstr *MI) {
624 // MI may be in WorkList. Make sure we don't visit it.
625 ErasedInstrs.insert(MI);
626}
627
628bool RegisterCoalescer::adjustCopiesBackFrom(const CoalescerPair &CP,
629 MachineInstr *CopyMI) {
630 assert(!CP.isPartial() && "This doesn't work for partial copies.");
631 assert(!CP.isPhys() && "This doesn't work for physreg copies.");
632
633 LiveInterval &IntA =
634 LIS->getInterval(CP.isFlipped() ? CP.getDstReg() : CP.getSrcReg());
635 LiveInterval &IntB =
636 LIS->getInterval(CP.isFlipped() ? CP.getSrcReg() : CP.getDstReg());
637 SlotIndex CopyIdx = LIS->getInstructionIndex(*CopyMI).getRegSlot();
638
639 // We have a non-trivially-coalescable copy with IntA being the source and
640 // IntB being the dest, thus this defines a value number in IntB. If the
641 // source value number (in IntA) is defined by a copy from B, see if we can
642 // merge these two pieces of B into a single value number, eliminating a copy.
643 // For example:
644 //
645 // A3 = B0
646 // ...
647 // B1 = A3 <- this copy
648 //
649 // In this case, B0 can be extended to where the B1 copy lives, allowing the
650 // B1 value number to be replaced with B0 (which simplifies the B
651 // liveinterval).
652
653 // BValNo is a value number in B that is defined by a copy from A. 'B1' in
654 // the example above.
656 if (BS == IntB.end())
657 return false;
658 VNInfo *BValNo = BS->valno;
659
660 // Get the location that B is defined at. Two options: either this value has
661 // an unknown definition point or it is defined at CopyIdx. If unknown, we
662 // can't process it.
663 if (BValNo->def != CopyIdx)
664 return false;
665
666 // AValNo is the value number in A that defines the copy, A3 in the example.
667 SlotIndex CopyUseIdx = CopyIdx.getRegSlot(true);
668 LiveInterval::iterator AS = IntA.FindSegmentContaining(CopyUseIdx);
669 // The live segment might not exist after fun with physreg coalescing.
670 if (AS == IntA.end())
671 return false;
672 VNInfo *AValNo = AS->valno;
673
674 // If AValNo is defined as a copy from IntB, we can potentially process this.
675 // Get the instruction that defines this value number.
676 MachineInstr *ACopyMI = LIS->getInstructionFromIndex(AValNo->def);
677 // Don't allow any partial copies, even if isCoalescable() allows them.
678 if (!CP.isCoalescable(ACopyMI) || !ACopyMI->isFullCopy())
679 return false;
680
681 // Get the Segment in IntB that this value number starts with.
683 IntB.FindSegmentContaining(AValNo->def.getPrevSlot());
684 if (ValS == IntB.end())
685 return false;
686
687 // Make sure that the end of the live segment is inside the same block as
688 // CopyMI.
689 MachineInstr *ValSEndInst =
690 LIS->getInstructionFromIndex(ValS->end.getPrevSlot());
691 if (!ValSEndInst || ValSEndInst->getParent() != CopyMI->getParent())
692 return false;
693
694 // Okay, we now know that ValS ends in the same block that the CopyMI
695 // live-range starts. If there are no intervening live segments between them
696 // in IntB, we can merge them.
697 if (ValS + 1 != BS)
698 return false;
699
700 LLVM_DEBUG(dbgs() << "Extending: " << printReg(IntB.reg(), TRI));
701
702 SlotIndex FillerStart = ValS->end, FillerEnd = BS->start;
703 // We are about to delete CopyMI, so need to remove it as the 'instruction
704 // that defines this value #'. Update the valnum with the new defining
705 // instruction #.
706 BValNo->def = FillerStart;
707
708 // Okay, we can merge them. We need to insert a new liverange:
709 // [ValS.end, BS.begin) of either value number, then we merge the
710 // two value numbers.
711 IntB.addSegment(LiveInterval::Segment(FillerStart, FillerEnd, BValNo));
712
713 // Okay, merge "B1" into the same value number as "B0".
714 if (BValNo != ValS->valno)
715 IntB.MergeValueNumberInto(BValNo, ValS->valno);
716
717 // Do the same for the subregister segments.
718 for (LiveInterval::SubRange &S : IntB.subranges()) {
719 // Check for SubRange Segments of the form [1234r,1234d:0) which can be
720 // removed to prevent creating bogus SubRange Segments.
721 LiveInterval::iterator SS = S.FindSegmentContaining(CopyIdx);
722 if (SS != S.end() && SlotIndex::isSameInstr(SS->start, SS->end)) {
723 S.removeSegment(*SS, true);
724 continue;
725 }
726 // The subrange may have ended before FillerStart. If so, extend it.
727 if (!S.getVNInfoAt(FillerStart)) {
728 SlotIndex BBStart =
729 LIS->getMBBStartIdx(LIS->getMBBFromIndex(FillerStart));
730 S.extendInBlock(BBStart, FillerStart);
731 }
732 VNInfo *SubBValNo = S.getVNInfoAt(CopyIdx);
733 S.addSegment(LiveInterval::Segment(FillerStart, FillerEnd, SubBValNo));
734 VNInfo *SubValSNo = S.getVNInfoAt(AValNo->def.getPrevSlot());
735 if (SubBValNo != SubValSNo)
736 S.MergeValueNumberInto(SubBValNo, SubValSNo);
737 }
738
739 LLVM_DEBUG(dbgs() << " result = " << IntB << '\n');
740
741 // If the source instruction was killing the source register before the
742 // merge, unset the isKill marker given the live range has been extended.
743 int UIdx =
744 ValSEndInst->findRegisterUseOperandIdx(IntB.reg(), /*TRI=*/nullptr, true);
745 if (UIdx != -1) {
746 ValSEndInst->getOperand(UIdx).setIsKill(false);
747 }
748
749 // Rewrite the copy.
750 CopyMI->substituteRegister(IntA.reg(), IntB.reg(), 0, *TRI);
751 // If the copy instruction was killing the destination register or any
752 // subrange before the merge trim the live range.
753 bool RecomputeLiveRange = AS->end == CopyIdx;
754 if (!RecomputeLiveRange) {
755 for (LiveInterval::SubRange &S : IntA.subranges()) {
756 LiveInterval::iterator SS = S.FindSegmentContaining(CopyUseIdx);
757 if (SS != S.end() && SS->end == CopyIdx) {
758 RecomputeLiveRange = true;
759 break;
760 }
761 }
762 }
763 if (RecomputeLiveRange)
764 shrinkToUses(&IntA);
765
766 ++numExtends;
767 return true;
768}
769
770bool RegisterCoalescer::hasOtherReachingDefs(LiveInterval &IntA,
771 LiveInterval &IntB, VNInfo *AValNo,
772 VNInfo *BValNo) {
773 // If AValNo has PHI kills, conservatively assume that IntB defs can reach
774 // the PHI values.
775 if (LIS->hasPHIKill(IntA, AValNo))
776 return true;
777
778 for (LiveRange::Segment &ASeg : IntA.segments) {
779 if (ASeg.valno != AValNo)
780 continue;
782 if (BI != IntB.begin())
783 --BI;
784 for (; BI != IntB.end() && ASeg.end >= BI->start; ++BI) {
785 if (BI->valno == BValNo)
786 continue;
787 if (BI->start <= ASeg.start && BI->end > ASeg.start)
788 return true;
789 if (BI->start > ASeg.start && BI->start < ASeg.end)
790 return true;
791 }
792 }
793 return false;
794}
795
796/// Copy segments with value number @p SrcValNo from liverange @p Src to live
797/// range @Dst and use value number @p DstValNo there.
798static std::pair<bool, bool> addSegmentsWithValNo(LiveRange &Dst,
799 VNInfo *DstValNo,
800 const LiveRange &Src,
801 const VNInfo *SrcValNo) {
802 bool Changed = false;
803 bool MergedWithDead = false;
804 for (const LiveRange::Segment &S : Src.segments) {
805 if (S.valno != SrcValNo)
806 continue;
807 // This is adding a segment from Src that ends in a copy that is about
808 // to be removed. This segment is going to be merged with a pre-existing
809 // segment in Dst. This works, except in cases when the corresponding
810 // segment in Dst is dead. For example: adding [192r,208r:1) from Src
811 // to [208r,208d:1) in Dst would create [192r,208d:1) in Dst.
812 // Recognized such cases, so that the segments can be shrunk.
813 LiveRange::Segment Added = LiveRange::Segment(S.start, S.end, DstValNo);
814 LiveRange::Segment &Merged = *Dst.addSegment(Added);
815 if (Merged.end.isDead())
816 MergedWithDead = true;
817 Changed = true;
818 }
819 return std::make_pair(Changed, MergedWithDead);
820}
821
822std::pair<bool, bool>
823RegisterCoalescer::removeCopyByCommutingDef(const CoalescerPair &CP,
824 MachineInstr *CopyMI) {
825 assert(!CP.isPhys());
826
827 LiveInterval &IntA =
828 LIS->getInterval(CP.isFlipped() ? CP.getDstReg() : CP.getSrcReg());
829 LiveInterval &IntB =
830 LIS->getInterval(CP.isFlipped() ? CP.getSrcReg() : CP.getDstReg());
831
832 // We found a non-trivially-coalescable copy with IntA being the source and
833 // IntB being the dest, thus this defines a value number in IntB. If the
834 // source value number (in IntA) is defined by a commutable instruction and
835 // its other operand is coalesced to the copy dest register, see if we can
836 // transform the copy into a noop by commuting the definition. For example,
837 //
838 // A3 = op A2 killed B0
839 // ...
840 // B1 = A3 <- this copy
841 // ...
842 // = op A3 <- more uses
843 //
844 // ==>
845 //
846 // B2 = op B0 killed A2
847 // ...
848 // B1 = B2 <- now an identity copy
849 // ...
850 // = op B2 <- more uses
851
852 // BValNo is a value number in B that is defined by a copy from A. 'B1' in
853 // the example above.
854 SlotIndex CopyIdx = LIS->getInstructionIndex(*CopyMI).getRegSlot();
855 VNInfo *BValNo = IntB.getVNInfoAt(CopyIdx);
856 assert(BValNo != nullptr && BValNo->def == CopyIdx);
857
858 // AValNo is the value number in A that defines the copy, A3 in the example.
859 VNInfo *AValNo = IntA.getVNInfoAt(CopyIdx.getRegSlot(true));
860 assert(AValNo && !AValNo->isUnused() && "COPY source not live");
861 if (AValNo->isPHIDef())
862 return {false, false};
864 if (!DefMI)
865 return {false, false};
866 if (!DefMI->isCommutable())
867 return {false, false};
868 // If DefMI is a two-address instruction then commuting it will change the
869 // destination register.
870 int DefIdx = DefMI->findRegisterDefOperandIdx(IntA.reg(), /*TRI=*/nullptr);
871 assert(DefIdx != -1);
872 unsigned UseOpIdx;
873 if (!DefMI->isRegTiedToUseOperand(DefIdx, &UseOpIdx))
874 return {false, false};
875
876 // If DefMI only defines the register partially, we can't replace uses of the
877 // full register with the new destination register after commuting it.
878 if (IntA.reg().isVirtual() &&
879 none_of(DefMI->all_defs(), [&](const MachineOperand &DefMO) {
880 return DefMO.getReg() == IntA.reg() && !DefMO.getSubReg();
881 }))
882 return {false, false};
883
884 // FIXME: The code below tries to commute 'UseOpIdx' operand with some other
885 // commutable operand which is expressed by 'CommuteAnyOperandIndex'value
886 // passed to the method. That _other_ operand is chosen by
887 // the findCommutedOpIndices() method.
888 //
889 // That is obviously an area for improvement in case of instructions having
890 // more than 2 operands. For example, if some instruction has 3 commutable
891 // operands then all possible variants (i.e. op#1<->op#2, op#1<->op#3,
892 // op#2<->op#3) of commute transformation should be considered/tried here.
893 unsigned NewDstIdx = TargetInstrInfo::CommuteAnyOperandIndex;
894 if (!TII->findCommutedOpIndices(*DefMI, UseOpIdx, NewDstIdx))
895 return {false, false};
896
897 MachineOperand &NewDstMO = DefMI->getOperand(NewDstIdx);
898 Register NewReg = NewDstMO.getReg();
899 if (NewReg != IntB.reg() || !IntB.Query(AValNo->def).isKill())
900 return {false, false};
901
902 // Make sure there are no other definitions of IntB that would reach the
903 // uses which the new definition can reach.
904 if (hasOtherReachingDefs(IntA, IntB, AValNo, BValNo))
905 return {false, false};
906
907 // Make sure all reads of AValNo can be rewritten to the new register.
908 for (MachineOperand &MO : MRI->reg_nodbg_operands(IntA.reg())) {
909 if (!MO.readsReg())
910 continue;
911 MachineInstr *UseMI = MO.getParent();
912 unsigned OpNo = &MO - &UseMI->getOperand(0);
913 SlotIndex UseIdx = LIS->getInstructionIndex(*UseMI);
915 if (US == IntA.end() || US->valno != AValNo)
916 continue;
917 // Partial defs and tied uses can't be rewritten independently.
918 if (MO.isDef() || UseMI->isRegTiedToDefOperand(OpNo))
919 return {false, false};
920 }
921
922 LLVM_DEBUG(dbgs() << "\tremoveCopyByCommutingDef: " << AValNo->def << '\t'
923 << *DefMI);
924
925 // At this point we have decided that it is legal to do this
926 // transformation. Start by commuting the instruction.
928 MachineInstr *NewMI =
929 TII->commuteInstruction(*DefMI, false, UseOpIdx, NewDstIdx);
930 if (!NewMI)
931 return {false, false};
932 if (IntA.reg().isVirtual() && IntB.reg().isVirtual() &&
933 !MRI->constrainRegClass(IntB.reg(), MRI->getRegClass(IntA.reg())))
934 return {false, false};
935 if (NewMI != DefMI) {
936 LIS->ReplaceMachineInstrInMaps(*DefMI, *NewMI);
938 MBB->insert(Pos, NewMI);
939 MBB->erase(DefMI);
940 }
941
942 // If ALR and BLR overlaps and end of BLR extends beyond end of ALR, e.g.
943 // A = or A, B
944 // ...
945 // B = A
946 // ...
947 // C = killed A
948 // ...
949 // = B
950
951 // Update uses of IntA of the specific Val# with IntB.
952 for (MachineOperand &UseMO :
954 if (UseMO.isUndef())
955 continue;
956 MachineInstr *UseMI = UseMO.getParent();
957 if (UseMI->isDebugInstr()) {
958 // FIXME These don't have an instruction index. Not clear we have enough
959 // info to decide whether to do this replacement or not. For now do it.
960 UseMO.setReg(NewReg);
961 continue;
962 }
963 SlotIndex UseIdx = LIS->getInstructionIndex(*UseMI).getRegSlot(true);
965 assert(US != IntA.end() && "Use must be live");
966 if (US->valno != AValNo)
967 continue;
968 // Kill flags are no longer accurate. They are recomputed after RA.
969 UseMO.setIsKill(false);
970 if (NewReg.isPhysical())
971 UseMO.substPhysReg(NewReg, *TRI);
972 else
973 UseMO.setReg(NewReg);
974 if (UseMI == CopyMI)
975 continue;
976 if (!UseMI->isCopy())
977 continue;
978 if (UseMI->getOperand(0).getReg() != IntB.reg() ||
980 continue;
981
982 // This copy will become a noop. If it's defining a new val#, merge it into
983 // BValNo.
984 SlotIndex DefIdx = UseIdx.getRegSlot();
985 VNInfo *DVNI = IntB.getVNInfoAt(DefIdx);
986 if (!DVNI)
987 continue;
988 LLVM_DEBUG(dbgs() << "\t\tnoop: " << DefIdx << '\t' << *UseMI);
989 assert(DVNI->def == DefIdx);
990 BValNo = IntB.MergeValueNumberInto(DVNI, BValNo);
991 for (LiveInterval::SubRange &S : IntB.subranges()) {
992 VNInfo *SubDVNI = S.getVNInfoAt(DefIdx);
993 if (!SubDVNI)
994 continue;
995 VNInfo *SubBValNo = S.getVNInfoAt(CopyIdx);
996 assert(SubBValNo->def == CopyIdx);
997 S.MergeValueNumberInto(SubDVNI, SubBValNo);
998 }
999
1000 deleteInstr(UseMI);
1001 }
1002
1003 // Extend BValNo by merging in IntA live segments of AValNo. Val# definition
1004 // is updated.
1005 bool ShrinkB = false;
1007 if (IntA.hasSubRanges() || IntB.hasSubRanges()) {
1008 if (!IntA.hasSubRanges()) {
1010 IntA.createSubRangeFrom(Allocator, Mask, IntA);
1011 } else if (!IntB.hasSubRanges()) {
1013 IntB.createSubRangeFrom(Allocator, Mask, IntB);
1014 }
1015 SlotIndex AIdx = CopyIdx.getRegSlot(true);
1016 LaneBitmask MaskA;
1017 const SlotIndexes &Indexes = *LIS->getSlotIndexes();
1018 for (LiveInterval::SubRange &SA : IntA.subranges()) {
1019 VNInfo *ASubValNo = SA.getVNInfoAt(AIdx);
1020 // Even if we are dealing with a full copy, some lanes can
1021 // still be undefined.
1022 // E.g.,
1023 // undef A.subLow = ...
1024 // B = COPY A <== A.subHigh is undefined here and does
1025 // not have a value number.
1026 if (!ASubValNo)
1027 continue;
1028 MaskA |= SA.LaneMask;
1029
1030 IntB.refineSubRanges(
1031 Allocator, SA.LaneMask,
1032 [&Allocator, &SA, CopyIdx, ASubValNo,
1033 &ShrinkB](LiveInterval::SubRange &SR) {
1034 VNInfo *BSubValNo = SR.empty() ? SR.getNextValue(CopyIdx, Allocator)
1035 : SR.getVNInfoAt(CopyIdx);
1036 assert(BSubValNo != nullptr);
1037 auto P = addSegmentsWithValNo(SR, BSubValNo, SA, ASubValNo);
1038 ShrinkB |= P.second;
1039 if (P.first)
1040 BSubValNo->def = ASubValNo->def;
1041 },
1042 Indexes, *TRI);
1043 }
1044 // Go over all subranges of IntB that have not been covered by IntA,
1045 // and delete the segments starting at CopyIdx. This can happen if
1046 // IntA has undef lanes that are defined in IntB.
1047 for (LiveInterval::SubRange &SB : IntB.subranges()) {
1048 if ((SB.LaneMask & MaskA).any())
1049 continue;
1050 if (LiveRange::Segment *S = SB.getSegmentContaining(CopyIdx))
1051 if (S->start.getBaseIndex() == CopyIdx.getBaseIndex())
1052 SB.removeSegment(*S, true);
1053 }
1054 }
1055
1056 BValNo->def = AValNo->def;
1057 auto P = addSegmentsWithValNo(IntB, BValNo, IntA, AValNo);
1058 ShrinkB |= P.second;
1059 LLVM_DEBUG(dbgs() << "\t\textended: " << IntB << '\n');
1060
1061 LIS->removeVRegDefAt(IntA, AValNo->def);
1062
1063 LLVM_DEBUG(dbgs() << "\t\ttrimmed: " << IntA << '\n');
1064 ++numCommutes;
1065 return {true, ShrinkB};
1066}
1067
1068/// For copy B = A in BB2, if A is defined by A = B in BB0 which is a
1069/// predecessor of BB2, and if B is not redefined on the way from A = B
1070/// in BB0 to B = A in BB2, B = A in BB2 is partially redundant if the
1071/// execution goes through the path from BB0 to BB2. We may move B = A
1072/// to the predecessor without such reversed copy.
1073/// So we will transform the program from:
1074/// BB0:
1075/// A = B; BB1:
1076/// ... ...
1077/// / \ /
1078/// BB2:
1079/// ...
1080/// B = A;
1081///
1082/// to:
1083///
1084/// BB0: BB1:
1085/// A = B; ...
1086/// ... B = A;
1087/// / \ /
1088/// BB2:
1089/// ...
1090///
1091/// A special case is when BB0 and BB2 are the same BB which is the only
1092/// BB in a loop:
1093/// BB1:
1094/// ...
1095/// BB0/BB2: ----
1096/// B = A; |
1097/// ... |
1098/// A = B; |
1099/// |-------
1100/// |
1101/// We may hoist B = A from BB0/BB2 to BB1.
1102///
1103/// The major preconditions for correctness to remove such partial
1104/// redundancy include:
1105/// 1. A in B = A in BB2 is defined by a PHI in BB2, and one operand of
1106/// the PHI is defined by the reversed copy A = B in BB0.
1107/// 2. No B is referenced from the start of BB2 to B = A.
1108/// 3. No B is defined from A = B to the end of BB0.
1109/// 4. BB1 has only one successor.
1110///
1111/// 2 and 4 implicitly ensure B is not live at the end of BB1.
1112/// 4 guarantees BB2 is hotter than BB1, so we can only move a copy to a
1113/// colder place, which not only prevent endless loop, but also make sure
1114/// the movement of copy is beneficial.
1115bool RegisterCoalescer::removePartialRedundancy(const CoalescerPair &CP,
1116 MachineInstr &CopyMI) {
1117 assert(!CP.isPhys());
1118 if (!CopyMI.isFullCopy())
1119 return false;
1120
1121 MachineBasicBlock &MBB = *CopyMI.getParent();
1122 // If this block is the target of an invoke/inlineasm_br, moving the copy into
1123 // the predecessor is tricker, and we don't handle it.
1125 return false;
1126
1127 if (MBB.pred_size() != 2)
1128 return false;
1129
1130 LiveInterval &IntA =
1131 LIS->getInterval(CP.isFlipped() ? CP.getDstReg() : CP.getSrcReg());
1132 LiveInterval &IntB =
1133 LIS->getInterval(CP.isFlipped() ? CP.getSrcReg() : CP.getDstReg());
1134
1135 // A is defined by PHI at the entry of MBB.
1136 SlotIndex CopyIdx = LIS->getInstructionIndex(CopyMI).getRegSlot(true);
1137 VNInfo *AValNo = IntA.getVNInfoAt(CopyIdx);
1138 assert(AValNo && !AValNo->isUnused() && "COPY source not live");
1139 if (!AValNo->isPHIDef())
1140 return false;
1141
1142 // No B is referenced before CopyMI in MBB.
1143 if (IntB.overlaps(LIS->getMBBStartIdx(&MBB), CopyIdx))
1144 return false;
1145
1146 // MBB has two predecessors: one contains A = B so no copy will be inserted
1147 // for it. The other one will have a copy moved from MBB.
1148 bool FoundReverseCopy = false;
1149 MachineBasicBlock *CopyLeftBB = nullptr;
1150 for (MachineBasicBlock *Pred : MBB.predecessors()) {
1151 VNInfo *PVal = IntA.getVNInfoBefore(LIS->getMBBEndIdx(Pred));
1153 if (!DefMI || !DefMI->isFullCopy()) {
1154 CopyLeftBB = Pred;
1155 continue;
1156 }
1157 // Check DefMI is a reverse copy and it is in BB Pred.
1158 if (DefMI->getOperand(0).getReg() != IntA.reg() ||
1159 DefMI->getOperand(1).getReg() != IntB.reg() ||
1160 DefMI->getParent() != Pred) {
1161 CopyLeftBB = Pred;
1162 continue;
1163 }
1164 // If there is any other def of B after DefMI and before the end of Pred,
1165 // we need to keep the copy of B = A at the end of Pred if we remove
1166 // B = A from MBB.
1167 bool ValB_Changed = false;
1168 for (auto *VNI : IntB.valnos) {
1169 if (VNI->isUnused())
1170 continue;
1171 if (PVal->def < VNI->def && VNI->def < LIS->getMBBEndIdx(Pred)) {
1172 ValB_Changed = true;
1173 break;
1174 }
1175 }
1176 if (ValB_Changed) {
1177 CopyLeftBB = Pred;
1178 continue;
1179 }
1180 FoundReverseCopy = true;
1181 }
1182
1183 // If no reverse copy is found in predecessors, nothing to do.
1184 if (!FoundReverseCopy)
1185 return false;
1186
1187 // If CopyLeftBB is nullptr, it means every predecessor of MBB contains
1188 // reverse copy, CopyMI can be removed trivially if only IntA/IntB is updated.
1189 // If CopyLeftBB is not nullptr, move CopyMI from MBB to CopyLeftBB and
1190 // update IntA/IntB.
1191 //
1192 // If CopyLeftBB is not nullptr, ensure CopyLeftBB has a single succ so
1193 // MBB is hotter than CopyLeftBB.
1194 if (CopyLeftBB && CopyLeftBB->succ_size() > 1)
1195 return false;
1196
1197 // Now (almost sure it's) ok to move copy.
1198 if (CopyLeftBB) {
1199 // Position in CopyLeftBB where we should insert new copy.
1200 auto InsPos = CopyLeftBB->getFirstTerminator();
1201
1202 // Make sure that B isn't referenced in the terminators (if any) at the end
1203 // of the predecessor since we're about to insert a new definition of B
1204 // before them.
1205 if (InsPos != CopyLeftBB->end()) {
1206 SlotIndex InsPosIdx = LIS->getInstructionIndex(*InsPos).getRegSlot(true);
1207 if (IntB.overlaps(InsPosIdx, LIS->getMBBEndIdx(CopyLeftBB)))
1208 return false;
1209 }
1210
1211 LLVM_DEBUG(dbgs() << "\tremovePartialRedundancy: Move the copy to "
1212 << printMBBReference(*CopyLeftBB) << '\t' << CopyMI);
1213
1214 // Insert new copy to CopyLeftBB.
1215 MachineInstr *NewCopyMI = BuildMI(*CopyLeftBB, InsPos, CopyMI.getDebugLoc(),
1216 TII->get(TargetOpcode::COPY), IntB.reg())
1217 .addReg(IntA.reg());
1218 SlotIndex NewCopyIdx =
1219 LIS->InsertMachineInstrInMaps(*NewCopyMI).getRegSlot();
1220 IntB.createDeadDef(NewCopyIdx, LIS->getVNInfoAllocator());
1221 for (LiveInterval::SubRange &SR : IntB.subranges())
1222 SR.createDeadDef(NewCopyIdx, LIS->getVNInfoAllocator());
1223
1224 // If the newly created Instruction has an address of an instruction that
1225 // was deleted before (object recycled by the allocator) it needs to be
1226 // removed from the deleted list.
1227 ErasedInstrs.erase(NewCopyMI);
1228 } else {
1229 LLVM_DEBUG(dbgs() << "\tremovePartialRedundancy: Remove the copy from "
1230 << printMBBReference(MBB) << '\t' << CopyMI);
1231 }
1232
1233 const bool IsUndefCopy = CopyMI.getOperand(1).isUndef();
1234
1235 // Remove CopyMI.
1236 // Note: This is fine to remove the copy before updating the live-ranges.
1237 // While updating the live-ranges, we only look at slot indices and
1238 // never go back to the instruction.
1239 // Mark instructions as deleted.
1240 deleteInstr(&CopyMI);
1241
1242 // Update the liveness.
1243 SmallVector<SlotIndex, 8> EndPoints;
1244 VNInfo *BValNo = IntB.Query(CopyIdx).valueOutOrDead();
1245 LIS->pruneValue(*static_cast<LiveRange *>(&IntB), CopyIdx.getRegSlot(),
1246 &EndPoints);
1247 BValNo->markUnused();
1248
1249 if (IsUndefCopy) {
1250 // We're introducing an undef phi def, and need to set undef on any users of
1251 // the previously local def to avoid artifically extending the lifetime
1252 // through the block.
1253 for (MachineOperand &MO : MRI->use_nodbg_operands(IntB.reg())) {
1254 const MachineInstr &MI = *MO.getParent();
1255 SlotIndex UseIdx = LIS->getInstructionIndex(MI);
1256 if (!IntB.liveAt(UseIdx))
1257 MO.setIsUndef(true);
1258 }
1259 }
1260
1261 // Extend IntB to the EndPoints of its original live interval.
1262 LIS->extendToIndices(IntB, EndPoints);
1263
1264 // Now, do the same for its subranges.
1265 for (LiveInterval::SubRange &SR : IntB.subranges()) {
1266 EndPoints.clear();
1267 VNInfo *BValNo = SR.Query(CopyIdx).valueOutOrDead();
1268 assert(BValNo && "All sublanes should be live");
1269 LIS->pruneValue(SR, CopyIdx.getRegSlot(), &EndPoints);
1270 BValNo->markUnused();
1271 // We can have a situation where the result of the original copy is live,
1272 // but is immediately dead in this subrange, e.g. [336r,336d:0). That makes
1273 // the copy appear as an endpoint from pruneValue(), but we don't want it
1274 // to because the copy has been removed. We can go ahead and remove that
1275 // endpoint; there is no other situation here that there could be a use at
1276 // the same place as we know that the copy is a full copy.
1277 for (unsigned I = 0; I != EndPoints.size();) {
1278 if (SlotIndex::isSameInstr(EndPoints[I], CopyIdx)) {
1279 EndPoints[I] = EndPoints.back();
1280 EndPoints.pop_back();
1281 continue;
1282 }
1283 ++I;
1284 }
1286 IntB.computeSubRangeUndefs(Undefs, SR.LaneMask, *MRI,
1287 *LIS->getSlotIndexes());
1288 LIS->extendToIndices(SR, EndPoints, Undefs);
1289 }
1290 // If any dead defs were extended, truncate them.
1291 shrinkToUses(&IntB);
1292
1293 // Finally, update the live-range of IntA.
1294 shrinkToUses(&IntA);
1295 return true;
1296}
1297
1298bool RegisterCoalescer::reMaterializeDef(const CoalescerPair &CP,
1299 MachineInstr *CopyMI,
1300 bool &IsDefCopy) {
1301 IsDefCopy = false;
1302 Register SrcReg = CP.isFlipped() ? CP.getDstReg() : CP.getSrcReg();
1303 unsigned SrcIdx = CP.isFlipped() ? CP.getDstIdx() : CP.getSrcIdx();
1304 Register DstReg = CP.isFlipped() ? CP.getSrcReg() : CP.getDstReg();
1305 unsigned DstIdx = CP.isFlipped() ? CP.getSrcIdx() : CP.getDstIdx();
1306 if (SrcReg.isPhysical())
1307 return false;
1308
1309 LiveInterval &SrcInt = LIS->getInterval(SrcReg);
1310 SlotIndex CopyIdx = LIS->getInstructionIndex(*CopyMI);
1311 VNInfo *ValNo = SrcInt.Query(CopyIdx).valueIn();
1312 if (!ValNo)
1313 return false;
1314 if (ValNo->isPHIDef() || ValNo->isUnused())
1315 return false;
1317 if (!DefMI)
1318 return false;
1319 if (DefMI->isCopyLike()) {
1320 IsDefCopy = true;
1321 return false;
1322 }
1323 if (!TII->isAsCheapAsAMove(*DefMI))
1324 return false;
1325
1326 if (!TII->isReMaterializable(*DefMI))
1327 return false;
1328
1329 bool SawStore = false;
1330 if (!DefMI->isSafeToMove(SawStore))
1331 return false;
1332 const MCInstrDesc &MCID = DefMI->getDesc();
1333 if (MCID.getNumDefs() != 1)
1334 return false;
1335
1336 // If both SrcIdx and DstIdx are set, correct rematerialization would widen
1337 // the register substantially (beyond both source and dest size). This is bad
1338 // for performance since it can cascade through a function, introducing many
1339 // extra spills and fills (e.g. ARM can easily end up copying QQQQPR registers
1340 // around after a few subreg copies).
1341 if (SrcIdx && DstIdx)
1342 return false;
1343
1344 // Only support subregister destinations when the def is read-undef.
1345 MachineOperand &DstOperand = CopyMI->getOperand(0);
1346 Register CopyDstReg = DstOperand.getReg();
1347 if (DstOperand.getSubReg() && !DstOperand.isUndef())
1348 return false;
1349
1350 // In the physical register case, checking that the def is read-undef is not
1351 // enough. We're widening the def and need to avoid clobbering other live
1352 // values in the unused register pieces.
1353 //
1354 // TODO: Targets may support rewriting the rematerialized instruction to only
1355 // touch relevant lanes, in which case we don't need any liveness check.
1356 if (CopyDstReg.isPhysical() && CP.isPartial()) {
1357 for (MCRegUnit Unit : TRI->regunits(DstReg)) {
1358 // Ignore the register units we are writing anyway.
1359 if (is_contained(TRI->regunits(CopyDstReg), Unit))
1360 continue;
1361
1362 // Check if the other lanes we are defining are live at the
1363 // rematerialization point.
1364 LiveRange &LR = LIS->getRegUnit(Unit);
1365 if (LR.liveAt(CopyIdx))
1366 return false;
1367 }
1368 }
1369
1370 const unsigned DefSubIdx = DefMI->getOperand(0).getSubReg();
1371 const TargetRegisterClass *DefRC = TII->getRegClass(MCID, 0);
1372 if (!DefMI->isImplicitDef()) {
1373 if (DstReg.isPhysical()) {
1374 Register NewDstReg = DstReg;
1375
1376 unsigned NewDstIdx = TRI->composeSubRegIndices(CP.getSrcIdx(), DefSubIdx);
1377 if (NewDstIdx)
1378 NewDstReg = TRI->getSubReg(DstReg, NewDstIdx);
1379
1380 // Finally, make sure that the physical subregister that will be
1381 // constructed later is permitted for the instruction.
1382 if (!DefRC->contains(NewDstReg))
1383 return false;
1384 } else {
1385 // Theoretically, some stack frame reference could exist. Just make sure
1386 // it hasn't actually happened.
1387 assert(DstReg.isVirtual() &&
1388 "Only expect to deal with virtual or physical registers");
1389 }
1390 }
1391
1392 if (!VirtRegAuxInfo::allUsesAvailableAt(DefMI, CopyIdx, *LIS, *MRI, *TII))
1393 return false;
1394
1395 DebugLoc DL = CopyMI->getDebugLoc();
1396 MachineBasicBlock *MBB = CopyMI->getParent();
1398 std::next(MachineBasicBlock::iterator(CopyMI));
1399 LiveRangeEdit::Remat RM(ValNo);
1400 RM.OrigMI = DefMI;
1402 LiveRangeEdit Edit(&SrcInt, NewRegs, *MF, *LIS, nullptr, this);
1403 Edit.rematerializeAt(*MBB, MII, DstReg, RM, *TRI, false, SrcIdx, CopyMI);
1404 MachineInstr &NewMI = *std::prev(MII);
1405 NewMI.setDebugLoc(DL);
1406
1407 // In a situation like the following:
1408 // %0:subreg = instr ; DefMI, subreg = DstIdx
1409 // %1 = copy %0:subreg ; CopyMI, SrcIdx = 0
1410 // instead of widening %1 to the register class of %0 simply do:
1411 // %1 = instr
1412 const TargetRegisterClass *NewRC = CP.getNewRC();
1413 if (DstIdx != 0) {
1414 MachineOperand &DefMO = NewMI.getOperand(0);
1415 if (DefMO.getSubReg() == DstIdx) {
1416 assert(SrcIdx == 0 && CP.isFlipped() &&
1417 "Shouldn't have SrcIdx+DstIdx at this point");
1418 const TargetRegisterClass *DstRC = MRI->getRegClass(DstReg);
1419 const TargetRegisterClass *CommonRC =
1420 TRI->getCommonSubClass(DefRC, DstRC);
1421 if (CommonRC != nullptr) {
1422 NewRC = CommonRC;
1423
1424 // Instruction might contain "undef %0:subreg" as use operand:
1425 // %0:subreg = instr op_1, ..., op_N, undef %0:subreg, op_N+2, ...
1426 //
1427 // Need to check all operands.
1428 for (MachineOperand &MO : NewMI.operands()) {
1429 if (MO.isReg() && MO.getReg() == DstReg && MO.getSubReg() == DstIdx) {
1430 MO.setSubReg(0);
1431 }
1432 }
1433
1434 DstIdx = 0;
1435 DefMO.setIsUndef(false); // Only subregs can have def+undef.
1436 }
1437 }
1438 }
1439
1440 // CopyMI may have implicit operands, save them so that we can transfer them
1441 // over to the newly materialized instruction after CopyMI is removed.
1443 ImplicitOps.reserve(CopyMI->getNumOperands() -
1444 CopyMI->getDesc().getNumOperands());
1445 for (unsigned I = CopyMI->getDesc().getNumOperands(),
1446 E = CopyMI->getNumOperands();
1447 I != E; ++I) {
1448 MachineOperand &MO = CopyMI->getOperand(I);
1449 if (MO.isReg()) {
1450 assert(MO.isImplicit() &&
1451 "No explicit operands after implicit operands.");
1452 assert((MO.getReg().isPhysical() ||
1453 (MO.getSubReg() == 0 && MO.getReg() == DstOperand.getReg())) &&
1454 "unexpected implicit virtual register def");
1455 ImplicitOps.push_back(MO);
1456 }
1457 }
1458
1459 CopyMI->eraseFromParent();
1460 ErasedInstrs.insert(CopyMI);
1461
1462 // NewMI may have dead implicit defs (E.g. EFLAGS for MOV<bits>r0 on X86).
1463 // We need to remember these so we can add intervals once we insert
1464 // NewMI into SlotIndexes.
1465 //
1466 // We also expect to have tied implicit-defs of super registers originating
1467 // from SUBREG_TO_REG, such as:
1468 // $edi = MOV32r0 implicit-def dead $eflags, implicit-def $rdi
1469 // undef %0.sub_32bit = MOV32r0 implicit-def dead $eflags, implicit-def %0
1470 //
1471 // The implicit-def of the super register may have been reduced to
1472 // subregisters depending on the uses.
1474 for (unsigned i = NewMI.getDesc().getNumOperands(),
1475 e = NewMI.getNumOperands();
1476 i != e; ++i) {
1477 MachineOperand &MO = NewMI.getOperand(i);
1478 if (MO.isReg() && MO.isDef()) {
1479 assert(MO.isImplicit());
1480 if (MO.getReg().isPhysical()) {
1481 assert(MO.isImplicit() && MO.getReg().isPhysical() &&
1482 (MO.isDead() ||
1483 (DefSubIdx &&
1484 ((TRI->getSubReg(MO.getReg(), DefSubIdx) ==
1485 MCRegister((unsigned)NewMI.getOperand(0).getReg())) ||
1486 TRI->isSubRegisterEq(NewMI.getOperand(0).getReg(),
1487 MO.getReg())))));
1488 NewMIImplDefs.push_back({i, MO.getReg()});
1489 } else {
1490 assert(MO.getReg() == NewMI.getOperand(0).getReg());
1491
1492 // We're only expecting another def of the main output, so the range
1493 // should get updated with the regular output range.
1494 //
1495 // FIXME: The range updating below probably needs updating to look at
1496 // the super register if subranges are tracked.
1497 assert(!MRI->shouldTrackSubRegLiveness(DstReg) &&
1498 "subrange update for implicit-def of super register may not be "
1499 "properly handled");
1500 }
1501 }
1502 }
1503
1504 if (DstReg.isVirtual()) {
1505 unsigned NewIdx = NewMI.getOperand(0).getSubReg();
1506
1507 if (DefRC != nullptr) {
1508 if (NewIdx)
1509 NewRC = TRI->getMatchingSuperRegClass(NewRC, DefRC, NewIdx);
1510 else
1511 NewRC = TRI->getCommonSubClass(NewRC, DefRC);
1512 assert(NewRC && "subreg chosen for remat incompatible with instruction");
1513 }
1514
1515 // Remap subranges to new lanemask and change register class.
1516 LiveInterval &DstInt = LIS->getInterval(DstReg);
1517 for (LiveInterval::SubRange &SR : DstInt.subranges()) {
1518 SR.LaneMask = TRI->composeSubRegIndexLaneMask(DstIdx, SR.LaneMask);
1519 }
1520 MRI->setRegClass(DstReg, NewRC);
1521
1522 // Update machine operands and add flags.
1523 updateRegDefsUses(DstReg, DstReg, DstIdx);
1524 NewMI.getOperand(0).setSubReg(NewIdx);
1525 // updateRegDefUses can add an "undef" flag to the definition, since
1526 // it will replace DstReg with DstReg.DstIdx. If NewIdx is 0, make
1527 // sure that "undef" is not set.
1528 if (NewIdx == 0)
1529 NewMI.getOperand(0).setIsUndef(false);
1530
1531 // In a situation like the following:
1532 //
1533 // undef %2.subreg:reg = INST %1:reg ; DefMI (rematerializable),
1534 // ; Defines only some of lanes,
1535 // ; so DefSubIdx = NewIdx = subreg
1536 // %3:reg = COPY %2 ; Copy full reg
1537 // .... = SOMEINSTR %3:reg ; Use full reg
1538 //
1539 // there are no subranges for %3 so after rematerialization we need
1540 // to explicitly create them. Undefined subranges are removed later on.
1541 if (NewIdx && !DstInt.hasSubRanges() &&
1542 MRI->shouldTrackSubRegLiveness(DstReg)) {
1543 LaneBitmask FullMask = MRI->getMaxLaneMaskForVReg(DstReg);
1544 LaneBitmask UsedLanes = TRI->getSubRegIndexLaneMask(NewIdx);
1545 LaneBitmask UnusedLanes = FullMask & ~UsedLanes;
1547 DstInt.createSubRangeFrom(Alloc, UsedLanes, DstInt);
1548 DstInt.createSubRangeFrom(Alloc, UnusedLanes, DstInt);
1549 }
1550
1551 // Add dead subregister definitions if we are defining the whole register
1552 // but only part of it is live.
1553 // This could happen if the rematerialization instruction is rematerializing
1554 // more than actually is used in the register.
1555 // An example would be:
1556 // %1 = LOAD CONSTANTS 5, 8 ; Loading both 5 and 8 in different subregs
1557 // ; Copying only part of the register here, but the rest is undef.
1558 // %2:sub_16bit<def, read-undef> = COPY %1:sub_16bit
1559 // ==>
1560 // ; Materialize all the constants but only using one
1561 // %2 = LOAD_CONSTANTS 5, 8
1562 //
1563 // at this point for the part that wasn't defined before we could have
1564 // subranges missing the definition.
1565 if (NewIdx == 0 && DstInt.hasSubRanges()) {
1566 SlotIndex CurrIdx = LIS->getInstructionIndex(NewMI);
1567 SlotIndex DefIndex =
1568 CurrIdx.getRegSlot(NewMI.getOperand(0).isEarlyClobber());
1569 LaneBitmask MaxMask = MRI->getMaxLaneMaskForVReg(DstReg);
1571 for (LiveInterval::SubRange &SR : DstInt.subranges()) {
1572 if (!SR.liveAt(DefIndex))
1573 SR.createDeadDef(DefIndex, Alloc);
1574 MaxMask &= ~SR.LaneMask;
1575 }
1576 if (MaxMask.any()) {
1577 LiveInterval::SubRange *SR = DstInt.createSubRange(Alloc, MaxMask);
1578 SR->createDeadDef(DefIndex, Alloc);
1579 }
1580 }
1581
1582 // Make sure that the subrange for resultant undef is removed
1583 // For example:
1584 // %1:sub1<def,read-undef> = LOAD CONSTANT 1
1585 // %2 = COPY %1
1586 // ==>
1587 // %2:sub1<def, read-undef> = LOAD CONSTANT 1
1588 // ; Correct but need to remove the subrange for %2:sub0
1589 // ; as it is now undef
1590 if (NewIdx != 0 && DstInt.hasSubRanges()) {
1591 // The affected subregister segments can be removed.
1592 SlotIndex CurrIdx = LIS->getInstructionIndex(NewMI);
1593 LaneBitmask DstMask = TRI->getSubRegIndexLaneMask(NewIdx);
1594 bool UpdatedSubRanges = false;
1595 SlotIndex DefIndex =
1596 CurrIdx.getRegSlot(NewMI.getOperand(0).isEarlyClobber());
1598
1599 // Refine the subranges that are now defined by the remat.
1600 // This will split existing subranges if necessary.
1601 DstInt.refineSubRanges(
1602 Alloc, DstMask,
1603 [&DefIndex, &Alloc](LiveInterval::SubRange &SR) {
1604 // We know that this lane is defined by this instruction,
1605 // but at this point it might not be live because it was not defined
1606 // by the original instruction. This happens when the
1607 // rematerialization widens the defined register. Assign that lane a
1608 // dead def so that the interferences are properly modeled.
1609 if (!SR.liveAt(DefIndex))
1610 SR.createDeadDef(DefIndex, Alloc);
1611 },
1612 *LIS->getSlotIndexes(), *TRI);
1613
1614 for (LiveInterval::SubRange &SR : DstInt.subranges()) {
1615 if ((SR.LaneMask & DstMask).none()) {
1617 << "Removing undefined SubRange "
1618 << PrintLaneMask(SR.LaneMask) << " : " << SR << "\n");
1619
1620 if (VNInfo *RmValNo = SR.getVNInfoAt(CurrIdx.getRegSlot())) {
1621 // VNI is in ValNo - remove any segments in this SubRange that have
1622 // this ValNo
1623 SR.removeValNo(RmValNo);
1624 }
1625
1626 // We may not have a defined value at this point, but still need to
1627 // clear out any empty subranges tentatively created by
1628 // updateRegDefUses. The original subrange def may have only undefed
1629 // some lanes.
1630 UpdatedSubRanges = true;
1631 }
1632 }
1633 if (UpdatedSubRanges)
1634 DstInt.removeEmptySubRanges();
1635 }
1636 } else if (NewMI.getOperand(0).getReg() != CopyDstReg) {
1637 // The New instruction may be defining a sub-register of what's actually
1638 // been asked for. If so it must implicitly define the whole thing.
1639 assert(DstReg.isPhysical() &&
1640 "Only expect virtual or physical registers in remat");
1641
1642 // CopyDstReg is added as an implicit-def below. The remat may also define
1643 // units CopyDstReg does not cover; nothing uses those, so the def is dead.
1644 // If CopyDstReg covers every defined unit, the def is part of that live
1645 // value and must stay live.
1646 Register DefReg = NewMI.getOperand(0).getReg();
1647 if (any_of(TRI->regunits(DefReg.asMCReg()), [&](MCRegUnit Unit) {
1648 return !TRI->hasRegUnit(CopyDstReg, Unit);
1649 }))
1650 NewMI.getOperand(0).setIsDead(true);
1651
1652 bool HasDefMatchingCopy = false;
1653 for (auto [OpIndex, Reg] : NewMIImplDefs) {
1654 if (Reg != DstReg)
1655 continue;
1656 // Also, if CopyDstReg is a sub-register of DstReg (and it is defined), we
1657 // must mark DstReg as dead since it is not going to used as a result of
1658 // this remat.
1659 if (DstReg != CopyDstReg)
1660 NewMI.getOperand(OpIndex).setIsDead(true);
1661 else
1662 HasDefMatchingCopy = true;
1663 }
1664
1665 // If NewMI does not already have an implicit-def CopyDstReg add one now.
1666 if (!HasDefMatchingCopy)
1668 CopyDstReg, true /*IsDef*/, true /*IsImp*/, false /*IsKill*/));
1669
1670 // Record small dead def live-ranges for all the subregisters
1671 // of the destination register.
1672 // Otherwise, variables that live through may miss some
1673 // interferences, thus creating invalid allocation.
1674 // E.g., i386 code:
1675 // %1 = somedef ; %1 GR8
1676 // %2 = remat ; %2 GR32
1677 // CL = COPY %2.sub_8bit
1678 // = somedef %1 ; %1 GR8
1679 // =>
1680 // %1 = somedef ; %1 GR8
1681 // dead ECX = remat ; implicit-def CL
1682 // = somedef %1 ; %1 GR8
1683 // %1 will see the interferences with CL but not with CH since
1684 // no live-ranges would have been created for ECX.
1685 // Fix that!
1686 SlotIndex NewMIIdx = LIS->getInstructionIndex(NewMI);
1687 for (MCRegUnit Unit : TRI->regunits(NewMI.getOperand(0).getReg()))
1688 if (LiveRange *LR = LIS->getCachedRegUnit(Unit))
1689 LR->createDeadDef(NewMIIdx.getRegSlot(), LIS->getVNInfoAllocator());
1690 }
1691
1692 NewMI.setRegisterDefReadUndef(NewMI.getOperand(0).getReg());
1693
1694 // Transfer over implicit operands to the rematerialized instruction.
1695 for (MachineOperand &MO : ImplicitOps)
1696 NewMI.addOperand(MO);
1697
1698 SlotIndex NewMIIdx = LIS->getInstructionIndex(NewMI);
1699 for (Register Reg : make_second_range(NewMIImplDefs)) {
1700 for (MCRegUnit Unit : TRI->regunits(Reg.asMCReg()))
1701 if (LiveRange *LR = LIS->getCachedRegUnit(Unit))
1702 LR->createDeadDef(NewMIIdx.getRegSlot(), LIS->getVNInfoAllocator());
1703 }
1704
1705 LLVM_DEBUG(dbgs() << "Remat: " << NewMI);
1706 ++NumReMats;
1707
1708 // If the virtual SrcReg is completely eliminated, update all DBG_VALUEs
1709 // to describe DstReg instead.
1710 if (MRI->use_nodbg_empty(SrcReg)) {
1711 for (MachineOperand &UseMO :
1713 MachineInstr *UseMI = UseMO.getParent();
1714 if (UseMI->isDebugInstr()) {
1715 if (DstReg.isPhysical())
1716 UseMO.substPhysReg(DstReg, *TRI);
1717 else
1718 UseMO.setReg(DstReg);
1719 // Move the debug value directly after the def of the rematerialized
1720 // value in DstReg.
1721 MBB->splice(std::next(NewMI.getIterator()), UseMI->getParent(), UseMI);
1722 LLVM_DEBUG(dbgs() << "\t\tupdated: " << *UseMI);
1723 }
1724 }
1725 }
1726
1727 if (ToBeUpdated.count(SrcReg))
1728 return true;
1729
1730 unsigned NumCopyUses = 0;
1731 for (MachineOperand &UseMO : MRI->use_nodbg_operands(SrcReg)) {
1732 if (UseMO.getParent()->isCopyLike())
1733 NumCopyUses++;
1734 }
1735 if (NumCopyUses < LateRematUpdateThreshold) {
1736 // The source interval can become smaller because we removed a use.
1737 shrinkToUses(&SrcInt, &DeadDefs);
1738 if (!DeadDefs.empty())
1739 eliminateDeadDefs(&Edit);
1740 } else {
1741 ToBeUpdated.insert(SrcReg);
1742 }
1743 return true;
1744}
1745
1746MachineInstr *RegisterCoalescer::eliminateUndefCopy(MachineInstr *CopyMI) {
1747 // ProcessImplicitDefs may leave some copies of <undef> values, it only
1748 // removes local variables. When we have a copy like:
1749 //
1750 // %1 = COPY undef %2
1751 //
1752 // We delete the copy and remove the corresponding value number from %1.
1753 // Any uses of that value number are marked as <undef>.
1754
1755 // Note that we do not query CoalescerPair here but redo isMoveInstr as the
1756 // CoalescerPair may have a new register class with adjusted subreg indices
1757 // at this point.
1758 Register SrcReg, DstReg;
1759 unsigned SrcSubIdx = 0, DstSubIdx = 0;
1760 if (!isMoveInstr(*TRI, CopyMI, SrcReg, DstReg, SrcSubIdx, DstSubIdx))
1761 return nullptr;
1762
1763 SlotIndex Idx = LIS->getInstructionIndex(*CopyMI);
1764 const LiveInterval &SrcLI = LIS->getInterval(SrcReg);
1765 // CopyMI is undef iff SrcReg is not live before the instruction.
1766 if (SrcSubIdx != 0 && SrcLI.hasSubRanges()) {
1767 LaneBitmask SrcMask = TRI->getSubRegIndexLaneMask(SrcSubIdx);
1768 for (const LiveInterval::SubRange &SR : SrcLI.subranges()) {
1769 if ((SR.LaneMask & SrcMask).none())
1770 continue;
1771 if (SR.liveAt(Idx))
1772 return nullptr;
1773 }
1774 } else if (SrcLI.liveAt(Idx))
1775 return nullptr;
1776
1777 // If the undef copy defines a live-out value (i.e. an input to a PHI def),
1778 // then replace it with an IMPLICIT_DEF.
1779 LiveInterval &DstLI = LIS->getInterval(DstReg);
1780 SlotIndex RegIndex = Idx.getRegSlot();
1781 LiveRange::Segment *Seg = DstLI.getSegmentContaining(RegIndex);
1782 assert(Seg != nullptr && "No segment for defining instruction");
1783 VNInfo *V = DstLI.getVNInfoAt(Seg->end);
1784
1785 // The source interval may also have been on an undef use, in which case the
1786 // copy introduced a live value.
1787 if (((V && V->isPHIDef()) || (!V && !DstLI.liveAt(Idx)))) {
1788 for (unsigned i = CopyMI->getNumOperands(); i != 0; --i) {
1789 MachineOperand &MO = CopyMI->getOperand(i - 1);
1790 if (MO.isReg()) {
1791 if (MO.isUse())
1792 CopyMI->removeOperand(i - 1);
1793 } else {
1794 assert(MO.isImm() &&
1795 CopyMI->getOpcode() == TargetOpcode::SUBREG_TO_REG);
1796 CopyMI->removeOperand(i - 1);
1797 }
1798 }
1799
1800 CopyMI->setDesc(TII->get(TargetOpcode::IMPLICIT_DEF));
1801 LLVM_DEBUG(dbgs() << "\tReplaced copy of <undef> value with an "
1802 "implicit def\n");
1803 return CopyMI;
1804 }
1805
1806 // Remove any DstReg segments starting at the instruction.
1807 LLVM_DEBUG(dbgs() << "\tEliminating copy of <undef> value\n");
1808
1809 // Remove value or merge with previous one in case of a subregister def.
1810 if (VNInfo *PrevVNI = DstLI.getVNInfoAt(Idx)) {
1811 VNInfo *VNI = DstLI.getVNInfoAt(RegIndex);
1812 DstLI.MergeValueNumberInto(VNI, PrevVNI);
1813
1814 // The affected subregister segments can be removed.
1815 LaneBitmask DstMask = TRI->getSubRegIndexLaneMask(DstSubIdx);
1816 for (LiveInterval::SubRange &SR : DstLI.subranges()) {
1817 if ((SR.LaneMask & DstMask).none())
1818 continue;
1819
1820 VNInfo *SVNI = SR.getVNInfoAt(RegIndex);
1821 assert(SVNI != nullptr && SlotIndex::isSameInstr(SVNI->def, RegIndex));
1822 SR.removeValNo(SVNI);
1823 }
1824 DstLI.removeEmptySubRanges();
1825 } else
1826 LIS->removeVRegDefAt(DstLI, RegIndex);
1827
1828 // Mark uses as undef.
1829 for (MachineOperand &MO : MRI->reg_nodbg_operands(DstReg)) {
1830 if (MO.isDef() && !MO.getSubReg())
1831 continue;
1832 const MachineInstr &MI = *MO.getParent();
1833 SlotIndex UseIdx = LIS->getInstructionIndex(MI);
1834 LaneBitmask UseMask = TRI->getSubRegIndexLaneMask(MO.getSubReg());
1835 if (MO.isDef())
1836 UseMask = ~UseMask;
1837 bool isLive;
1838 if (!UseMask.all() && DstLI.hasSubRanges()) {
1839 isLive = false;
1840 for (const LiveInterval::SubRange &SR : DstLI.subranges()) {
1841 if ((SR.LaneMask & UseMask).none())
1842 continue;
1843 if (SR.liveAt(UseIdx)) {
1844 isLive = true;
1845 break;
1846 }
1847 }
1848 } else
1849 isLive = DstLI.liveAt(UseIdx);
1850 if (isLive)
1851 continue;
1852 MO.setIsUndef(true);
1853 LLVM_DEBUG(dbgs() << "\tnew undef: " << UseIdx << '\t' << MI);
1854 }
1855
1856 // A def of a subregister may be a use of the other subregisters, so
1857 // deleting a def of a subregister may also remove uses. Since CopyMI
1858 // is still part of the function (but about to be erased), mark all
1859 // defs of DstReg in it as <undef>, so that shrinkToUses would
1860 // ignore them.
1861 for (MachineOperand &MO : CopyMI->all_defs())
1862 if (MO.getReg() == DstReg)
1863 MO.setIsUndef(true);
1864 LIS->shrinkToUses(&DstLI);
1865
1866 return CopyMI;
1867}
1868
1869void RegisterCoalescer::addUndefFlag(const LiveInterval &Int, SlotIndex UseIdx,
1870 MachineOperand &MO, unsigned SubRegIdx) {
1871 LaneBitmask Mask = TRI->getSubRegIndexLaneMask(SubRegIdx);
1872 if (MO.isDef())
1873 Mask = ~Mask;
1874 bool IsUndef = true;
1875 for (const LiveInterval::SubRange &S : Int.subranges()) {
1876 if ((S.LaneMask & Mask).none())
1877 continue;
1878 if (S.liveAt(UseIdx)) {
1879 IsUndef = false;
1880 break;
1881 }
1882 }
1883 if (IsUndef) {
1884 MO.setIsUndef(true);
1885 // We found out some subregister use is actually reading an undefined
1886 // value. In some cases the whole vreg has become undefined at this
1887 // point so we have to potentially shrink the main range if the
1888 // use was ending a live segment there.
1889 LiveQueryResult Q = Int.Query(UseIdx);
1890 if (Q.valueOut() == nullptr)
1891 ShrinkMainRange = true;
1892 }
1893}
1894
1895void RegisterCoalescer::updateRegDefsUses(Register SrcReg, Register DstReg,
1896 unsigned SubIdx) {
1897 bool DstIsPhys = DstReg.isPhysical();
1898 LiveInterval *DstInt = DstIsPhys ? nullptr : &LIS->getInterval(DstReg);
1899
1900 if (DstInt && DstReg != SrcReg) {
1901 bool HasSubRanges = DstInt->hasSubRanges();
1902 for (MachineOperand &MO : MRI->reg_nodbg_operands(DstReg)) {
1903 if (MO.isUndef())
1904 continue;
1905 unsigned SubReg = MO.getSubReg();
1906 if (SubReg == 0 && MO.isDef())
1907 continue;
1908
1909 SlotIndex UseIdx =
1910 LIS->getInstructionIndex(*MO.getParent()).getRegSlot(true);
1911 if (HasSubRanges) {
1912 addUndefFlag(*DstInt, UseIdx, MO, SubReg);
1913 } else if (MO.isUse() && SubReg == 0 && !DstInt->liveAt(UseIdx)) {
1914 // A full-register use already referencing DstReg (not renamed from
1915 // SrcReg) may have no reaching def after the join if its feeding COPY
1916 // and erasable IMPLICIT_DEF were removed. Mark such uses undef; the
1917 // SrcReg rename loop below only visits SrcReg operands and will miss
1918 // these.
1919 MO.setIsUndef(true);
1920 }
1921 }
1922 }
1923
1926 E = MRI->reg_instr_end();
1927 I != E;) {
1928 MachineInstr *UseMI = &*(I++);
1929
1930 // Each instruction can only be rewritten once because sub-register
1931 // composition is not always idempotent. When SrcReg != DstReg, rewriting
1932 // the UseMI operands removes them from the SrcReg use-def chain, but when
1933 // SrcReg is DstReg we could encounter UseMI twice if it has multiple
1934 // operands mentioning the virtual register.
1935 if (SrcReg == DstReg && !Visited.insert(UseMI).second)
1936 continue;
1937
1939 bool Reads, Writes;
1940 std::tie(Reads, Writes) = UseMI->readsWritesVirtualRegister(SrcReg, &Ops);
1941
1942 // If SrcReg wasn't read, it may still be the case that DstReg is live-in
1943 // because SrcReg is a sub-register.
1944 if (DstInt && !Reads && SubIdx && !UseMI->isDebugInstr())
1945 Reads = DstInt->liveAt(LIS->getInstructionIndex(*UseMI));
1946
1947 // Replace SrcReg with DstReg in all UseMI operands.
1948 for (unsigned Op : Ops) {
1950
1951 // Adjust <undef> flags in case of sub-register joins. We don't want to
1952 // turn a full def into a read-modify-write sub-register def and vice
1953 // versa.
1954 if (SubIdx && MO.isDef())
1955 MO.setIsUndef(!Reads);
1956
1957 // A subreg use of a partially undef (super) register may be a complete
1958 // undef use now and then has to be marked that way.
1959 if (MO.isUse() && !MO.isUndef() && !DstIsPhys) {
1960 unsigned SubUseIdx = TRI->composeSubRegIndices(SubIdx, MO.getSubReg());
1961 if (SubUseIdx != 0 && MRI->shouldTrackSubRegLiveness(DstReg)) {
1962 if (!DstInt->hasSubRanges()) {
1964 LaneBitmask FullMask = MRI->getMaxLaneMaskForVReg(DstInt->reg());
1965 LaneBitmask UsedLanes = TRI->getSubRegIndexLaneMask(SubIdx);
1966 LaneBitmask UnusedLanes = FullMask & ~UsedLanes;
1967 DstInt->createSubRangeFrom(Allocator, UsedLanes, *DstInt);
1968 // The unused lanes are just empty live-ranges at this point.
1969 // It is the caller responsibility to set the proper
1970 // dead segments if there is an actual dead def of the
1971 // unused lanes. This may happen with rematerialization.
1972 DstInt->createSubRange(Allocator, UnusedLanes);
1973 }
1974 SlotIndex MIIdx = UseMI->isDebugInstr()
1976 : LIS->getInstructionIndex(*UseMI);
1977 SlotIndex UseIdx = MIIdx.getRegSlot(true);
1978 addUndefFlag(*DstInt, UseIdx, MO, SubUseIdx);
1979 }
1980 }
1981
1982 if (DstIsPhys)
1983 MO.substPhysReg(DstReg, *TRI);
1984 else
1985 MO.substVirtReg(DstReg, SubIdx, *TRI);
1986 }
1987
1988 LLVM_DEBUG({
1989 dbgs() << "\t\tupdated: ";
1990 if (!UseMI->isDebugInstr())
1991 dbgs() << LIS->getInstructionIndex(*UseMI) << "\t";
1992 dbgs() << *UseMI;
1993 });
1994 }
1995}
1996
1997bool RegisterCoalescer::canJoinPhys(const CoalescerPair &CP) {
1998 // Always join simple intervals that are defined by a single copy from a
1999 // reserved register. This doesn't increase register pressure, so it is
2000 // always beneficial.
2001 if (!MRI->isReserved(CP.getDstReg())) {
2002 LLVM_DEBUG(dbgs() << "\tCan only merge into reserved registers.\n");
2003 return false;
2004 }
2005
2006 LiveInterval &JoinVInt = LIS->getInterval(CP.getSrcReg());
2007 if (JoinVInt.containsOneValue())
2008 return true;
2009
2010 LLVM_DEBUG(
2011 dbgs() << "\tCannot join complex intervals into reserved register.\n");
2012 return false;
2013}
2014
2015bool RegisterCoalescer::copyValueUndefInPredecessors(
2017 for (const MachineBasicBlock *Pred : MBB->predecessors()) {
2018 SlotIndex PredEnd = LIS->getMBBEndIdx(Pred);
2019 if (VNInfo *V = S.getVNInfoAt(PredEnd.getPrevSlot())) {
2020 // If this is a self loop, we may be reading the same value.
2021 if (V->id != SLRQ.valueOutOrDead()->id)
2022 return false;
2023 }
2024 }
2025
2026 return true;
2027}
2028
2029void RegisterCoalescer::setUndefOnPrunedSubRegUses(LiveInterval &LI,
2030 Register Reg,
2031 LaneBitmask PrunedLanes) {
2032 // If we had other instructions in the segment reading the undef sublane
2033 // value, we need to mark them with undef.
2034 for (MachineOperand &MO : MRI->use_nodbg_operands(Reg)) {
2035 unsigned SubRegIdx = MO.getSubReg();
2036 if (SubRegIdx == 0 || MO.isUndef())
2037 continue;
2038
2039 LaneBitmask SubRegMask = TRI->getSubRegIndexLaneMask(SubRegIdx);
2040 SlotIndex Pos = LIS->getInstructionIndex(*MO.getParent());
2041 for (LiveInterval::SubRange &S : LI.subranges()) {
2042 if (!S.liveAt(Pos) && (PrunedLanes & SubRegMask).any()) {
2043 MO.setIsUndef();
2044 break;
2045 }
2046 }
2047 }
2048
2050
2051 // A def of a subregister may be a use of other register lanes. Replacing
2052 // such a def with a def of a different register will eliminate the use,
2053 // and may cause the recorded live range to be larger than the actual
2054 // liveness in the program IR.
2055 LIS->shrinkToUses(&LI);
2056}
2057
2058RegisterCoalescer::JoinResult RegisterCoalescer::joinCopy(
2059 MachineInstr *CopyMI,
2060 SmallPtrSetImpl<MachineInstr *> &CurrentErasedInstrs) {
2061 LLVM_DEBUG(dbgs() << LIS->getInstructionIndex(*CopyMI) << '\t' << *CopyMI);
2062
2063 CoalescerPair CP(*TRI);
2064 if (!CP.setRegisters(CopyMI)) {
2065 LLVM_DEBUG(dbgs() << "\tNot coalescable.\n");
2066 return JoinResult::Rejected;
2067 }
2068
2069 if (CP.getNewRC()) {
2070 if (RegClassInfo->getNumAllocatableRegs(CP.getNewRC()) == 0) {
2071 LLVM_DEBUG(dbgs() << "\tNo " << TRI->getRegClassName(CP.getNewRC())
2072 << "are available for allocation\n");
2073 return JoinResult::Rejected;
2074 }
2075
2076 auto SrcRC = MRI->getRegClass(CP.getSrcReg());
2077 auto DstRC = MRI->getRegClass(CP.getDstReg());
2078 unsigned SrcIdx = CP.getSrcIdx();
2079 unsigned DstIdx = CP.getDstIdx();
2080 if (CP.isFlipped()) {
2081 std::swap(SrcIdx, DstIdx);
2082 std::swap(SrcRC, DstRC);
2083 }
2084 if (!TRI->shouldCoalesce(CopyMI, SrcRC, SrcIdx, DstRC, DstIdx,
2085 CP.getNewRC(), *LIS)) {
2086 LLVM_DEBUG(dbgs() << "\tSubtarget bailed on coalescing.\n");
2087 return JoinResult::Rejected;
2088 }
2089 }
2090
2091 // Dead code elimination. This really should be handled by MachineDCE, but
2092 // sometimes dead copies slip through, and we can't generate invalid live
2093 // ranges.
2094 if (!CP.isPhys() && CopyMI->allDefsAreDead()) {
2095 LLVM_DEBUG(dbgs() << "\tCopy is dead.\n");
2096 DeadDefs.push_back(CopyMI);
2097 eliminateDeadDefs();
2098 return JoinResult::Joined;
2099 }
2100
2101 // Eliminate undefs.
2102 if (!CP.isPhys()) {
2103 // If this is an IMPLICIT_DEF, leave it alone, but don't try to coalesce.
2104 if (MachineInstr *UndefMI = eliminateUndefCopy(CopyMI)) {
2105 if (UndefMI->isImplicitDef())
2106 return JoinResult::Rejected;
2107 deleteInstr(CopyMI);
2108 return JoinResult::Rejected; // Not coalescable.
2109 }
2110 }
2111
2112 // Coalesced copies are normally removed immediately, but transformations
2113 // like removeCopyByCommutingDef() can inadvertently create identity copies.
2114 // When that happens, just join the values and remove the copy.
2115 if (CP.getSrcReg() == CP.getDstReg()) {
2116 LiveInterval &LI = LIS->getInterval(CP.getSrcReg());
2117 LLVM_DEBUG(dbgs() << "\tCopy already coalesced: " << LI << '\n');
2118 const SlotIndex CopyIdx = LIS->getInstructionIndex(*CopyMI);
2119 LiveQueryResult LRQ = LI.Query(CopyIdx);
2120 if (VNInfo *DefVNI = LRQ.valueDefined()) {
2121 VNInfo *ReadVNI = LRQ.valueIn();
2122 assert(ReadVNI && "No value before copy and no <undef> flag.");
2123 assert(ReadVNI != DefVNI && "Cannot read and define the same value.");
2124
2125 // Track incoming undef lanes we need to eliminate from the subrange.
2126 LaneBitmask PrunedLanes;
2127 MachineBasicBlock *MBB = CopyMI->getParent();
2128
2129 // Process subregister liveranges.
2130 for (LiveInterval::SubRange &S : LI.subranges()) {
2131 LiveQueryResult SLRQ = S.Query(CopyIdx);
2132 if (VNInfo *SDefVNI = SLRQ.valueDefined()) {
2133 if (VNInfo *SReadVNI = SLRQ.valueIn())
2134 SDefVNI = S.MergeValueNumberInto(SDefVNI, SReadVNI);
2135
2136 // If this copy introduced an undef subrange from an incoming value,
2137 // we need to eliminate the undef live in values from the subrange.
2138 if (copyValueUndefInPredecessors(S, MBB, SLRQ)) {
2139 LLVM_DEBUG(dbgs() << "Incoming sublane value is undef at copy\n");
2140 PrunedLanes |= S.LaneMask;
2141 S.removeValNo(SDefVNI);
2142 }
2143 }
2144 }
2145
2146 LI.MergeValueNumberInto(DefVNI, ReadVNI);
2147 if (PrunedLanes.any()) {
2148 LLVM_DEBUG(dbgs() << "Pruning undef incoming lanes: " << PrunedLanes
2149 << '\n');
2150 setUndefOnPrunedSubRegUses(LI, CP.getSrcReg(), PrunedLanes);
2151 }
2152
2153 LLVM_DEBUG(dbgs() << "\tMerged values: " << LI << '\n');
2154 }
2155 deleteInstr(CopyMI);
2156 return JoinResult::Joined;
2157 }
2158
2159 // Enforce policies.
2160 if (CP.isPhys()) {
2161 LLVM_DEBUG(dbgs() << "\tConsidering merging "
2162 << printReg(CP.getSrcReg(), TRI) << " with "
2163 << printReg(CP.getDstReg(), TRI, CP.getSrcIdx()) << '\n');
2164 if (!canJoinPhys(CP)) {
2165 // Before giving up coalescing, try rematerializing the source of
2166 // the copy instead if it is cheap.
2167 bool IsDefCopy = false;
2168 if (reMaterializeDef(CP, CopyMI, IsDefCopy))
2169 return JoinResult::Joined;
2170 if (IsDefCopy)
2171 return JoinResult::Deferred; // May be possible to coalesce later.
2172 return JoinResult::Rejected;
2173 }
2174 } else {
2175 // When possible, let DstReg be the larger interval.
2176 if (!CP.isPartial() && LIS->getInterval(CP.getSrcReg()).size() >
2177 LIS->getInterval(CP.getDstReg()).size())
2178 CP.flip();
2179
2180 LLVM_DEBUG({
2181 dbgs() << "\tConsidering merging to "
2182 << TRI->getRegClassName(CP.getNewRC()) << " with ";
2183 if (CP.getDstIdx() && CP.getSrcIdx())
2184 dbgs() << printReg(CP.getDstReg()) << " in "
2185 << TRI->getSubRegIndexName(CP.getDstIdx()) << " and "
2186 << printReg(CP.getSrcReg()) << " in "
2187 << TRI->getSubRegIndexName(CP.getSrcIdx()) << '\n';
2188 else
2189 dbgs() << printReg(CP.getSrcReg(), TRI) << " in "
2190 << printReg(CP.getDstReg(), TRI, CP.getSrcIdx()) << '\n';
2191 });
2192 }
2193
2194 ShrinkMask = LaneBitmask::getNone();
2195 ShrinkMainRange = false;
2196
2197 // Okay, attempt to join these two intervals. If one of the intervals being
2198 // joined is a physreg and the join succeeds, this method always canonicalizes
2199 // DstInt to be it. The output "SrcInt" will not have been modified, so we
2200 // can use this information below to update aliases.
2201 JoinResult Result = joinIntervals(CP);
2202 if (Result != JoinResult::Joined) {
2203 // Coalescing failed.
2204
2205 // Try rematerializing the definition of the source if it is cheap.
2206 bool IsDefCopy = false;
2207 if (reMaterializeDef(CP, CopyMI, IsDefCopy))
2208 return JoinResult::Joined;
2209
2210 // If we can eliminate the copy without merging the live segments, do so
2211 // now.
2212 if (!CP.isPartial() && !CP.isPhys()) {
2213 bool Changed = adjustCopiesBackFrom(CP, CopyMI);
2214 bool Shrink = false;
2215 if (!Changed)
2216 std::tie(Changed, Shrink) = removeCopyByCommutingDef(CP, CopyMI);
2217 if (Changed) {
2218 deleteInstr(CopyMI);
2219 if (Shrink) {
2220 Register DstReg = CP.isFlipped() ? CP.getSrcReg() : CP.getDstReg();
2221 LiveInterval &DstLI = LIS->getInterval(DstReg);
2222 shrinkToUses(&DstLI);
2223 LLVM_DEBUG(dbgs() << "\t\tshrunk: " << DstLI << '\n');
2224 }
2225 LLVM_DEBUG(dbgs() << "\tTrivial!\n");
2226 return JoinResult::Joined;
2227 }
2228 }
2229
2230 // Try and see if we can partially eliminate the copy by moving the copy to
2231 // its predecessor.
2232 if (!CP.isPartial() && !CP.isPhys())
2233 if (removePartialRedundancy(CP, *CopyMI))
2234 return JoinResult::Joined;
2235
2236 // Otherwise, we are unable to join the intervals.
2237 LLVM_DEBUG(dbgs() << "\tInterference!\n");
2238 // A high-cost interval is already too expensive to retry. Keeping the copy
2239 // in WorkList would make every subsequent successful join rescan it again,
2240 // which can dominate compile time.
2241 if (Result == JoinResult::Deferred)
2242 LLVM_DEBUG(dbgs() << "\tWill retry later.\n");
2243 return Result;
2244 }
2245
2246 // Coalescing to a virtual register that is of a sub-register class of the
2247 // other. Make sure the resulting register is set to the right register class.
2248 if (CP.isCrossClass()) {
2249 ++numCrossRCs;
2250 MRI->setRegClass(CP.getDstReg(), CP.getNewRC());
2251 }
2252
2253 // Removing sub-register copies can ease the register class constraints.
2254 // Make sure we attempt to inflate the register class of DstReg.
2255 if (!CP.isPhys() && RegClassInfo->isProperSubClass(CP.getNewRC()))
2256 InflateRegs.push_back(CP.getDstReg());
2257
2258 // CopyMI has been erased by joinIntervals at this point. Remove it from
2259 // ErasedInstrs since copyCoalesceWorkList() won't add a successful join back
2260 // to the work list. This keeps ErasedInstrs from growing needlessly.
2261 if (ErasedInstrs.erase(CopyMI))
2262 // But we may encounter the instruction again in this iteration.
2263 CurrentErasedInstrs.insert(CopyMI);
2264
2265 // Rewrite all SrcReg operands to DstReg.
2266 // Also update DstReg operands to include DstIdx if it is set.
2267 if (CP.getDstIdx())
2268 updateRegDefsUses(CP.getDstReg(), CP.getDstReg(), CP.getDstIdx());
2269 updateRegDefsUses(CP.getSrcReg(), CP.getDstReg(), CP.getSrcIdx());
2270
2271 // Shrink subregister ranges if necessary.
2272 if (ShrinkMask.any()) {
2273 LiveInterval &LI = LIS->getInterval(CP.getDstReg());
2274 for (LiveInterval::SubRange &S : LI.subranges()) {
2275 if ((S.LaneMask & ShrinkMask).none())
2276 continue;
2277 LLVM_DEBUG(dbgs() << "Shrink LaneUses (Lane " << PrintLaneMask(S.LaneMask)
2278 << ")\n");
2279 LIS->shrinkToUses(S, LI.reg());
2280 ShrinkMainRange = true;
2281 }
2283 }
2284
2285 // CP.getSrcReg()'s live interval has been merged into CP.getDstReg's live
2286 // interval. Since CP.getSrcReg() is in ToBeUpdated set and its live interval
2287 // is not up-to-date, need to update the merged live interval here.
2288 if (ToBeUpdated.count(CP.getSrcReg()))
2289 ShrinkMainRange = true;
2290
2291 if (ShrinkMainRange) {
2292 LiveInterval &LI = LIS->getInterval(CP.getDstReg());
2293 shrinkToUses(&LI);
2294 }
2295
2296 // SrcReg is guaranteed to be the register whose live interval that is
2297 // being merged.
2298 LIS->removeInterval(CP.getSrcReg());
2299
2300 // Update regalloc hint.
2301 TRI->updateRegAllocHint(CP.getSrcReg(), CP.getDstReg(), *MF);
2302
2303 LLVM_DEBUG({
2304 dbgs() << "\tSuccess: " << printReg(CP.getSrcReg(), TRI, CP.getSrcIdx())
2305 << " -> " << printReg(CP.getDstReg(), TRI, CP.getDstIdx()) << '\n';
2306 dbgs() << "\tResult = ";
2307 if (CP.isPhys())
2308 dbgs() << printReg(CP.getDstReg(), TRI);
2309 else
2310 dbgs() << LIS->getInterval(CP.getDstReg());
2311 dbgs() << '\n';
2312 });
2313
2314 ++numJoins;
2315 return JoinResult::Joined;
2316}
2317
2318bool RegisterCoalescer::joinReservedPhysReg(CoalescerPair &CP) {
2319 Register DstReg = CP.getDstReg();
2320 Register SrcReg = CP.getSrcReg();
2321 assert(CP.isPhys() && "Must be a physreg copy");
2322 assert(MRI->isReserved(DstReg) && "Not a reserved register");
2323 LiveInterval &RHS = LIS->getInterval(SrcReg);
2324 LLVM_DEBUG(dbgs() << "\t\tRHS = " << RHS << '\n');
2325
2326 assert(RHS.containsOneValue() && "Invalid join with reserved register");
2327
2328 // Optimization for reserved registers like ESP. We can only merge with a
2329 // reserved physreg if RHS has a single value that is a copy of DstReg.
2330 // The live range of the reserved register will look like a set of dead defs
2331 // - we don't properly track the live range of reserved registers.
2332
2333 // Deny any overlapping intervals. This depends on all the reserved
2334 // register live ranges to look like dead defs.
2335 if (!MRI->isConstantPhysReg(DstReg)) {
2336 for (MCRegUnit Unit : TRI->regunits(DstReg)) {
2337 // Abort if not all the regunits are reserved.
2338 for (MCRegUnitRootIterator RI(Unit, TRI); RI.isValid(); ++RI) {
2339 if (!MRI->isReserved(*RI))
2340 return false;
2341 }
2342 if (RHS.overlaps(LIS->getRegUnit(Unit))) {
2343 LLVM_DEBUG(dbgs() << "\t\tInterference: " << printRegUnit(Unit, TRI)
2344 << '\n');
2345 return false;
2346 }
2347 }
2348
2349 // We must also check for overlaps with regmask clobbers.
2350 BitVector RegMaskUsable;
2351 if (LIS->checkRegMaskInterference(RHS, RegMaskUsable) &&
2352 !RegMaskUsable.test(DstReg.id())) {
2353 LLVM_DEBUG(dbgs() << "\t\tRegMask interference\n");
2354 return false;
2355 }
2356 }
2357
2358 // Skip any value computations, we are not adding new values to the
2359 // reserved register. Also skip merging the live ranges, the reserved
2360 // register live range doesn't need to be accurate as long as all the
2361 // defs are there.
2362
2363 // Delete the identity copy.
2364 MachineInstr *CopyMI;
2365 if (CP.isFlipped()) {
2366 // Physreg is copied into vreg
2367 // %y = COPY %physreg_x
2368 // ... //< no other def of %physreg_x here
2369 // use %y
2370 // =>
2371 // ...
2372 // use %physreg_x
2373 CopyMI = MRI->getVRegDef(SrcReg);
2374 deleteInstr(CopyMI);
2375 } else {
2376 // VReg is copied into physreg:
2377 // %y = def
2378 // ... //< no other def or use of %physreg_x here
2379 // %physreg_x = COPY %y
2380 // =>
2381 // %physreg_x = def
2382 // ...
2383 if (!MRI->hasOneNonDBGUse(SrcReg)) {
2384 LLVM_DEBUG(dbgs() << "\t\tMultiple vreg uses!\n");
2385 return false;
2386 }
2387
2388 if (!LIS->intervalIsInOneMBB(RHS)) {
2389 LLVM_DEBUG(dbgs() << "\t\tComplex control flow!\n");
2390 return false;
2391 }
2392
2393 MachineInstr &DestMI = *MRI->getVRegDef(SrcReg);
2394 CopyMI = &*MRI->use_instr_nodbg_begin(SrcReg);
2395 SlotIndex CopyRegIdx = LIS->getInstructionIndex(*CopyMI).getRegSlot();
2396 SlotIndex DestRegIdx = LIS->getInstructionIndex(DestMI).getRegSlot();
2397
2398 if (!MRI->isConstantPhysReg(DstReg)) {
2399 // We checked above that there are no interfering defs of the physical
2400 // register. However, for this case, where we intend to move up the def of
2401 // the physical register, we also need to check for interfering uses.
2402 SlotIndexes *Indexes = LIS->getSlotIndexes();
2403 for (SlotIndex SI = Indexes->getNextNonNullIndex(DestRegIdx);
2404 SI != CopyRegIdx; SI = Indexes->getNextNonNullIndex(SI)) {
2406 if (MI->readsRegister(DstReg, TRI)) {
2407 LLVM_DEBUG(dbgs() << "\t\tInterference (read): " << *MI);
2408 return false;
2409 }
2410 }
2411 }
2412
2413 // We're going to remove the copy which defines a physical reserved
2414 // register, so remove its valno, etc.
2415 LLVM_DEBUG(dbgs() << "\t\tRemoving phys reg def of "
2416 << printReg(DstReg, TRI) << " at " << CopyRegIdx << "\n");
2417
2418 LIS->removePhysRegDefAt(DstReg.asMCReg(), CopyRegIdx);
2419 deleteInstr(CopyMI);
2420
2421 // Create a new dead def at the new def location.
2422 for (MCRegUnit Unit : TRI->regunits(DstReg)) {
2423 LiveRange &LR = LIS->getRegUnit(Unit);
2424 LR.createDeadDef(DestRegIdx, LIS->getVNInfoAllocator());
2425 }
2426 }
2427
2428 // We don't track kills for reserved registers.
2429 MRI->clearKillFlags(CP.getSrcReg());
2430
2431 return true;
2432}
2433
2434//===----------------------------------------------------------------------===//
2435// Interference checking and interval joining
2436//===----------------------------------------------------------------------===//
2437//
2438// In the easiest case, the two live ranges being joined are disjoint, and
2439// there is no interference to consider. It is quite common, though, to have
2440// overlapping live ranges, and we need to check if the interference can be
2441// resolved.
2442//
2443// The live range of a single SSA value forms a sub-tree of the dominator tree.
2444// This means that two SSA values overlap if and only if the def of one value
2445// is contained in the live range of the other value. As a special case, the
2446// overlapping values can be defined at the same index.
2447//
2448// The interference from an overlapping def can be resolved in these cases:
2449//
2450// 1. Coalescable copies. The value is defined by a copy that would become an
2451// identity copy after joining SrcReg and DstReg. The copy instruction will
2452// be removed, and the value will be merged with the source value.
2453//
2454// There can be several copies back and forth, causing many values to be
2455// merged into one. We compute a list of ultimate values in the joined live
2456// range as well as a mappings from the old value numbers.
2457//
2458// 2. IMPLICIT_DEF. This instruction is only inserted to ensure all PHI
2459// predecessors have a live out value. It doesn't cause real interference,
2460// and can be merged into the value it overlaps. Like a coalescable copy, it
2461// can be erased after joining.
2462//
2463// 3. Copy of external value. The overlapping def may be a copy of a value that
2464// is already in the other register. This is like a coalescable copy, but
2465// the live range of the source register must be trimmed after erasing the
2466// copy instruction:
2467//
2468// %src = COPY %ext
2469// %dst = COPY %ext <-- Remove this COPY, trim the live range of %ext.
2470//
2471// 4. Clobbering undefined lanes. Vector registers are sometimes built by
2472// defining one lane at a time:
2473//
2474// %dst:ssub0<def,read-undef> = FOO
2475// %src = BAR
2476// %dst:ssub1 = COPY %src
2477//
2478// The live range of %src overlaps the %dst value defined by FOO, but
2479// merging %src into %dst:ssub1 is only going to clobber the ssub1 lane
2480// which was undef anyway.
2481//
2482// The value mapping is more complicated in this case. The final live range
2483// will have different value numbers for both FOO and BAR, but there is no
2484// simple mapping from old to new values. It may even be necessary to add
2485// new PHI values.
2486//
2487// 5. Clobbering dead lanes. A def may clobber a lane of a vector register that
2488// is live, but never read. This can happen because we don't compute
2489// individual live ranges per lane.
2490//
2491// %dst = FOO
2492// %src = BAR
2493// %dst:ssub1 = COPY %src
2494//
2495// This kind of interference is only resolved locally. If the clobbered
2496// lane value escapes the block, the join is aborted.
2497
2498namespace {
2499
2500/// Track information about values in a single virtual register about to be
2501/// joined. Objects of this class are always created in pairs - one for each
2502/// side of the CoalescerPair (or one for each lane of a side of the coalescer
2503/// pair)
2504class JoinVals {
2505 /// Live range we work on.
2506 LiveRange &LR;
2507
2508 /// (Main) register we work on.
2509 const Register Reg;
2510
2511 /// Reg (and therefore the values in this liverange) will end up as
2512 /// subregister SubIdx in the coalesced register. Either CP.DstIdx or
2513 /// CP.SrcIdx.
2514 const unsigned SubIdx;
2515
2516 /// The LaneMask that this liverange will occupy the coalesced register. May
2517 /// be smaller than the lanemask produced by SubIdx when merging subranges.
2518 const LaneBitmask LaneMask;
2519
2520 /// This is true when joining sub register ranges, false when joining main
2521 /// ranges.
2522 const bool SubRangeJoin;
2523
2524 /// Whether the current LiveInterval tracks subregister liveness.
2525 const bool TrackSubRegLiveness;
2526
2527 /// Values that will be present in the final live range.
2528 SmallVectorImpl<VNInfo *> &NewVNInfo;
2529
2530 const CoalescerPair &CP;
2531 LiveIntervals *LIS;
2532 SlotIndexes *Indexes;
2533 const TargetRegisterInfo *TRI;
2534
2535 /// Value number assignments. Maps value numbers in LI to entries in
2536 /// NewVNInfo. This is suitable for passing to LiveInterval::join().
2537 SmallVector<int, 8> Assignments;
2538
2539public:
2540 /// Conflict resolution for overlapping values.
2541 enum ConflictResolution {
2542 /// No overlap, simply keep this value.
2543 CR_Keep,
2544
2545 /// Merge this value into OtherVNI and erase the defining instruction.
2546 /// Used for IMPLICIT_DEF, coalescable copies, and copies from external
2547 /// values.
2548 CR_Erase,
2549
2550 /// Merge this value into OtherVNI but keep the defining instruction.
2551 /// This is for the special case where OtherVNI is defined by the same
2552 /// instruction.
2553 CR_Merge,
2554
2555 /// Keep this value, and have it replace OtherVNI where possible. This
2556 /// complicates value mapping since OtherVNI maps to two different values
2557 /// before and after this def.
2558 /// Used when clobbering undefined or dead lanes.
2559 CR_Replace,
2560
2561 /// Unresolved conflict. Visit later when all values have been mapped.
2562 CR_Unresolved,
2563
2564 /// Unresolvable conflict. Abort the join.
2565 CR_Impossible
2566 };
2567
2568private:
2569 /// Per-value info for LI. The lane bit masks are all relative to the final
2570 /// joined register, so they can be compared directly between SrcReg and
2571 /// DstReg.
2572 struct Val {
2573 ConflictResolution Resolution = CR_Keep;
2574
2575 /// Lanes written by this def, 0 for unanalyzed values.
2576 LaneBitmask WriteLanes;
2577
2578 /// Lanes with defined values in this register. Other lanes are undef and
2579 /// safe to clobber.
2580 LaneBitmask ValidLanes;
2581
2582 /// Value in LI being redefined by this def.
2583 VNInfo *RedefVNI = nullptr;
2584
2585 /// Value in the other live range that overlaps this def, if any.
2586 VNInfo *OtherVNI = nullptr;
2587
2588 /// Is this value an IMPLICIT_DEF that can be erased?
2589 ///
2590 /// IMPLICIT_DEF values should only exist at the end of a basic block that
2591 /// is a predecessor to a phi-value. These IMPLICIT_DEF instructions can be
2592 /// safely erased if they are overlapping a live value in the other live
2593 /// interval.
2594 ///
2595 /// Weird control flow graphs and incomplete PHI handling in
2596 /// ProcessImplicitDefs can very rarely create IMPLICIT_DEF values with
2597 /// longer live ranges. Such IMPLICIT_DEF values should be treated like
2598 /// normal values.
2599 bool ErasableImplicitDef = false;
2600
2601 /// True when the live range of this value will be pruned because of an
2602 /// overlapping CR_Replace value in the other live range.
2603 bool Pruned = false;
2604
2605 /// True once Pruned above has been computed.
2606 bool PrunedComputed = false;
2607
2608 /// True if this value is determined to be identical to OtherVNI
2609 /// (in valuesIdentical). This is used with CR_Erase where the erased
2610 /// copy is redundant, i.e. the source value is already the same as
2611 /// the destination. In such cases the subranges need to be updated
2612 /// properly. See comment at pruneSubRegValues for more info.
2613 bool Identical = false;
2614
2615 Val() = default;
2616
2617 bool isAnalyzed() const { return WriteLanes.any(); }
2618
2619 /// Mark this value as an IMPLICIT_DEF which must be kept as if it were an
2620 /// ordinary value.
2621 void mustKeepImplicitDef(const TargetRegisterInfo &TRI,
2622 const MachineInstr &ImpDef) {
2623 assert(ImpDef.isImplicitDef());
2624 ErasableImplicitDef = false;
2625 ValidLanes |=
2626 TRI.getSubRegIndexLaneMask(ImpDef.getOperand(0).getSubReg());
2627 }
2628 };
2629
2630 /// One entry per value number in LI.
2632
2633 /// Compute the bitmask of lanes actually written by DefMI.
2634 /// Set Redef if there are any partial register definitions that depend on the
2635 /// previous value of the register.
2636 LaneBitmask computeWriteLanes(const MachineInstr *DefMI, bool &Redef) const;
2637
2638 /// Find the ultimate value that VNI was copied from.
2639 std::pair<const VNInfo *, Register> followCopyChain(const VNInfo *VNI) const;
2640
2641 bool valuesIdentical(VNInfo *Value0, VNInfo *Value1,
2642 const JoinVals &Other) const;
2643
2644 /// Analyze ValNo in this live range, and set all fields of Vals[ValNo].
2645 /// Return a conflict resolution when possible, but leave the hard cases as
2646 /// CR_Unresolved.
2647 /// Recursively calls computeAssignment() on this and Other, guaranteeing that
2648 /// both OtherVNI and RedefVNI have been analyzed and mapped before returning.
2649 /// The recursion always goes upwards in the dominator tree, making loops
2650 /// impossible.
2651 ConflictResolution analyzeValue(unsigned ValNo, JoinVals &Other);
2652
2653 /// Compute the value assignment for ValNo in RI.
2654 /// This may be called recursively by analyzeValue(), but never for a ValNo on
2655 /// the stack.
2656 void computeAssignment(unsigned ValNo, JoinVals &Other);
2657
2658 /// Assuming ValNo is going to clobber some valid lanes in Other.LR, compute
2659 /// the extent of the tainted lanes in the block.
2660 ///
2661 /// Multiple values in Other.LR can be affected since partial redefinitions
2662 /// can preserve previously tainted lanes.
2663 ///
2664 /// 1 %dst = VLOAD <-- Define all lanes in %dst
2665 /// 2 %src = FOO <-- ValNo to be joined with %dst:ssub0
2666 /// 3 %dst:ssub1 = BAR <-- Partial redef doesn't clear taint in ssub0
2667 /// 4 %dst:ssub0 = COPY %src <-- Conflict resolved, ssub0 wasn't read
2668 ///
2669 /// For each ValNo in Other that is affected, add an (EndIndex, TaintedLanes)
2670 /// entry to TaintedVals.
2671 ///
2672 /// Returns false if the tainted lanes extend beyond the basic block.
2673 bool
2674 taintExtent(unsigned ValNo, LaneBitmask TaintedLanes, JoinVals &Other,
2675 SmallVectorImpl<std::pair<SlotIndex, LaneBitmask>> &TaintExtent);
2676
2677 /// Return true if MI uses any of the given Lanes from Reg.
2678 /// This does not include partial redefinitions of Reg.
2679 bool usesLanes(const MachineInstr &MI, Register, unsigned, LaneBitmask) const;
2680
2681 /// Determine if ValNo is a copy of a value number in LR or Other.LR that will
2682 /// be pruned:
2683 ///
2684 /// %dst = COPY %src
2685 /// %src = COPY %dst <-- This value to be pruned.
2686 /// %dst = COPY %src <-- This value is a copy of a pruned value.
2687 bool isPrunedValue(unsigned ValNo, JoinVals &Other);
2688
2689public:
2690 JoinVals(LiveRange &LR, Register Reg, unsigned SubIdx, LaneBitmask LaneMask,
2691 SmallVectorImpl<VNInfo *> &newVNInfo, const CoalescerPair &cp,
2692 LiveIntervals *lis, const TargetRegisterInfo *TRI, bool SubRangeJoin,
2693 bool TrackSubRegLiveness)
2694 : LR(LR), Reg(Reg), SubIdx(SubIdx), LaneMask(LaneMask),
2695 SubRangeJoin(SubRangeJoin), TrackSubRegLiveness(TrackSubRegLiveness),
2696 NewVNInfo(newVNInfo), CP(cp), LIS(lis), Indexes(LIS->getSlotIndexes()),
2697 TRI(TRI), Assignments(LR.getNumValNums(), -1),
2698 Vals(LR.getNumValNums()) {}
2699
2700 /// Analyze defs in LR and compute a value mapping in NewVNInfo.
2701 /// Returns false if any conflicts were impossible to resolve.
2702 bool mapValues(JoinVals &Other);
2703
2704 /// Try to resolve conflicts that require all values to be mapped.
2705 /// Returns false if any conflicts were impossible to resolve.
2706 bool resolveConflicts(JoinVals &Other);
2707
2708 /// Prune the live range of values in Other.LR where they would conflict with
2709 /// CR_Replace values in LR. Collect end points for restoring the live range
2710 /// after joining.
2711 void pruneValues(JoinVals &Other, SmallVectorImpl<SlotIndex> &EndPoints,
2712 bool changeInstrs);
2713
2714 /// Removes subranges starting at copies that get removed. This sometimes
2715 /// happens when undefined subranges are copied around. These ranges contain
2716 /// no useful information and can be removed.
2717 void pruneSubRegValues(LiveInterval &LI, LaneBitmask &ShrinkMask);
2718
2719 /// Pruning values in subranges can lead to removing segments in these
2720 /// subranges started by IMPLICIT_DEFs. The corresponding segments in
2721 /// the main range also need to be removed. This function will mark
2722 /// the corresponding values in the main range as pruned, so that
2723 /// eraseInstrs can do the final cleanup.
2724 /// The parameter @p LI must be the interval whose main range is the
2725 /// live range LR.
2726 void pruneMainSegments(LiveInterval &LI, bool &ShrinkMainRange);
2727
2728 /// Erase any machine instructions that have been coalesced away.
2729 /// Add erased instructions to ErasedInstrs.
2730 /// Add foreign virtual registers to ShrinkRegs if their live range ended at
2731 /// the erased instrs.
2732 void eraseInstrs(SmallPtrSetImpl<MachineInstr *> &ErasedInstrs,
2733 SmallVectorImpl<Register> &ShrinkRegs,
2734 LiveInterval *LI = nullptr);
2735
2736 /// Remove liverange defs at places where implicit defs will be removed.
2737 void removeImplicitDefs();
2738
2739 /// Get the value assignments suitable for passing to LiveInterval::join.
2740 const int *getAssignments() const { return Assignments.data(); }
2741
2742 /// Get the conflict resolution for a value number.
2743 ConflictResolution getResolution(unsigned Num) const {
2744 return Vals[Num].Resolution;
2745 }
2746};
2747
2748} // end anonymous namespace
2749
2750LaneBitmask JoinVals::computeWriteLanes(const MachineInstr *DefMI,
2751 bool &Redef) const {
2752 LaneBitmask L;
2753 for (const MachineOperand &MO : DefMI->all_defs()) {
2754 if (MO.getReg() != Reg)
2755 continue;
2756 L |= TRI->getSubRegIndexLaneMask(
2757 TRI->composeSubRegIndices(SubIdx, MO.getSubReg()));
2758 if (MO.readsReg())
2759 Redef = true;
2760 }
2761 return L;
2762}
2763
2764std::pair<const VNInfo *, Register>
2765JoinVals::followCopyChain(const VNInfo *VNI) const {
2766 Register TrackReg = Reg;
2767
2768 while (!VNI->isPHIDef()) {
2769 SlotIndex Def = VNI->def;
2770 MachineInstr *MI = Indexes->getInstructionFromIndex(Def);
2771 assert(MI && "No defining instruction");
2772 if (!MI->isFullCopy())
2773 return std::make_pair(VNI, TrackReg);
2774 Register SrcReg = MI->getOperand(1).getReg();
2775 if (!SrcReg.isVirtual())
2776 return std::make_pair(VNI, TrackReg);
2777
2778 const LiveInterval &LI = LIS->getInterval(SrcReg);
2779 const VNInfo *ValueIn;
2780 // No subrange involved.
2781 if (!SubRangeJoin || !LI.hasSubRanges()) {
2782 LiveQueryResult LRQ = LI.Query(Def);
2783 ValueIn = LRQ.valueIn();
2784 } else {
2785 // Query subranges. Ensure that all matching ones take us to the same def
2786 // (allowing some of them to be undef).
2787 ValueIn = nullptr;
2788 for (const LiveInterval::SubRange &S : LI.subranges()) {
2789 // Transform lanemask to a mask in the joined live interval.
2790 LaneBitmask SMask = TRI->composeSubRegIndexLaneMask(SubIdx, S.LaneMask);
2791 if ((SMask & LaneMask).none())
2792 continue;
2793 LiveQueryResult LRQ = S.Query(Def);
2794 if (!ValueIn) {
2795 ValueIn = LRQ.valueIn();
2796 continue;
2797 }
2798 if (LRQ.valueIn() && ValueIn != LRQ.valueIn())
2799 return std::make_pair(VNI, TrackReg);
2800 }
2801 }
2802 if (ValueIn == nullptr) {
2803 // Reaching an undefined value is legitimate, for example:
2804 //
2805 // 1 undef %0.sub1 = ... ;; %0.sub0 == undef
2806 // 2 %1 = COPY %0 ;; %1 is defined here.
2807 // 3 %0 = COPY %1 ;; Now %0.sub0 has a definition,
2808 // ;; but it's equivalent to "undef".
2809 return std::make_pair(nullptr, SrcReg);
2810 }
2811 VNI = ValueIn;
2812 TrackReg = SrcReg;
2813 }
2814 return std::make_pair(VNI, TrackReg);
2815}
2816
2817bool JoinVals::valuesIdentical(VNInfo *Value0, VNInfo *Value1,
2818 const JoinVals &Other) const {
2819 const VNInfo *Orig0;
2820 Register Reg0;
2821 std::tie(Orig0, Reg0) = followCopyChain(Value0);
2822 if (Orig0 == Value1 && Reg0 == Other.Reg)
2823 return true;
2824
2825 const VNInfo *Orig1;
2826 Register Reg1;
2827 std::tie(Orig1, Reg1) = Other.followCopyChain(Value1);
2828 // If both values are undefined, and the source registers are the same
2829 // register, the values are identical. Filter out cases where only one
2830 // value is defined.
2831 if (Orig0 == nullptr || Orig1 == nullptr)
2832 return Orig0 == Orig1 && Reg0 == Reg1;
2833
2834 // The values are equal if they are defined at the same place and use the
2835 // same register. Note that we cannot compare VNInfos directly as some of
2836 // them might be from a copy created in mergeSubRangeInto() while the other
2837 // is from the original LiveInterval.
2838 return Orig0->def == Orig1->def && Reg0 == Reg1;
2839}
2840
2841JoinVals::ConflictResolution JoinVals::analyzeValue(unsigned ValNo,
2842 JoinVals &Other) {
2843 Val &V = Vals[ValNo];
2844 assert(!V.isAnalyzed() && "Value has already been analyzed!");
2845 VNInfo *VNI = LR.getValNumInfo(ValNo);
2846 if (VNI->isUnused()) {
2847 V.WriteLanes = LaneBitmask::getAll();
2848 return CR_Keep;
2849 }
2850
2851 // Get the instruction defining this value, compute the lanes written.
2852 const MachineInstr *DefMI = nullptr;
2853 if (VNI->isPHIDef()) {
2854 // Conservatively assume that all lanes in a PHI are valid.
2855 LaneBitmask Lanes = SubRangeJoin ? LaneBitmask::getLane(0)
2856 : TRI->getSubRegIndexLaneMask(SubIdx);
2857 V.ValidLanes = V.WriteLanes = Lanes;
2858 } else {
2859 DefMI = Indexes->getInstructionFromIndex(VNI->def);
2860 assert(DefMI != nullptr);
2861 if (SubRangeJoin) {
2862 // We don't care about the lanes when joining subregister ranges.
2863 V.WriteLanes = V.ValidLanes = LaneBitmask::getLane(0);
2864 if (DefMI->isImplicitDef()) {
2865 V.ValidLanes = LaneBitmask::getNone();
2866 V.ErasableImplicitDef = true;
2867 }
2868 } else {
2869 bool Redef = false;
2870 V.ValidLanes = V.WriteLanes = computeWriteLanes(DefMI, Redef);
2871
2872 // If this is a read-modify-write instruction, there may be more valid
2873 // lanes than the ones written by this instruction.
2874 // This only covers partial redef operands. DefMI may have normal use
2875 // operands reading the register. They don't contribute valid lanes.
2876 //
2877 // This adds ssub1 to the set of valid lanes in %src:
2878 //
2879 // %src:ssub1 = FOO
2880 //
2881 // This leaves only ssub1 valid, making any other lanes undef:
2882 //
2883 // %src:ssub1<def,read-undef> = FOO %src:ssub2
2884 //
2885 // The <read-undef> flag on the def operand means that old lane values are
2886 // not important.
2887 if (Redef) {
2888 V.RedefVNI = LR.Query(VNI->def).valueIn();
2889 assert((TrackSubRegLiveness || V.RedefVNI) &&
2890 "Instruction is reading nonexistent value");
2891 if (V.RedefVNI != nullptr) {
2892 computeAssignment(V.RedefVNI->id, Other);
2893 V.ValidLanes |= Vals[V.RedefVNI->id].ValidLanes;
2894 }
2895 }
2896
2897 // An IMPLICIT_DEF writes undef values.
2898 if (DefMI->isImplicitDef()) {
2899 // We normally expect IMPLICIT_DEF values to be live only until the end
2900 // of their block. If the value is really live longer and gets pruned in
2901 // another block, this flag is cleared again.
2902 //
2903 // Clearing the valid lanes is deferred until it is sure this can be
2904 // erased.
2905 V.ErasableImplicitDef = true;
2906 }
2907 }
2908 }
2909
2910 // Find the value in Other that overlaps VNI->def, if any.
2911 LiveQueryResult OtherLRQ = Other.LR.Query(VNI->def);
2912
2913 // It is possible that both values are defined by the same instruction, or
2914 // the values are PHIs defined in the same block. When that happens, the two
2915 // values should be merged into one, but not into any preceding value.
2916 // The first value defined or visited gets CR_Keep, the other gets CR_Merge.
2917 if (VNInfo *OtherVNI = OtherLRQ.valueDefined()) {
2918 assert(SlotIndex::isSameInstr(VNI->def, OtherVNI->def) && "Broken LRQ");
2919
2920 // One value stays, the other is merged. Keep the earlier one, or the first
2921 // one we see.
2922 if (OtherVNI->def < VNI->def)
2923 Other.computeAssignment(OtherVNI->id, *this);
2924 else if (VNI->def < OtherVNI->def && OtherLRQ.valueIn()) {
2925 // This is an early-clobber def overlapping a live-in value in the other
2926 // register. Not mergeable.
2927 V.OtherVNI = OtherLRQ.valueIn();
2928 return CR_Impossible;
2929 }
2930 V.OtherVNI = OtherVNI;
2931 Val &OtherV = Other.Vals[OtherVNI->id];
2932 // Keep this value, check for conflicts when analyzing OtherVNI. Avoid
2933 // revisiting OtherVNI->id in JoinVals::computeAssignment() below before it
2934 // is assigned.
2935 if (!OtherV.isAnalyzed() || Other.Assignments[OtherVNI->id] == -1)
2936 return CR_Keep;
2937 // Both sides have been analyzed now.
2938 // Allow overlapping PHI values. Any real interference would show up in a
2939 // predecessor, the PHI itself can't introduce any conflicts.
2940 if (VNI->isPHIDef())
2941 return CR_Merge;
2942 if ((V.ValidLanes & OtherV.ValidLanes).any())
2943 // Overlapping lanes can't be resolved.
2944 return CR_Impossible;
2945 return CR_Merge;
2946 }
2947
2948 // No simultaneous def. Is Other live at the def?
2949 V.OtherVNI = OtherLRQ.valueIn();
2950 if (!V.OtherVNI)
2951 // No overlap, no conflict.
2952 return CR_Keep;
2953
2954 assert(!SlotIndex::isSameInstr(VNI->def, V.OtherVNI->def) && "Broken LRQ");
2955
2956 // We have overlapping values, or possibly a kill of Other.
2957 // Recursively compute assignments up the dominator tree.
2958 Other.computeAssignment(V.OtherVNI->id, *this);
2959 Val &OtherV = Other.Vals[V.OtherVNI->id];
2960
2961 if (OtherV.ErasableImplicitDef) {
2962 // Check if OtherV is an IMPLICIT_DEF that extends beyond its basic block.
2963 // This shouldn't normally happen, but ProcessImplicitDefs can leave such
2964 // IMPLICIT_DEF instructions behind, and there is nothing wrong with it
2965 // technically.
2966 //
2967 // When it happens, treat that IMPLICIT_DEF as a normal value, and don't try
2968 // to erase the IMPLICIT_DEF instruction.
2969 //
2970 // Additionally we must keep an IMPLICIT_DEF if we're redefining an incoming
2971 // value.
2972
2973 MachineInstr *OtherImpDef =
2974 Indexes->getInstructionFromIndex(V.OtherVNI->def);
2975 MachineBasicBlock *OtherMBB = OtherImpDef->getParent();
2976 if (DefMI &&
2977 (DefMI->getParent() != OtherMBB || LIS->isLiveInToMBB(LR, OtherMBB))) {
2978 LLVM_DEBUG(dbgs() << "IMPLICIT_DEF defined at " << V.OtherVNI->def
2979 << " extends into "
2981 << ", keeping it.\n");
2982 OtherV.mustKeepImplicitDef(*TRI, *OtherImpDef);
2983 } else if (OtherMBB->hasEHPadSuccessor()) {
2984 // If OtherV is defined in a basic block that has EH pad successors then
2985 // we get the same problem not just if OtherV is live beyond its basic
2986 // block, but beyond the last call instruction in its basic block. Handle
2987 // this case conservatively.
2988 LLVM_DEBUG(
2989 dbgs() << "IMPLICIT_DEF defined at " << V.OtherVNI->def
2990 << " may be live into EH pad successors, keeping it.\n");
2991 OtherV.mustKeepImplicitDef(*TRI, *OtherImpDef);
2992 } else {
2993 // We deferred clearing these lanes in case we needed to save them
2994 OtherV.ValidLanes &= ~OtherV.WriteLanes;
2995 }
2996 }
2997
2998 // Allow overlapping PHI values. Any real interference would show up in a
2999 // predecessor, the PHI itself can't introduce any conflicts.
3000 if (VNI->isPHIDef())
3001 return CR_Replace;
3002
3003 // Check for simple erasable conflicts.
3004 if (DefMI->isImplicitDef())
3005 return CR_Erase;
3006
3007 // Include the non-conflict where DefMI is a coalescable copy that kills
3008 // OtherVNI. We still want the copy erased and value numbers merged.
3009 if (CP.isCoalescable(DefMI)) {
3010 // Some of the lanes copied from OtherVNI may be undef, making them undef
3011 // here too.
3012 V.ValidLanes &= ~V.WriteLanes | OtherV.ValidLanes;
3013 return CR_Erase;
3014 }
3015
3016 // This may not be a real conflict if DefMI simply kills Other and defines
3017 // VNI.
3018 if (OtherLRQ.isKill() && OtherLRQ.endPoint() <= VNI->def)
3019 return CR_Keep;
3020
3021 // Handle the case where VNI and OtherVNI can be proven to be identical:
3022 //
3023 // %other = COPY %ext
3024 // %this = COPY %ext <-- Erase this copy
3025 //
3026 if (DefMI->isFullCopy() && !CP.isPartial() &&
3027 valuesIdentical(VNI, V.OtherVNI, Other)) {
3028 V.Identical = true;
3029 return CR_Erase;
3030 }
3031
3032 // The remaining checks apply to the lanes, which aren't tracked here. This
3033 // was already decided to be OK via the following CR_Replace condition.
3034 // CR_Replace.
3035 if (SubRangeJoin)
3036 return CR_Replace;
3037
3038 // If the lanes written by this instruction were all undef in OtherVNI, it is
3039 // still safe to join the live ranges. This can't be done with a simple value
3040 // mapping, though - OtherVNI will map to multiple values:
3041 //
3042 // 1 %dst:ssub0 = FOO <-- OtherVNI
3043 // 2 %src = BAR <-- VNI
3044 // 3 %dst:ssub1 = COPY killed %src <-- Eliminate this copy.
3045 // 4 BAZ killed %dst
3046 // 5 QUUX killed %src
3047 //
3048 // Here OtherVNI will map to itself in [1;2), but to VNI in [2;5). CR_Replace
3049 // handles this complex value mapping.
3050 if ((V.WriteLanes & OtherV.ValidLanes).none())
3051 return CR_Replace;
3052
3053 // If the other live range is killed by DefMI and the live ranges are still
3054 // overlapping, it must be because we're looking at an early clobber def:
3055 //
3056 // %dst<def,early-clobber> = ASM killed %src
3057 //
3058 // In this case, it is illegal to merge the two live ranges since the early
3059 // clobber def would clobber %src before it was read.
3060 if (OtherLRQ.isKill()) {
3061 // This case where the def doesn't overlap the kill is handled above.
3062 assert(VNI->def.isEarlyClobber() &&
3063 "Only early clobber defs can overlap a kill");
3064 return CR_Impossible;
3065 }
3066
3067 // VNI is clobbering live lanes in OtherVNI, but there is still the
3068 // possibility that no instructions actually read the clobbered lanes.
3069 // If we're clobbering all the lanes in OtherVNI, at least one must be read.
3070 // Otherwise Other.RI wouldn't be live here.
3071 if ((TRI->getSubRegIndexLaneMask(Other.SubIdx) & ~V.WriteLanes).none())
3072 return CR_Impossible;
3073
3074 if (TrackSubRegLiveness) {
3075 auto &OtherLI = LIS->getInterval(Other.Reg);
3076 // If OtherVNI does not have subranges, it means all the lanes of OtherVNI
3077 // share the same live range, so we just need to check whether they have
3078 // any conflict bit in their LaneMask.
3079 if (!OtherLI.hasSubRanges()) {
3080 LaneBitmask OtherMask = TRI->getSubRegIndexLaneMask(Other.SubIdx);
3081 return (OtherMask & V.WriteLanes).none() ? CR_Replace : CR_Impossible;
3082 }
3083
3084 // If we are clobbering some active lanes of OtherVNI at VNI->def, it is
3085 // impossible to resolve the conflict. Otherwise, we can just replace
3086 // OtherVNI because of no real conflict.
3087 for (LiveInterval::SubRange &OtherSR : OtherLI.subranges()) {
3088 LaneBitmask OtherMask =
3089 TRI->composeSubRegIndexLaneMask(Other.SubIdx, OtherSR.LaneMask);
3090 if ((OtherMask & V.WriteLanes).none())
3091 continue;
3092
3093 auto OtherSRQ = OtherSR.Query(VNI->def);
3094 if (OtherSRQ.valueIn() && OtherSRQ.endPoint() > VNI->def) {
3095 // VNI is clobbering some lanes of OtherVNI, they have real conflict.
3096 return CR_Impossible;
3097 }
3098 }
3099
3100 // VNI is NOT clobbering any lane of OtherVNI, just replace OtherVNI.
3101 return CR_Replace;
3102 }
3103
3104 // We need to verify that no instructions are reading the clobbered lanes.
3105 // To save compile time, we'll only check that locally. Don't allow the
3106 // tainted value to escape the basic block.
3107 MachineBasicBlock *MBB = Indexes->getMBBFromIndex(VNI->def);
3108 if (OtherLRQ.endPoint() >= Indexes->getMBBEndIdx(MBB))
3109 return CR_Impossible;
3110
3111 // There are still some things that could go wrong besides clobbered lanes
3112 // being read, for example OtherVNI may be only partially redefined in MBB,
3113 // and some clobbered lanes could escape the block. Save this analysis for
3114 // resolveConflicts() when all values have been mapped. We need to know
3115 // RedefVNI and WriteLanes for any later defs in MBB, and we can't compute
3116 // that now - the recursive analyzeValue() calls must go upwards in the
3117 // dominator tree.
3118 return CR_Unresolved;
3119}
3120
3121void JoinVals::computeAssignment(unsigned ValNo, JoinVals &Other) {
3122 Val &V = Vals[ValNo];
3123 if (V.isAnalyzed()) {
3124 // Recursion should always move up the dominator tree, so ValNo is not
3125 // supposed to reappear before it has been assigned.
3126 assert(Assignments[ValNo] != -1 && "Bad recursion?");
3127 return;
3128 }
3129 switch ((V.Resolution = analyzeValue(ValNo, Other))) {
3130 case CR_Erase:
3131 case CR_Merge:
3132 // Merge this ValNo into OtherVNI.
3133 assert(V.OtherVNI && "OtherVNI not assigned, can't merge.");
3134 assert(Other.Vals[V.OtherVNI->id].isAnalyzed() && "Missing recursion");
3135 Assignments[ValNo] = Other.Assignments[V.OtherVNI->id];
3136 LLVM_DEBUG(dbgs() << "\t\tmerge " << printReg(Reg) << ':' << ValNo << '@'
3137 << LR.getValNumInfo(ValNo)->def << " into "
3138 << printReg(Other.Reg) << ':' << V.OtherVNI->id << '@'
3139 << V.OtherVNI->def << " --> @"
3140 << NewVNInfo[Assignments[ValNo]]->def << '\n');
3141 break;
3142 case CR_Replace:
3143 case CR_Unresolved: {
3144 // The other value is going to be pruned if this join is successful.
3145 assert(V.OtherVNI && "OtherVNI not assigned, can't prune");
3146 Val &OtherV = Other.Vals[V.OtherVNI->id];
3147 OtherV.Pruned = true;
3148 [[fallthrough]];
3149 }
3150 default:
3151 // This value number needs to go in the final joined live range.
3152 Assignments[ValNo] = NewVNInfo.size();
3153 NewVNInfo.push_back(LR.getValNumInfo(ValNo));
3154 break;
3155 }
3156}
3157
3158bool JoinVals::mapValues(JoinVals &Other) {
3159 for (unsigned i = 0, e = LR.getNumValNums(); i != e; ++i) {
3160 computeAssignment(i, Other);
3161 if (Vals[i].Resolution == CR_Impossible) {
3162 LLVM_DEBUG(dbgs() << "\t\tinterference at " << printReg(Reg) << ':' << i
3163 << '@' << LR.getValNumInfo(i)->def << '\n');
3164 return false;
3165 }
3166 }
3167 return true;
3168}
3169
3170bool JoinVals::taintExtent(
3171 unsigned ValNo, LaneBitmask TaintedLanes, JoinVals &Other,
3172 SmallVectorImpl<std::pair<SlotIndex, LaneBitmask>> &TaintExtent) {
3173 VNInfo *VNI = LR.getValNumInfo(ValNo);
3174 MachineBasicBlock *MBB = Indexes->getMBBFromIndex(VNI->def);
3175 SlotIndex MBBEnd = Indexes->getMBBEndIdx(MBB);
3176
3177 // Scan Other.LR from VNI.def to MBBEnd.
3178 LiveInterval::iterator OtherI = Other.LR.find(VNI->def);
3179 assert(OtherI != Other.LR.end() && "No conflict?");
3180 do {
3181 // OtherI is pointing to a tainted value. Abort the join if the tainted
3182 // lanes escape the block.
3183 SlotIndex End = OtherI->end;
3184 if (End >= MBBEnd) {
3185 LLVM_DEBUG(dbgs() << "\t\ttaints global " << printReg(Other.Reg) << ':'
3186 << OtherI->valno->id << '@' << OtherI->start << '\n');
3187 return false;
3188 }
3189 LLVM_DEBUG(dbgs() << "\t\ttaints local " << printReg(Other.Reg) << ':'
3190 << OtherI->valno->id << '@' << OtherI->start << " to "
3191 << End << '\n');
3192 // A dead def is not a problem.
3193 if (End.isDead())
3194 break;
3195 TaintExtent.push_back(std::make_pair(End, TaintedLanes));
3196
3197 // Check for another def in the MBB.
3198 if (++OtherI == Other.LR.end() || OtherI->start >= MBBEnd)
3199 break;
3200
3201 // Lanes written by the new def are no longer tainted.
3202 const Val &OV = Other.Vals[OtherI->valno->id];
3203 TaintedLanes &= ~OV.WriteLanes;
3204 if (!OV.RedefVNI)
3205 break;
3206 } while (TaintedLanes.any());
3207 return true;
3208}
3209
3210bool JoinVals::usesLanes(const MachineInstr &MI, Register Reg, unsigned SubIdx,
3211 LaneBitmask Lanes) const {
3212 if (MI.isDebugOrPseudoInstr())
3213 return false;
3214 for (const MachineOperand &MO : MI.all_uses()) {
3215 if (MO.getReg() != Reg)
3216 continue;
3217 if (!MO.readsReg())
3218 continue;
3219 unsigned S = TRI->composeSubRegIndices(SubIdx, MO.getSubReg());
3220 if ((Lanes & TRI->getSubRegIndexLaneMask(S)).any())
3221 return true;
3222 }
3223 return false;
3224}
3225
3226bool JoinVals::resolveConflicts(JoinVals &Other) {
3227 for (unsigned i = 0, e = LR.getNumValNums(); i != e; ++i) {
3228 Val &V = Vals[i];
3229 assert(V.Resolution != CR_Impossible && "Unresolvable conflict");
3230 if (V.Resolution != CR_Unresolved)
3231 continue;
3232 LLVM_DEBUG(dbgs() << "\t\tconflict at " << printReg(Reg) << ':' << i << '@'
3233 << LR.getValNumInfo(i)->def << ' '
3234 << PrintLaneMask(LaneMask) << '\n');
3235 if (SubRangeJoin)
3236 return false;
3237
3238 ++NumLaneConflicts;
3239 assert(V.OtherVNI && "Inconsistent conflict resolution.");
3240 VNInfo *VNI = LR.getValNumInfo(i);
3241 const Val &OtherV = Other.Vals[V.OtherVNI->id];
3242
3243 // VNI is known to clobber some lanes in OtherVNI. If we go ahead with the
3244 // join, those lanes will be tainted with a wrong value. Get the extent of
3245 // the tainted lanes.
3246 LaneBitmask TaintedLanes = V.WriteLanes & OtherV.ValidLanes;
3248 if (!taintExtent(i, TaintedLanes, Other, TaintExtent))
3249 // Tainted lanes would extend beyond the basic block.
3250 return false;
3251
3252 assert(!TaintExtent.empty() && "There should be at least one conflict.");
3253
3254 // Now look at the instructions from VNI->def to TaintExtent (inclusive).
3255 MachineBasicBlock *MBB = Indexes->getMBBFromIndex(VNI->def);
3257 if (!VNI->isPHIDef()) {
3258 MI = Indexes->getInstructionFromIndex(VNI->def);
3259 if (!VNI->def.isEarlyClobber()) {
3260 // No need to check the instruction defining VNI for reads.
3261 ++MI;
3262 }
3263 }
3264 assert(!SlotIndex::isSameInstr(VNI->def, TaintExtent.front().first) &&
3265 "Interference ends on VNI->def. Should have been handled earlier");
3266 MachineInstr *LastMI =
3267 Indexes->getInstructionFromIndex(TaintExtent.front().first);
3268 assert(LastMI && "Range must end at a proper instruction");
3269 unsigned TaintNum = 0;
3270 while (true) {
3271 assert(MI != MBB->end() && "Bad LastMI");
3272 if (usesLanes(*MI, Other.Reg, Other.SubIdx, TaintedLanes)) {
3273 LLVM_DEBUG(dbgs() << "\t\ttainted lanes used by: " << *MI);
3274 return false;
3275 }
3276 // LastMI is the last instruction to use the current value.
3277 if (&*MI == LastMI) {
3278 if (++TaintNum == TaintExtent.size())
3279 break;
3280 LastMI = Indexes->getInstructionFromIndex(TaintExtent[TaintNum].first);
3281 assert(LastMI && "Range must end at a proper instruction");
3282 TaintedLanes = TaintExtent[TaintNum].second;
3283 }
3284 ++MI;
3285 }
3286
3287 // The tainted lanes are unused.
3288 V.Resolution = CR_Replace;
3289 ++NumLaneResolves;
3290 }
3291 return true;
3292}
3293
3294bool JoinVals::isPrunedValue(unsigned ValNo, JoinVals &Other) {
3295 Val &V = Vals[ValNo];
3296 if (V.Pruned || V.PrunedComputed)
3297 return V.Pruned;
3298
3299 if (V.Resolution != CR_Erase && V.Resolution != CR_Merge)
3300 return V.Pruned;
3301
3302 // Follow copies up the dominator tree and check if any intermediate value
3303 // has been pruned.
3304 V.PrunedComputed = true;
3305 V.Pruned = Other.isPrunedValue(V.OtherVNI->id, *this);
3306 return V.Pruned;
3307}
3308
3309void JoinVals::pruneValues(JoinVals &Other,
3310 SmallVectorImpl<SlotIndex> &EndPoints,
3311 bool changeInstrs) {
3312 for (unsigned i = 0, e = LR.getNumValNums(); i != e; ++i) {
3313 SlotIndex Def = LR.getValNumInfo(i)->def;
3314 switch (Vals[i].Resolution) {
3315 case CR_Keep:
3316 break;
3317 case CR_Replace: {
3318 // This value takes precedence over the value in Other.LR.
3319 LIS->pruneValue(Other.LR, Def, &EndPoints);
3320 // Check if we're replacing an IMPLICIT_DEF value. The IMPLICIT_DEF
3321 // instructions are only inserted to provide a live-out value for PHI
3322 // predecessors, so the instruction should simply go away once its value
3323 // has been replaced.
3324 Val &OtherV = Other.Vals[Vals[i].OtherVNI->id];
3325 bool EraseImpDef =
3326 OtherV.ErasableImplicitDef && OtherV.Resolution == CR_Keep;
3327 if (!Def.isBlock()) {
3328 if (changeInstrs) {
3329 // Remove <def,read-undef> flags. This def is now a partial redef.
3330 // Also remove dead flags since the joined live range will
3331 // continue past this instruction.
3332 for (MachineOperand &MO :
3333 mi_bundle_ops(*Indexes->getInstructionFromIndex(Def))) {
3334 if (MO.isReg() && MO.isDef() && MO.getReg() == Reg) {
3335 if (MO.getSubReg() != 0 && MO.isUndef() && !EraseImpDef)
3336 MO.setIsUndef(false);
3337 MO.setIsDead(false);
3338 }
3339 }
3340 }
3341 // This value will reach instructions below, but we need to make sure
3342 // the live range also reaches the instruction at Def.
3343 if (!EraseImpDef)
3344 EndPoints.push_back(Def);
3345 }
3346 LLVM_DEBUG(dbgs() << "\t\tpruned " << printReg(Other.Reg) << " at " << Def
3347 << ": " << Other.LR << '\n');
3348 break;
3349 }
3350 case CR_Erase:
3351 case CR_Merge:
3352 if (isPrunedValue(i, Other)) {
3353 // This value is ultimately a copy of a pruned value in LR or Other.LR.
3354 // We can no longer trust the value mapping computed by
3355 // computeAssignment(), the value that was originally copied could have
3356 // been replaced.
3357 Val &OtherV = Other.Vals[Vals[i].OtherVNI->id];
3358 bool EraseImpDef =
3359 OtherV.ErasableImplicitDef && OtherV.Resolution == CR_Keep;
3360 // If the source is an erasable IMPLICIT_DEF, the pruned endpoint is
3361 // the next def boundary, not a real use — discard it.
3362 LIS->pruneValue(LR, Def, EraseImpDef ? nullptr : &EndPoints);
3363 LLVM_DEBUG(dbgs() << "\t\tpruned all of " << printReg(Reg) << " at "
3364 << Def << ": " << LR << '\n');
3365 }
3366 break;
3367 case CR_Unresolved:
3368 case CR_Impossible:
3369 llvm_unreachable("Unresolved conflicts");
3370 }
3371 }
3372}
3373
3374// Check if the segment consists of a copied live-through value (i.e. the copy
3375// in the block only extended the liveness, of an undef value which we may need
3376// to handle).
3377static bool isLiveThrough(const LiveQueryResult Q) {
3378 return Q.valueIn() && Q.valueIn()->isPHIDef() && Q.valueIn() == Q.valueOut();
3379}
3380
3381/// Consider the following situation when coalescing the copy between
3382/// %31 and %45 at 800. (The vertical lines represent live range segments.)
3383///
3384/// Main range Subrange 0004 (sub2)
3385/// %31 %45 %31 %45
3386/// 544 %45 = COPY %28 + +
3387/// | v1 | v1
3388/// 560B bb.1: + +
3389/// 624 = %45.sub2 | v2 | v2
3390/// 800 %31 = COPY %45 + + + +
3391/// | v0 | v0
3392/// 816 %31.sub1 = ... + |
3393/// 880 %30 = COPY %31 | v1 +
3394/// 928 %45 = COPY %30 | + +
3395/// | | v0 | v0 <--+
3396/// 992B ; backedge -> bb.1 | + + |
3397/// 1040 = %31.sub0 + |
3398/// This value must remain
3399/// live-out!
3400///
3401/// Assuming that %31 is coalesced into %45, the copy at 928 becomes
3402/// redundant, since it copies the value from %45 back into it. The
3403/// conflict resolution for the main range determines that %45.v0 is
3404/// to be erased, which is ok since %31.v1 is identical to it.
3405/// The problem happens with the subrange for sub2: it has to be live
3406/// on exit from the block, but since 928 was actually a point of
3407/// definition of %45.sub2, %45.sub2 was not live immediately prior
3408/// to that definition. As a result, when 928 was erased, the value v0
3409/// for %45.sub2 was pruned in pruneSubRegValues. Consequently, an
3410/// IMPLICIT_DEF was inserted as a "backedge" definition for %45.sub2,
3411/// providing an incorrect value to the use at 624.
3412///
3413/// Since the main-range values %31.v1 and %45.v0 were proved to be
3414/// identical, the corresponding values in subranges must also be the
3415/// same. A redundant copy is removed because it's not needed, and not
3416/// because it copied an undefined value, so any liveness that originated
3417/// from that copy cannot disappear. When pruning a value that started
3418/// at the removed copy, the corresponding identical value must be
3419/// extended to replace it.
3420void JoinVals::pruneSubRegValues(LiveInterval &LI, LaneBitmask &ShrinkMask) {
3421 // Look for values being erased.
3422 bool DidPrune = false;
3423 for (unsigned i = 0, e = LR.getNumValNums(); i != e; ++i) {
3424 Val &V = Vals[i];
3425 // We should trigger in all cases in which eraseInstrs() does something.
3426 // match what eraseInstrs() is doing, print a message so
3427 if (V.Resolution != CR_Erase &&
3428 (V.Resolution != CR_Keep || !V.ErasableImplicitDef || !V.Pruned))
3429 continue;
3430
3431 // Check subranges at the point where the copy will be removed.
3432 SlotIndex Def = LR.getValNumInfo(i)->def;
3433 SlotIndex OtherDef;
3434 if (V.Identical)
3435 OtherDef = V.OtherVNI->def;
3436
3437 // Print message so mismatches with eraseInstrs() can be diagnosed.
3438 LLVM_DEBUG(dbgs() << "\t\tExpecting instruction removal at " << Def
3439 << '\n');
3440 for (LiveInterval::SubRange &S : LI.subranges()) {
3441 LiveQueryResult Q = S.Query(Def);
3442
3443 // If a subrange starts at the copy then an undefined value has been
3444 // copied and we must remove that subrange value as well.
3445 VNInfo *ValueOut = Q.valueOutOrDead();
3446 if (ValueOut != nullptr &&
3447 (Q.valueIn() == nullptr ||
3448 (V.Identical && V.Resolution == CR_Erase && ValueOut->def == Def))) {
3449 LLVM_DEBUG(dbgs() << "\t\tPrune sublane " << PrintLaneMask(S.LaneMask)
3450 << " at " << Def << "\n");
3451 SmallVector<SlotIndex, 8> EndPoints;
3452 LIS->pruneValue(S, Def, &EndPoints);
3453 DidPrune = true;
3454 // Mark value number as unused.
3455 if (ValueOut->def == Def)
3456 ValueOut->markUnused();
3457
3458 if (V.Identical && S.Query(OtherDef).valueOutOrDead()) {
3459 // If V is identical to V.OtherVNI (and S was live at OtherDef),
3460 // then we can't simply prune V from S. V needs to be replaced
3461 // with V.OtherVNI.
3462 LIS->extendToIndices(S, EndPoints);
3463 }
3464
3465 // We may need to eliminate the subrange if the copy introduced a live
3466 // out undef value.
3467 if (ValueOut->isPHIDef())
3468 ShrinkMask |= S.LaneMask;
3469 continue;
3470 }
3471
3472 // If a subrange ends at the copy, then a value was copied but only
3473 // partially used later. Shrink the subregister range appropriately.
3474 //
3475 // Ultimately this calls shrinkToUses, so assuming ShrinkMask is
3476 // conservatively correct.
3477 if ((Q.valueIn() != nullptr && Q.valueOut() == nullptr) ||
3478 (V.Resolution == CR_Erase && isLiveThrough(Q))) {
3479 LLVM_DEBUG(dbgs() << "\t\tDead uses at sublane "
3480 << PrintLaneMask(S.LaneMask) << " at " << Def
3481 << "\n");
3482 ShrinkMask |= S.LaneMask;
3483 }
3484 }
3485 }
3486 if (DidPrune)
3488}
3489
3490/// Check if any of the subranges of @p LI contain a definition at @p Def.
3492 for (LiveInterval::SubRange &SR : LI.subranges()) {
3493 if (VNInfo *VNI = SR.Query(Def).valueOutOrDead())
3494 if (VNI->def == Def)
3495 return true;
3496 }
3497 return false;
3498}
3499
3500void JoinVals::pruneMainSegments(LiveInterval &LI, bool &ShrinkMainRange) {
3501 assert(&static_cast<LiveRange &>(LI) == &LR);
3502
3503 for (unsigned i = 0, e = LR.getNumValNums(); i != e; ++i) {
3504 if (Vals[i].Resolution != CR_Keep)
3505 continue;
3506 VNInfo *VNI = LR.getValNumInfo(i);
3507 if (VNI->isUnused() || VNI->isPHIDef() || isDefInSubRange(LI, VNI->def))
3508 continue;
3509 Vals[i].Pruned = true;
3510 ShrinkMainRange = true;
3511 }
3512}
3513
3514void JoinVals::removeImplicitDefs() {
3515 for (unsigned i = 0, e = LR.getNumValNums(); i != e; ++i) {
3516 Val &V = Vals[i];
3517 if (V.Resolution != CR_Keep || !V.ErasableImplicitDef || !V.Pruned)
3518 continue;
3519
3520 VNInfo *VNI = LR.getValNumInfo(i);
3521 VNI->markUnused();
3522 LR.removeValNo(VNI);
3523 }
3524}
3525
3526void JoinVals::eraseInstrs(SmallPtrSetImpl<MachineInstr *> &ErasedInstrs,
3527 SmallVectorImpl<Register> &ShrinkRegs,
3528 LiveInterval *LI) {
3529 for (unsigned i = 0, e = LR.getNumValNums(); i != e; ++i) {
3530 // Get the def location before markUnused() below invalidates it.
3531 VNInfo *VNI = LR.getValNumInfo(i);
3532 SlotIndex Def = VNI->def;
3533 switch (Vals[i].Resolution) {
3534 case CR_Keep: {
3535 // If an IMPLICIT_DEF value is pruned, it doesn't serve a purpose any
3536 // longer. The IMPLICIT_DEF instructions are only inserted by
3537 // PHIElimination to guarantee that all PHI predecessors have a value.
3538 if (!Vals[i].ErasableImplicitDef || !Vals[i].Pruned)
3539 break;
3540 // Remove value number i from LR.
3541 // For intervals with subranges, removing a segment from the main range
3542 // may require extending the previous segment: for each definition of
3543 // a subregister, there will be a corresponding def in the main range.
3544 // That def may fall in the middle of a segment from another subrange.
3545 // In such cases, removing this def from the main range must be
3546 // complemented by extending the main range to account for the liveness
3547 // of the other subrange.
3548 // The new end point of the main range segment to be extended.
3549 SlotIndex NewEnd;
3550 if (LI != nullptr) {
3552 assert(I != LR.end());
3553 // Do not extend beyond the end of the segment being removed.
3554 // The segment may have been pruned in preparation for joining
3555 // live ranges.
3556 NewEnd = I->end;
3557 }
3558
3559 LR.removeValNo(VNI);
3560 // Note that this VNInfo is reused and still referenced in NewVNInfo,
3561 // make it appear like an unused value number.
3562 VNI->markUnused();
3563
3564 if (LI != nullptr && LI->hasSubRanges()) {
3565 assert(static_cast<LiveRange *>(LI) == &LR);
3566 // Determine the end point based on the subrange information:
3567 // minimum of (earliest def of next segment,
3568 // latest end point of containing segment)
3569 SlotIndex ED, LE;
3570 for (LiveInterval::SubRange &SR : LI->subranges()) {
3571 LiveRange::iterator I = SR.find(Def);
3572 if (I == SR.end())
3573 continue;
3574 if (I->start > Def)
3575 ED = ED.isValid() ? std::min(ED, I->start) : I->start;
3576 else
3577 LE = LE.isValid() ? std::max(LE, I->end) : I->end;
3578 }
3579 if (LE.isValid())
3580 NewEnd = std::min(NewEnd, LE);
3581 if (ED.isValid())
3582 NewEnd = std::min(NewEnd, ED);
3583
3584 // We only want to do the extension if there was a subrange that
3585 // was live across Def.
3586 if (LE.isValid()) {
3587 LiveRange::iterator S = LR.find(Def);
3588 if (S != LR.begin())
3589 std::prev(S)->end = NewEnd;
3590 }
3591 }
3592 LLVM_DEBUG({
3593 dbgs() << "\t\tremoved " << i << '@' << Def << ": " << LR << '\n';
3594 if (LI != nullptr)
3595 dbgs() << "\t\t LHS = " << *LI << '\n';
3596 });
3597 [[fallthrough]];
3598 }
3599
3600 case CR_Erase: {
3601 MachineInstr *MI = Indexes->getInstructionFromIndex(Def);
3602 assert(MI && "No instruction to erase");
3603 if (MI->isCopy()) {
3604 Register Reg = MI->getOperand(1).getReg();
3605 if (Reg.isVirtual() && Reg != CP.getSrcReg() && Reg != CP.getDstReg())
3606 ShrinkRegs.push_back(Reg);
3607 }
3608 ErasedInstrs.insert(MI);
3609 LLVM_DEBUG(dbgs() << "\t\terased:\t" << Def << '\t' << *MI);
3611 MI->eraseFromParent();
3612 break;
3613 }
3614 default:
3615 break;
3616 }
3617 }
3618}
3619
3620void RegisterCoalescer::joinSubRegRanges(LiveRange &LRange, LiveRange &RRange,
3621 LaneBitmask LaneMask,
3622 const CoalescerPair &CP) {
3623 SmallVector<VNInfo *, 16> NewVNInfo;
3624 JoinVals RHSVals(RRange, CP.getSrcReg(), CP.getSrcIdx(), LaneMask, NewVNInfo,
3625 CP, LIS, TRI, true, true);
3626 JoinVals LHSVals(LRange, CP.getDstReg(), CP.getDstIdx(), LaneMask, NewVNInfo,
3627 CP, LIS, TRI, true, true);
3628
3629 // Compute NewVNInfo and resolve conflicts (see also joinVirtRegs())
3630 // We should be able to resolve all conflicts here as we could successfully do
3631 // it on the mainrange already. There is however a problem when multiple
3632 // ranges get mapped to the "overflow" lane mask bit which creates unexpected
3633 // interferences.
3634 if (!LHSVals.mapValues(RHSVals) || !RHSVals.mapValues(LHSVals)) {
3635 // We already determined that it is legal to merge the intervals, so this
3636 // should never fail.
3637 llvm_unreachable("*** Couldn't join subrange!\n");
3638 }
3639 if (!LHSVals.resolveConflicts(RHSVals) ||
3640 !RHSVals.resolveConflicts(LHSVals)) {
3641 // We already determined that it is legal to merge the intervals, so this
3642 // should never fail.
3643 llvm_unreachable("*** Couldn't join subrange!\n");
3644 }
3645
3646 // The merging algorithm in LiveInterval::join() can't handle conflicting
3647 // value mappings, so we need to remove any live ranges that overlap a
3648 // CR_Replace resolution. Collect a set of end points that can be used to
3649 // restore the live range after joining.
3650 SmallVector<SlotIndex, 8> EndPoints;
3651 LHSVals.pruneValues(RHSVals, EndPoints, false);
3652 RHSVals.pruneValues(LHSVals, EndPoints, false);
3653
3654 LHSVals.removeImplicitDefs();
3655 RHSVals.removeImplicitDefs();
3656
3657 assert(LRange.verify() && RRange.verify());
3658
3659 // Join RRange into LHS.
3660 LRange.join(RRange, LHSVals.getAssignments(), RHSVals.getAssignments(),
3661 NewVNInfo);
3662
3663 LLVM_DEBUG(dbgs() << "\t\tjoined lanes: " << PrintLaneMask(LaneMask) << ' '
3664 << LRange << "\n");
3665 if (EndPoints.empty())
3666 return;
3667
3668 // Recompute the parts of the live range we had to remove because of
3669 // CR_Replace conflicts.
3670 LLVM_DEBUG({
3671 dbgs() << "\t\trestoring liveness to " << EndPoints.size() << " points: ";
3672 for (unsigned i = 0, n = EndPoints.size(); i != n; ++i) {
3673 dbgs() << EndPoints[i];
3674 if (i != n - 1)
3675 dbgs() << ',';
3676 }
3677 dbgs() << ": " << LRange << '\n';
3678 });
3679 LIS->extendToIndices(LRange, EndPoints);
3680}
3681
3682void RegisterCoalescer::mergeSubRangeInto(LiveInterval &LI,
3683 const LiveRange &ToMerge,
3684 LaneBitmask LaneMask,
3685 CoalescerPair &CP,
3686 unsigned ComposeSubRegIdx) {
3688 LI.refineSubRanges(
3689 Allocator, LaneMask,
3690 [this, &Allocator, &ToMerge, &CP](LiveInterval::SubRange &SR) {
3691 if (SR.empty()) {
3692 SR.assign(ToMerge, Allocator);
3693 } else {
3694 // joinSubRegRange() destroys the merged range, so we need a copy.
3695 LiveRange RangeCopy(ToMerge, Allocator);
3696 joinSubRegRanges(SR, RangeCopy, SR.LaneMask, CP);
3697 }
3698 },
3699 *LIS->getSlotIndexes(), *TRI, ComposeSubRegIdx);
3700
3701 // Merging may leave subranges empty; drop them so the interval is left in a
3702 // valid state.
3704}
3705
3706bool RegisterCoalescer::isHighCostLiveInterval(LiveInterval &LI) {
3708 return false;
3709 auto &Counter = LargeLIVisitCounter[LI.reg()];
3710 if (Counter < LargeIntervalFreqThreshold) {
3711 Counter++;
3712 return false;
3713 }
3714 return true;
3715}
3716
3717RegisterCoalescer::JoinResult
3718RegisterCoalescer::joinVirtRegs(CoalescerPair &CP) {
3719 SmallVector<VNInfo *, 16> NewVNInfo;
3720 LiveInterval &RHS = LIS->getInterval(CP.getSrcReg());
3721 LiveInterval &LHS = LIS->getInterval(CP.getDstReg());
3722 bool TrackSubRegLiveness = MRI->shouldTrackSubRegLiveness(*CP.getNewRC());
3723 JoinVals RHSVals(RHS, CP.getSrcReg(), CP.getSrcIdx(), LaneBitmask::getNone(),
3724 NewVNInfo, CP, LIS, TRI, false, TrackSubRegLiveness);
3725 JoinVals LHSVals(LHS, CP.getDstReg(), CP.getDstIdx(), LaneBitmask::getNone(),
3726 NewVNInfo, CP, LIS, TRI, false, TrackSubRegLiveness);
3727
3728 LLVM_DEBUG(dbgs() << "\t\tRHS = " << RHS << "\n\t\tLHS = " << LHS << '\n');
3729
3730 if (isHighCostLiveInterval(LHS) || isHighCostLiveInterval(RHS)) {
3731 LLVM_DEBUG(dbgs() << "\t\tHigh-cost live interval: RHS valnos="
3732 << RHS.valnos.size() << ", segments=" << RHS.size()
3733 << "; LHS valnos=" << LHS.valnos.size()
3734 << ", segments=" << LHS.size() << '\n');
3735 return JoinResult::Rejected;
3736 }
3737
3738 // First compute NewVNInfo and the simple value mappings. Conflicts found
3739 // here only reject this attempt; subsequent coalescing may still make the
3740 // same copy joinable, so keep it deferred.
3741 if (!LHSVals.mapValues(RHSVals) || !RHSVals.mapValues(LHSVals))
3742 return JoinResult::Deferred;
3743
3744 // Some conflicts can only be resolved after all values have been mapped.
3745 // As above, unresolved conflicts are retryable interference.
3746 if (!LHSVals.resolveConflicts(RHSVals) || !RHSVals.resolveConflicts(LHSVals))
3747 return JoinResult::Deferred;
3748
3749 // All clear, the live ranges can be merged.
3750 if (RHS.hasSubRanges() || LHS.hasSubRanges()) {
3752
3753 // Transform lanemasks from the LHS to masks in the coalesced register and
3754 // create initial subranges if necessary.
3755 unsigned DstIdx = CP.getDstIdx();
3756 if (!LHS.hasSubRanges()) {
3757 LaneBitmask Mask = DstIdx == 0 ? CP.getNewRC()->getLaneMask()
3758 : TRI->getSubRegIndexLaneMask(DstIdx);
3759 // LHS must support subregs or we wouldn't be in this codepath.
3760 assert(Mask.any());
3761 LHS.createSubRangeFrom(Allocator, Mask, LHS);
3762 } else if (DstIdx != 0) {
3763 // Transform LHS lanemasks to new register class if necessary.
3764 for (LiveInterval::SubRange &R : LHS.subranges()) {
3765 LaneBitmask Mask = TRI->composeSubRegIndexLaneMask(DstIdx, R.LaneMask);
3766 R.LaneMask = Mask;
3767 }
3768 }
3769 LLVM_DEBUG(dbgs() << "\t\tLHST = " << printReg(CP.getDstReg()) << ' ' << LHS
3770 << '\n');
3771
3772 // Determine lanemasks of RHS in the coalesced register and merge subranges.
3773 unsigned SrcIdx = CP.getSrcIdx();
3774 if (!RHS.hasSubRanges()) {
3775 LaneBitmask Mask = SrcIdx == 0 ? CP.getNewRC()->getLaneMask()
3776 : TRI->getSubRegIndexLaneMask(SrcIdx);
3777 mergeSubRangeInto(LHS, RHS, Mask, CP, DstIdx);
3778 } else {
3779 // Pair up subranges and merge.
3780 for (LiveInterval::SubRange &R : RHS.subranges()) {
3781 LaneBitmask Mask = TRI->composeSubRegIndexLaneMask(SrcIdx, R.LaneMask);
3782 mergeSubRangeInto(LHS, R, Mask, CP, DstIdx);
3783 }
3784 }
3785 LLVM_DEBUG(dbgs() << "\tJoined SubRanges " << LHS << "\n");
3786
3787 // Pruning implicit defs from subranges may result in the main range
3788 // having stale segments.
3789 LHSVals.pruneMainSegments(LHS, ShrinkMainRange);
3790
3791 LHSVals.pruneSubRegValues(LHS, ShrinkMask);
3792 RHSVals.pruneSubRegValues(LHS, ShrinkMask);
3793 } else if (TrackSubRegLiveness && !CP.getDstIdx() && CP.getSrcIdx()) {
3794 LHS.createSubRangeFrom(LIS->getVNInfoAllocator(),
3795 CP.getNewRC()->getLaneMask(), LHS);
3796 mergeSubRangeInto(LHS, RHS, TRI->getSubRegIndexLaneMask(CP.getSrcIdx()), CP,
3797 CP.getDstIdx());
3798 LHSVals.pruneMainSegments(LHS, ShrinkMainRange);
3799 LHSVals.pruneSubRegValues(LHS, ShrinkMask);
3800 }
3801
3802 // The merging algorithm in LiveInterval::join() can't handle conflicting
3803 // value mappings, so we need to remove any live ranges that overlap a
3804 // CR_Replace resolution. Collect a set of end points that can be used to
3805 // restore the live range after joining.
3806 SmallVector<SlotIndex, 8> EndPoints;
3807 LHSVals.pruneValues(RHSVals, EndPoints, true);
3808 RHSVals.pruneValues(LHSVals, EndPoints, true);
3809
3810 // Erase COPY and IMPLICIT_DEF instructions. This may cause some external
3811 // registers to require trimming.
3812 SmallVector<Register, 8> ShrinkRegs;
3813 LHSVals.eraseInstrs(ErasedInstrs, ShrinkRegs, &LHS);
3814 RHSVals.eraseInstrs(ErasedInstrs, ShrinkRegs);
3815 while (!ShrinkRegs.empty())
3816 shrinkToUses(&LIS->getInterval(ShrinkRegs.pop_back_val()));
3817
3818 // Scan and mark undef any DBG_VALUEs that would refer to a different value.
3819 checkMergingChangesDbgValues(CP, LHS, LHSVals, RHS, RHSVals);
3820
3821 // If the RHS covers any PHI locations that were tracked for debug-info, we
3822 // must update tracking information to reflect the join.
3823 auto RegIt = RegToPHIIdx.find(CP.getSrcReg());
3824 if (RegIt != RegToPHIIdx.end()) {
3825 // Iterate over all the debug instruction numbers assigned this register.
3826 for (unsigned InstID : RegIt->second) {
3827 auto PHIIt = PHIValToPos.find(InstID);
3828 assert(PHIIt != PHIValToPos.end());
3829 const SlotIndex &SI = PHIIt->second.SI;
3830
3831 // Does the RHS cover the position of this PHI?
3832 auto LII = RHS.find(SI);
3833 if (LII == RHS.end() || LII->start > SI)
3834 continue;
3835
3836 // Accept two kinds of subregister movement:
3837 // * When we merge from one register class into a larger register:
3838 // %1:gr16 = some-inst
3839 // ->
3840 // %2:gr32.sub_16bit = some-inst
3841 // * When the PHI is already in a subregister, and the larger class
3842 // is coalesced:
3843 // %2:gr32.sub_16bit = some-inst
3844 // %3:gr32 = COPY %2
3845 // ->
3846 // %3:gr32.sub_16bit = some-inst
3847 // Test for subregister move:
3848 if (CP.getSrcIdx() != 0 || CP.getDstIdx() != 0)
3849 // If we're moving between different subregisters, ignore this join.
3850 // The PHI will not get a location, dropping variable locations.
3851 if (PHIIt->second.SubReg && PHIIt->second.SubReg != CP.getSrcIdx())
3852 continue;
3853
3854 // Update our tracking of where the PHI is.
3855 PHIIt->second.Reg = CP.getDstReg();
3856
3857 // If we merge into a sub-register of a larger class (test above),
3858 // update SubReg.
3859 if (CP.getSrcIdx() != 0)
3860 PHIIt->second.SubReg = CP.getSrcIdx();
3861 }
3862
3863 // Rebuild the register index in RegToPHIIdx to account for PHIs tracking
3864 // different VRegs now. Copy old collection of debug instruction numbers and
3865 // erase the old one:
3866 auto InstrNums = RegIt->second;
3867 RegToPHIIdx.erase(RegIt);
3868
3869 // There might already be PHIs being tracked in the destination VReg. Insert
3870 // into an existing tracking collection, or insert a new one.
3871 RegIt = RegToPHIIdx.find(CP.getDstReg());
3872 if (RegIt != RegToPHIIdx.end())
3873 llvm::append_range(RegIt->second, InstrNums);
3874 else
3875 RegToPHIIdx.insert({CP.getDstReg(), InstrNums});
3876 }
3877
3878 // Join RHS into LHS.
3879 LHS.join(RHS, LHSVals.getAssignments(), RHSVals.getAssignments(), NewVNInfo);
3880
3881 // Kill flags are going to be wrong if the live ranges were overlapping.
3882 // Eventually, we should simply clear all kill flags when computing live
3883 // ranges. They are reinserted after register allocation.
3884 MRI->clearKillFlags(LHS.reg());
3885 MRI->clearKillFlags(RHS.reg());
3886
3887 if (!EndPoints.empty()) {
3888 // Recompute the parts of the live range we had to remove because of
3889 // CR_Replace conflicts.
3890 LLVM_DEBUG({
3891 dbgs() << "\t\trestoring liveness to " << EndPoints.size() << " points: ";
3892 for (unsigned i = 0, n = EndPoints.size(); i != n; ++i) {
3893 dbgs() << EndPoints[i];
3894 if (i != n - 1)
3895 dbgs() << ',';
3896 }
3897 dbgs() << ": " << LHS << '\n';
3898 });
3899 LIS->extendToIndices((LiveRange &)LHS, EndPoints);
3900 }
3901
3902 return JoinResult::Joined;
3903}
3904
3905RegisterCoalescer::JoinResult
3906RegisterCoalescer::joinIntervals(CoalescerPair &CP) {
3907 if (CP.isPhys())
3908 return joinReservedPhysReg(CP) ? JoinResult::Joined : JoinResult::Deferred;
3909 return joinVirtRegs(CP);
3910}
3911
3912void RegisterCoalescer::buildVRegToDbgValueMap(MachineFunction &MF) {
3913 const SlotIndexes &Slots = *LIS->getSlotIndexes();
3915
3916 // After collecting a block of DBG_VALUEs into ToInsert, enter them into the
3917 // vreg => DbgValueLoc map.
3918 auto CloseNewDVRange = [this, &ToInsert](SlotIndex Slot) {
3919 for (auto *X : ToInsert) {
3920 for (const auto &Op : X->debug_operands()) {
3921 if (Op.isReg() && Op.getReg().isVirtual())
3922 DbgVRegToValues[Op.getReg()].push_back({Slot, X});
3923 }
3924 }
3925
3926 ToInsert.clear();
3927 };
3928
3929 // Iterate over all instructions, collecting them into the ToInsert vector.
3930 // Once a non-debug instruction is found, record the slot index of the
3931 // collected DBG_VALUEs.
3932 for (auto &MBB : MF) {
3933 SlotIndex CurrentSlot = Slots.getMBBStartIdx(&MBB);
3934
3935 for (auto &MI : MBB) {
3936 if (MI.isDebugValue()) {
3937 if (any_of(MI.debug_operands(), [](const MachineOperand &MO) {
3938 return MO.isReg() && MO.getReg().isVirtual();
3939 }))
3940 ToInsert.push_back(&MI);
3941 } else if (!MI.isDebugOrPseudoInstr()) {
3942 CurrentSlot = Slots.getInstructionIndex(MI);
3943 CloseNewDVRange(CurrentSlot);
3944 }
3945 }
3946
3947 // Close range of DBG_VALUEs at the end of blocks.
3948 CloseNewDVRange(Slots.getMBBEndIdx(&MBB));
3949 }
3950
3951 // Sort all DBG_VALUEs we've seen by slot number.
3952 for (auto &Pair : DbgVRegToValues)
3953 llvm::sort(Pair.second);
3954}
3955
3956void RegisterCoalescer::checkMergingChangesDbgValues(CoalescerPair &CP,
3957 LiveRange &LHS,
3958 JoinVals &LHSVals,
3959 LiveRange &RHS,
3960 JoinVals &RHSVals) {
3961 auto ScanForDstReg = [&](Register Reg) {
3962 checkMergingChangesDbgValuesImpl(Reg, RHS, LHS, LHSVals);
3963 };
3964
3965 auto ScanForSrcReg = [&](Register Reg) {
3966 checkMergingChangesDbgValuesImpl(Reg, LHS, RHS, RHSVals);
3967 };
3968
3969 // Scan for unsound updates of both the source and destination register.
3970 ScanForSrcReg(CP.getSrcReg());
3971 ScanForDstReg(CP.getDstReg());
3972}
3973
3974void RegisterCoalescer::checkMergingChangesDbgValuesImpl(Register Reg,
3975 LiveRange &OtherLR,
3976 LiveRange &RegLR,
3977 JoinVals &RegVals) {
3978 // Are there any DBG_VALUEs to examine?
3979 auto VRegMapIt = DbgVRegToValues.find(Reg);
3980 if (VRegMapIt == DbgVRegToValues.end())
3981 return;
3982
3983 auto &DbgValueSet = VRegMapIt->second;
3984 auto DbgValueSetIt = DbgValueSet.begin();
3985 auto SegmentIt = OtherLR.begin();
3986
3987 bool LastUndefResult = false;
3988 SlotIndex LastUndefIdx;
3989
3990 // If the "Other" register is live at a slot Idx, test whether Reg can
3991 // safely be merged with it, or should be marked undef.
3992 auto ShouldUndef = [&RegVals, &RegLR, &LastUndefResult,
3993 &LastUndefIdx](SlotIndex Idx) -> bool {
3994 // Our worst-case performance typically happens with asan, causing very
3995 // many DBG_VALUEs of the same location. Cache a copy of the most recent
3996 // result for this edge-case.
3997 if (LastUndefIdx == Idx)
3998 return LastUndefResult;
3999
4000 // If the other range was live, and Reg's was not, the register coalescer
4001 // will not have tried to resolve any conflicts. We don't know whether
4002 // the DBG_VALUE will refer to the same value number, so it must be made
4003 // undef.
4004 auto OtherIt = RegLR.find(Idx);
4005 if (OtherIt == RegLR.end())
4006 return true;
4007
4008 // Both the registers were live: examine the conflict resolution record for
4009 // the value number Reg refers to. CR_Keep meant that this value number
4010 // "won" and the merged register definitely refers to that value. CR_Erase
4011 // means the value number was a redundant copy of the other value, which
4012 // was coalesced and Reg deleted. It's safe to refer to the other register
4013 // (which will be the source of the copy).
4014 auto Resolution = RegVals.getResolution(OtherIt->valno->id);
4015 LastUndefResult =
4016 Resolution != JoinVals::CR_Keep && Resolution != JoinVals::CR_Erase;
4017 LastUndefIdx = Idx;
4018 return LastUndefResult;
4019 };
4020
4021 // Iterate over both the live-range of the "Other" register, and the set of
4022 // DBG_VALUEs for Reg at the same time. Advance whichever one has the lowest
4023 // slot index. This relies on the DbgValueSet being ordered.
4024 while (DbgValueSetIt != DbgValueSet.end() && SegmentIt != OtherLR.end()) {
4025 if (DbgValueSetIt->first < SegmentIt->end) {
4026 // "Other" is live and there is a DBG_VALUE of Reg: test if we should
4027 // set it undef.
4028 if (DbgValueSetIt->first >= SegmentIt->start) {
4029 bool HasReg = DbgValueSetIt->second->hasDebugOperandForReg(Reg);
4030 bool ShouldUndefReg = ShouldUndef(DbgValueSetIt->first);
4031 if (HasReg && ShouldUndefReg) {
4032 // Mark undef, erase record of this DBG_VALUE to avoid revisiting.
4033 DbgValueSetIt->second->setDebugValueUndef();
4034 continue;
4035 }
4036 }
4037 ++DbgValueSetIt;
4038 } else {
4039 ++SegmentIt;
4040 }
4041 }
4042}
4043
4044namespace {
4045
4046/// Information concerning MBB coalescing priority.
4047struct MBBPriorityInfo {
4048 MachineBasicBlock *MBB;
4049 unsigned Depth;
4050 bool IsSplit;
4051
4052 MBBPriorityInfo(MachineBasicBlock *mbb, unsigned depth, bool issplit)
4053 : MBB(mbb), Depth(depth), IsSplit(issplit) {}
4054};
4055
4056} // end anonymous namespace
4057
4058/// C-style comparator that sorts first based on the loop depth of the basic
4059/// block (the unsigned), and then on the MBB number.
4060///
4061/// EnableGlobalCopies assumes that the primary sort key is loop depth.
4062static int compareMBBPriority(const MBBPriorityInfo *LHS,
4063 const MBBPriorityInfo *RHS) {
4064 // Deeper loops first
4065 if (LHS->Depth != RHS->Depth)
4066 return LHS->Depth > RHS->Depth ? -1 : 1;
4067
4068 // Try to unsplit critical edges next.
4069 if (LHS->IsSplit != RHS->IsSplit)
4070 return LHS->IsSplit ? -1 : 1;
4071
4072 // Prefer blocks that are more connected in the CFG. This takes care of
4073 // the most difficult copies first while intervals are short.
4074 unsigned cl = LHS->MBB->pred_size() + LHS->MBB->succ_size();
4075 unsigned cr = RHS->MBB->pred_size() + RHS->MBB->succ_size();
4076 if (cl != cr)
4077 return cl > cr ? -1 : 1;
4078
4079 // As a last resort, sort by block number.
4080 return LHS->MBB->getNumber() < RHS->MBB->getNumber() ? -1 : 1;
4081}
4082
4083/// \returns true if the given copy uses or defines a local live range.
4084static bool isLocalCopy(MachineInstr *Copy, const LiveIntervals *LIS) {
4085 if (!Copy->isCopy())
4086 return false;
4087
4088 if (Copy->getOperand(1).isUndef())
4089 return false;
4090
4091 Register SrcReg = Copy->getOperand(1).getReg();
4092 Register DstReg = Copy->getOperand(0).getReg();
4093 if (SrcReg.isPhysical() || DstReg.isPhysical())
4094 return false;
4095
4096 return LIS->intervalIsInOneMBB(LIS->getInterval(SrcReg)) ||
4097 LIS->intervalIsInOneMBB(LIS->getInterval(DstReg));
4098}
4099
4100void RegisterCoalescer::lateLiveIntervalUpdate() {
4101 for (Register reg : ToBeUpdated) {
4102 if (!LIS->hasInterval(reg))
4103 continue;
4104 LiveInterval &LI = LIS->getInterval(reg);
4105 shrinkToUses(&LI, &DeadDefs);
4106 if (!DeadDefs.empty())
4107 eliminateDeadDefs();
4108 }
4109 ToBeUpdated.clear();
4110}
4111
4112bool RegisterCoalescer::copyCoalesceWorkList(
4114 bool Progress = false;
4115 SmallPtrSet<MachineInstr *, 4> CurrentErasedInstrs;
4116 for (MachineInstr *&MI : CurrList) {
4117 if (!MI)
4118 continue;
4119 // Skip instruction pointers that have already been erased, for example by
4120 // dead code elimination.
4121 if (ErasedInstrs.count(MI) || CurrentErasedInstrs.count(MI)) {
4122 MI = nullptr;
4123 continue;
4124 }
4125 JoinResult Result = joinCopy(MI, CurrentErasedInstrs);
4126 Progress |= Result == JoinResult::Joined;
4127 if (Result != JoinResult::Deferred)
4128 MI = nullptr;
4129 }
4130 // Clear instructions not recorded in `ErasedInstrs` but erased.
4131 if (!CurrentErasedInstrs.empty()) {
4132 for (MachineInstr *&MI : CurrList) {
4133 if (MI && CurrentErasedInstrs.count(MI))
4134 MI = nullptr;
4135 }
4136 for (MachineInstr *&MI : WorkList) {
4137 if (MI && CurrentErasedInstrs.count(MI))
4138 MI = nullptr;
4139 }
4140 }
4141 return Progress;
4142}
4143
4144/// Check if DstReg is a terminal node.
4145/// I.e., it does not have any affinity other than \p Copy.
4146static bool isTerminalReg(Register DstReg, const MachineInstr &Copy,
4147 const MachineRegisterInfo *MRI) {
4148 assert(Copy.isCopyLike());
4149 // Check if the destination of this copy as any other affinity.
4150 for (const MachineInstr &MI : MRI->reg_nodbg_instructions(DstReg))
4151 if (&MI != &Copy && MI.isCopyLike())
4152 return false;
4153 return true;
4154}
4155
4156bool RegisterCoalescer::applyTerminalRule(const MachineInstr &Copy) const {
4157 assert(Copy.isCopyLike());
4158 if (!UseTerminalRule)
4159 return false;
4160 Register SrcReg, DstReg;
4161 unsigned SrcSubReg = 0, DstSubReg = 0;
4162 if (!isMoveInstr(*TRI, &Copy, SrcReg, DstReg, SrcSubReg, DstSubReg))
4163 return false;
4164 // Check if the destination of this copy has any other affinity.
4165 if (DstReg.isPhysical() ||
4166 // If SrcReg is a physical register, the copy won't be coalesced.
4167 // Ignoring it may have other side effect (like missing
4168 // rematerialization). So keep it.
4169 SrcReg.isPhysical() || !isTerminalReg(DstReg, Copy, MRI))
4170 return false;
4171
4172 // DstReg is a terminal node. Check if it interferes with any other
4173 // copy involving SrcReg.
4174 const MachineBasicBlock *OrigBB = Copy.getParent();
4175 const LiveInterval &DstLI = LIS->getInterval(DstReg);
4176 for (const MachineInstr &MI : MRI->reg_nodbg_instructions(SrcReg)) {
4177 // Technically we should check if the weight of the new copy is
4178 // interesting compared to the other one and update the weight
4179 // of the copies accordingly. However, this would only work if
4180 // we would gather all the copies first then coalesce, whereas
4181 // right now we interleave both actions.
4182 // For now, just consider the copies that are in the same block.
4183 if (&MI == &Copy || !MI.isCopyLike() || MI.getParent() != OrigBB)
4184 continue;
4185 Register OtherSrcReg, OtherReg;
4186 unsigned OtherSrcSubReg = 0, OtherSubReg = 0;
4187 if (!isMoveInstr(*TRI, &MI, OtherSrcReg, OtherReg, OtherSrcSubReg,
4188 OtherSubReg))
4189 return false;
4190 if (OtherReg == SrcReg)
4191 OtherReg = OtherSrcReg;
4192 // Check if OtherReg is a non-terminal.
4193 if (OtherReg.isPhysical() || isTerminalReg(OtherReg, MI, MRI))
4194 continue;
4195 // Check that OtherReg interfere with DstReg.
4196 if (LIS->getInterval(OtherReg).overlaps(DstLI)) {
4197 LLVM_DEBUG(dbgs() << "Apply terminal rule for: " << printReg(DstReg)
4198 << '\n');
4199 return true;
4200 }
4201 }
4202 return false;
4203}
4204
4205void RegisterCoalescer::copyCoalesceInMBB(MachineBasicBlock *MBB) {
4206 LLVM_DEBUG(dbgs() << MBB->getName() << ":\n");
4207
4208 // Collect all copy-like instructions in MBB. Don't start coalescing anything
4209 // yet, it might invalidate the iterator.
4210 const unsigned PrevSize = WorkList.size();
4211 if (JoinGlobalCopies) {
4212 SmallVector<MachineInstr *, 2> LocalTerminals;
4213 SmallVector<MachineInstr *, 2> GlobalTerminals;
4214 // Coalesce copies top-down to propagate coalescing and rematerialization
4215 // forward.
4216 for (MachineInstr &MI : *MBB) {
4217 if (!MI.isCopyLike())
4218 continue;
4219 bool ApplyTerminalRule = applyTerminalRule(MI);
4220 if (isLocalCopy(&MI, LIS)) {
4221 if (ApplyTerminalRule)
4222 LocalTerminals.push_back(&MI);
4223 else
4224 LocalWorkList.push_back(&MI);
4225 } else {
4226 if (ApplyTerminalRule)
4227 GlobalTerminals.push_back(&MI);
4228 else
4229 WorkList.push_back(&MI);
4230 }
4231 }
4232 // Append the copies evicted by the terminal rule at the end of the list.
4233 LocalWorkList.append(LocalTerminals.begin(), LocalTerminals.end());
4234 WorkList.append(GlobalTerminals.begin(), GlobalTerminals.end());
4235 } else {
4237 // Coalesce copies top-down to propagate coalescing and rematerialization
4238 // forward.
4239 for (MachineInstr &MII : *MBB)
4240 if (MII.isCopyLike()) {
4241 if (applyTerminalRule(MII))
4242 Terminals.push_back(&MII);
4243 else
4244 WorkList.push_back(&MII);
4245 }
4246 // Append the copies evicted by the terminal rule at the end of the list.
4247 WorkList.append(Terminals.begin(), Terminals.end());
4248 }
4249 // Try coalescing the collected copies immediately, and remove the nulls.
4250 // This prevents the WorkList from getting too large since most copies are
4251 // joinable on the first attempt.
4252 MutableArrayRef<MachineInstr *> CurrList(WorkList.begin() + PrevSize,
4253 WorkList.end());
4254 if (copyCoalesceWorkList(CurrList))
4255 WorkList.erase(
4256 std::remove(WorkList.begin() + PrevSize, WorkList.end(), nullptr),
4257 WorkList.end());
4258}
4259
4260void RegisterCoalescer::coalesceLocals() {
4261 copyCoalesceWorkList(LocalWorkList);
4262 for (MachineInstr *MI : LocalWorkList) {
4263 if (MI)
4264 WorkList.push_back(MI);
4265 }
4266 LocalWorkList.clear();
4267}
4268
4269void RegisterCoalescer::joinAllIntervals() {
4270 LLVM_DEBUG(dbgs() << "********** JOINING INTERVALS ***********\n");
4271 assert(WorkList.empty() && LocalWorkList.empty() && "Old data still around.");
4272
4273 std::vector<MBBPriorityInfo> MBBs;
4274 MBBs.reserve(MF->size());
4275 for (MachineBasicBlock &MBB : *MF) {
4276 MBBs.push_back(MBBPriorityInfo(&MBB, Loops->getLoopDepth(&MBB),
4277 JoinSplitEdges && isSplitEdge(&MBB)));
4278 }
4279 array_pod_sort(MBBs.begin(), MBBs.end(), compareMBBPriority);
4280
4281 // Coalesce intervals in MBB priority order.
4282 unsigned CurrDepth = std::numeric_limits<unsigned>::max();
4283 for (MBBPriorityInfo &MBB : MBBs) {
4284 // Try coalescing the collected local copies for deeper loops.
4285 if (JoinGlobalCopies && MBB.Depth < CurrDepth) {
4286 coalesceLocals();
4287 CurrDepth = MBB.Depth;
4288 }
4289 copyCoalesceInMBB(MBB.MBB);
4290 }
4291 lateLiveIntervalUpdate();
4292 coalesceLocals();
4293
4294 // Joining intervals can allow other intervals to be joined. Iteratively join
4295 // until we make no progress.
4296 while (copyCoalesceWorkList(WorkList))
4297 /* empty */;
4298 lateLiveIntervalUpdate();
4299}
4300
4304 MFPropsModifier _(*this, MF);
4305 auto &LIS = MFAM.getResult<LiveIntervalsAnalysis>(MF);
4306 auto &Loops = MFAM.getResult<MachineLoopAnalysis>(MF);
4307 auto *SI = MFAM.getCachedResult<SlotIndexesAnalysis>(MF);
4308 auto *RegClassInfo = &MFAM.getResult<MachineRegisterClassAnalysis>(MF);
4309 RegisterCoalescer Impl(&LIS, SI, &Loops, RegClassInfo);
4310 if (!Impl.run(MF))
4311 return PreservedAnalyses::all();
4313 PA.preserveSet<CFGAnalyses>();
4314 PA.preserve<LiveIntervalsAnalysis>();
4315 PA.preserve<SlotIndexesAnalysis>();
4316 return PA;
4317}
4318
4319bool RegisterCoalescerLegacy::runOnMachineFunction(MachineFunction &MF) {
4320 auto *LIS = &getAnalysis<LiveIntervalsWrapperPass>().getLIS();
4321 auto *Loops = &getAnalysis<MachineLoopInfoWrapperPass>().getLI();
4322 auto *SIWrapper = getAnalysisIfAvailable<SlotIndexesWrapperPass>();
4323 auto *RegClassInfo =
4324 &getAnalysis<MachineRegisterClassInfoWrapperPass>().getRCI();
4325 SlotIndexes *SI = SIWrapper ? &SIWrapper->getSI() : nullptr;
4326 RegisterCoalescer Impl(LIS, SI, Loops, RegClassInfo);
4327 return Impl.run(MF);
4328}
4329
4330bool RegisterCoalescer::run(MachineFunction &fn) {
4331 LLVM_DEBUG(dbgs() << "********** REGISTER COALESCER **********\n"
4332 << "********** Function: " << fn.getName() << '\n');
4333
4334 // Variables changed between a setjmp and a longjump can have undefined value
4335 // after the longjmp. This behaviour can be observed if such a variable is
4336 // spilled, so longjmp won't restore the value in the spill slot.
4337 // RegisterCoalescer should not run in functions with a setjmp to avoid
4338 // merging such undefined variables with predictable ones.
4339 //
4340 // TODO: Could specifically disable coalescing registers live across setjmp
4341 // calls
4342 if (fn.exposesReturnsTwice()) {
4343 LLVM_DEBUG(
4344 dbgs() << "* Skipped as it exposes functions that returns twice.\n");
4345 return false;
4346 }
4347
4348 MF = &fn;
4349 MRI = &fn.getRegInfo();
4350 const TargetSubtargetInfo &STI = fn.getSubtarget();
4351 TRI = STI.getRegisterInfo();
4352 TII = STI.getInstrInfo();
4354 JoinGlobalCopies = STI.enableJoinGlobalCopies();
4355 else
4356 JoinGlobalCopies = (EnableGlobalCopies == cl::boolOrDefault::BOU_TRUE);
4357
4358 // If there are PHIs tracked by debug-info, they will need updating during
4359 // coalescing. Build an index of those PHIs to ease updating.
4360 SlotIndexes *Slots = LIS->getSlotIndexes();
4361 for (const auto &DebugPHI : MF->DebugPHIPositions) {
4362 MachineBasicBlock *MBB = DebugPHI.second.MBB;
4363 Register Reg = DebugPHI.second.Reg;
4364 unsigned SubReg = DebugPHI.second.SubReg;
4365 SlotIndex SI = Slots->getMBBStartIdx(MBB);
4366 PHIValPos P = {SI, Reg, SubReg};
4367 PHIValToPos.insert(std::make_pair(DebugPHI.first, P));
4368 RegToPHIIdx[Reg].push_back(DebugPHI.first);
4369 }
4370
4371 // The MachineScheduler does not currently require JoinSplitEdges. This will
4372 // either be enabled unconditionally or replaced by a more general live range
4373 // splitting optimization.
4374 JoinSplitEdges = EnableJoinSplits;
4375
4376 if (VerifyCoalescing)
4377 MF->verify(LIS, SI, "Before register coalescing", &errs());
4378
4379 DbgVRegToValues.clear();
4381
4382 // Join (coalesce) intervals if requested.
4383 if (EnableJoining)
4384 joinAllIntervals();
4385
4386 // After deleting a lot of copies, register classes may be less constrained.
4387 // Removing sub-register operands may allow GR32_ABCD -> GR32 and DPR_VFP2 ->
4388 // DPR inflation.
4389 array_pod_sort(InflateRegs.begin(), InflateRegs.end());
4390 InflateRegs.erase(llvm::unique(InflateRegs), InflateRegs.end());
4391 LLVM_DEBUG(dbgs() << "Trying to inflate " << InflateRegs.size()
4392 << " regs.\n");
4393 for (Register Reg : InflateRegs) {
4394 if (MRI->reg_nodbg_empty(Reg))
4395 continue;
4396 if (MRI->recomputeRegClass(Reg)) {
4397 LLVM_DEBUG(dbgs() << printReg(Reg) << " inflated to "
4398 << TRI->getRegClassName(MRI->getRegClass(Reg)) << '\n');
4399 ++NumInflated;
4400
4401 LiveInterval &LI = LIS->getInterval(Reg);
4402 if (LI.hasSubRanges()) {
4403 // If the inflated register class does not support subregisters anymore
4404 // remove the subranges.
4405 if (!MRI->shouldTrackSubRegLiveness(Reg)) {
4406 LI.clearSubRanges();
4407 } else {
4408#ifndef NDEBUG
4409 LaneBitmask MaxMask = MRI->getMaxLaneMaskForVReg(Reg);
4410 // If subranges are still supported, then the same subregs
4411 // should still be supported.
4412 for (LiveInterval::SubRange &S : LI.subranges()) {
4413 assert((S.LaneMask & ~MaxMask).none());
4414 }
4415#endif
4416 }
4417 }
4418 }
4419 }
4420
4421 // After coalescing, update any PHIs that are being tracked by debug-info
4422 // with their new VReg locations.
4423 for (auto &p : MF->DebugPHIPositions) {
4424 auto it = PHIValToPos.find(p.first);
4425 assert(it != PHIValToPos.end());
4426 p.second.Reg = it->second.Reg;
4427 p.second.SubReg = it->second.SubReg;
4428 }
4429
4430 PHIValToPos.clear();
4431 RegToPHIIdx.clear();
4432
4433 LLVM_DEBUG(LIS->dump());
4434
4435 if (VerifyCoalescing)
4436 MF->verify(LIS, SI, "After register coalescing", &errs());
4437 return true;
4438}
MachineInstrBuilder & UseMI
MachineInstrBuilder MachineInstrBuilder & DefMI
assert(UImm &&(UImm !=~static_cast< T >(0)) &&"Invalid immediate!")
aarch64 promote const
MachineBasicBlock & MBB
MachineBasicBlock MachineBasicBlock::iterator DebugLoc DL
#define X(NUM, ENUM, NAME)
Definition ELF.h:857
This file implements the BitVector class.
static GCRegistry::Add< CoreCLRGC > E("coreclr", "CoreCLR-compatible GC")
This file defines the DenseSet and SmallDenseSet classes.
const HexagonInstrInfo * TII
Hexagon Hardware Loops
#define _
IRTranslator LLVM IR MI
const AbstractManglingParser< Derived, Alloc >::OperatorInfo AbstractManglingParser< Derived, Alloc >::Ops[]
A common definition of LaneBitmask for use in TableGen and CodeGen.
#define I(x, y, z)
Definition MD5.cpp:57
Register Reg
Register const TargetRegisterInfo * TRI
Promote Memory to Register
Definition Mem2Reg.cpp:110
#define P(N)
if(PassOpts->AAPipeline)
#define INITIALIZE_PASS_DEPENDENCY(depName)
Definition PassSupport.h:42
#define INITIALIZE_PASS_END(passName, arg, name, cfg, analysis)
Definition PassSupport.h:44
#define INITIALIZE_PASS_BEGIN(passName, arg, name, cfg, analysis)
Definition PassSupport.h:39
Basic Register Allocator
static cl::opt< bool > UseTerminalRule("terminal-rule", cl::desc("Apply the terminal rule"), cl::init(true), cl::Hidden)
static bool isLocalCopy(MachineInstr *Copy, const LiveIntervals *LIS)
static bool isSplitEdge(const MachineBasicBlock *MBB)
Return true if this block should be vacated by the coalescer to eliminate branches.
static int compareMBBPriority(const MBBPriorityInfo *LHS, const MBBPriorityInfo *RHS)
C-style comparator that sorts first based on the loop depth of the basic block (the unsigned),...
static cl::opt< unsigned > LargeIntervalSizeThreshold("large-interval-size-threshold", cl::Hidden, cl::desc("If the valnos size of an interval is larger than the threshold, " "it is regarded as a large interval. "), cl::init(100))
static bool isDefInSubRange(LiveInterval &LI, SlotIndex Def)
Check if any of the subranges of LI contain a definition at Def.
static std::pair< bool, bool > addSegmentsWithValNo(LiveRange &Dst, VNInfo *DstValNo, const LiveRange &Src, const VNInfo *SrcValNo)
Copy segments with value number SrcValNo from liverange Src to live range @Dst and use value number D...
static bool isLiveThrough(const LiveQueryResult Q)
static bool isTerminalReg(Register DstReg, const MachineInstr &Copy, const MachineRegisterInfo *MRI)
Check if DstReg is a terminal node.
static cl::opt< bool > VerifyCoalescing("verify-coalescing", cl::desc("Verify machine instrs before and after register coalescing"), cl::Hidden)
register Register static false bool isMoveInstr(const TargetRegisterInfo &tri, const MachineInstr *MI, Register &Src, Register &Dst, unsigned &SrcSub, unsigned &DstSub)
static cl::opt< bool > EnableJoinSplits("join-splitedges", cl::desc("Coalesce copies on split edges (default=subtarget)"), cl::Hidden)
Temporary flag to test critical edge unsplitting.
static cl::opt< bool > EnableJoining("join-liveintervals", cl::desc("Coalesce copies (default=true)"), cl::init(true), cl::Hidden)
static cl::opt< unsigned > LargeIntervalFreqThreshold("large-interval-freq-threshold", cl::Hidden, cl::desc("For a large interval, if it is coalesced with other live " "intervals many times more than the threshold, stop its " "coalescing to control the compile time. "), cl::init(256))
static cl::opt< unsigned > LateRematUpdateThreshold("late-remat-update-threshold", cl::Hidden, cl::desc("During rematerialization for a copy, if the def instruction has " "many other copy uses to be rematerialized, delay the multiple " "separate live interval update work and do them all at once after " "all those rematerialization are done. It will save a lot of " "repeated work. "), cl::init(100))
static cl::opt< cl::boolOrDefault > EnableGlobalCopies("join-globalcopies", cl::desc("Coalesce copies that span blocks (default=subtarget)"), cl::init(cl::boolOrDefault::BOU_UNSET), cl::Hidden)
Temporary flag to test global copy optimization.
SI Optimize VGPR LiveRange
This file contains some templates that are useful if you are working with the STL at all.
This file defines the SmallPtrSet class.
This file defines the SmallVector class.
This file defines the 'Statistic' class, which is designed to be an easy way to expose various metric...
#define STATISTIC(VARNAME, DESC)
Definition Statistic.h:171
#define LLVM_DEBUG(...)
Definition Debug.h:119
static DenseMap< Register, std::vector< std::pair< SlotIndex, MachineInstr * > > > buildVRegToDbgValueMap(MachineFunction &MF, const LiveIntervals *Liveness)
static void shrinkToUses(LiveInterval &LI, LiveIntervals &LIS)
Value * RHS
Value * LHS
PassT::Result * getCachedResult(IRUnitT &IR) const
Get the cached result of an analysis pass for a given IR unit.
PassT::Result & getResult(IRUnitT &IR, ExtraArgTs... ExtraArgs)
Get the result of an analysis pass for a given IR unit.
Represent the analysis usage information of a pass.
AnalysisUsage & addUsedIfAvailable()
Add the specified Pass class to the set of analyses used by this pass.
AnalysisUsage & addRequired()
AnalysisUsage & addPreserved()
Add the specified Pass class to the set of analyses preserved by this pass.
LLVM_ABI void setPreservesCFG()
This function should be called by the pass, iff they do not:
Definition Pass.cpp:278
bool test(unsigned Idx) const
Returns true if bit Idx is set.
Definition BitVector.h:482
Represents analyses that only rely on functions' control flow.
Definition Analysis.h:73
A helper class for register coalescers.
unsigned getDstIdx() const
Return the subregister index that DstReg will be coalesced into, or 0.
bool isFlipped() const
Return true when getSrcReg is the register being defined by the original copy instruction.
bool isPartial() const
Return true if the original copy instruction did not copy the full register, but was a subreg operati...
bool flip()
Swap SrcReg and DstReg.
bool isPhys() const
Return true if DstReg is a physical register.
bool isCrossClass() const
Return true if DstReg is virtual and NewRC is a smaller register class than DstReg's.
Register getDstReg() const
Return the register (virtual or physical) that will remain after coalescing.
bool isCoalescable(const MachineInstr *) const
Return true if MI is a copy instruction that will become an identity copy after coalescing.
const TargetRegisterClass * getNewRC() const
Return the register class of the coalesced register.
bool setRegisters(const MachineInstr *)
Set registers to match the copy instruction MI.
unsigned getSrcIdx() const
Return the subregister index that SrcReg will be coalesced into, or 0.
Register getSrcReg() const
Return the virtual register that will be coalesced away.
A debug info location.
Definition DebugLoc.h:126
iterator find(const_arg_type_t< KeyT > Val)
Definition DenseMap.h:782
iterator end()
Definition DenseMap.h:702
bool erase(const KeyT &Val)
Definition DenseMap.h:946
std::pair< iterator, bool > insert(const std::pair< KeyT, ValueT > &KV)
Definition DenseMap.h:843
bool isAsCheapAsAMove(const MachineInstr &MI) const override
A live range for subregisters.
LiveInterval - This class represents the liveness of a register, or stack slot.
LLVM_ABI void removeEmptySubRanges()
Removes all subranges without any segments (subranges without segments are not considered valid and s...
Register reg() const
bool hasSubRanges() const
Returns true if subregister liveness information is available.
SubRange * createSubRangeFrom(BumpPtrAllocator &Allocator, LaneBitmask LaneMask, const LiveRange &CopyFrom)
Like createSubRange() but the new range is filled with a copy of the liveness information in CopyFrom...
iterator_range< subrange_iterator > subranges()
LLVM_ABI void refineSubRanges(BumpPtrAllocator &Allocator, LaneBitmask LaneMask, std::function< void(LiveInterval::SubRange &)> Apply, const SlotIndexes &Indexes, const TargetRegisterInfo &TRI, unsigned ComposeSubRegIdx=0)
Refines the subranges to support LaneMask.
LLVM_ABI void computeSubRangeUndefs(SmallVectorImpl< SlotIndex > &Undefs, LaneBitmask LaneMask, const MachineRegisterInfo &MRI, const SlotIndexes &Indexes) const
For a given lane mask LaneMask, compute indexes at which the lane is marked undefined by subregister ...
SubRange * createSubRange(BumpPtrAllocator &Allocator, LaneBitmask LaneMask)
Creates a new empty subregister live range.
LLVM_ABI void clearSubRanges()
Removes all subregister liveness information.
bool hasInterval(Register Reg) const
SlotIndex getMBBStartIdx(const MachineBasicBlock *mbb) const
Return the first index in the given basic block.
MachineInstr * getInstructionFromIndex(SlotIndex index) const
Returns the instruction associated with the given index.
LLVM_ABI bool hasPHIKill(const LiveInterval &LI, const VNInfo *VNI) const
Returns true if VNI is killed by any PHI-def values in LI.
SlotIndex InsertMachineInstrInMaps(MachineInstr &MI)
LLVM_ABI bool checkRegMaskInterference(const LiveInterval &LI, BitVector &UsableRegs)
Test if LI is live across any register mask instructions, and compute a bit mask of physical register...
SlotIndexes * getSlotIndexes() const
SlotIndex getInstructionIndex(const MachineInstr &Instr) const
Returns the base index of the given instruction.
void RemoveMachineInstrFromMaps(MachineInstr &MI)
VNInfo::Allocator & getVNInfoAllocator()
SlotIndex getMBBEndIdx(const MachineBasicBlock *mbb) const
Return the last index in the given basic block.
LiveInterval & getInterval(Register Reg)
LLVM_ABI void pruneValue(LiveRange &LR, SlotIndex Kill, SmallVectorImpl< SlotIndex > *EndPoints)
If LR has a live value at Kill, prune its live range by removing any liveness reachable from Kill.
void removeInterval(Register Reg)
Interval removal.
LiveRange & getRegUnit(MCRegUnit Unit)
Return the live range for register unit Unit.
LLVM_ABI MachineBasicBlock * intervalIsInOneMBB(const LiveInterval &LI) const
If LI is confined to a single basic block, return a pointer to that block.
LiveRange * getCachedRegUnit(MCRegUnit Unit)
Return the live range for register unit Unit if it has already been computed, or nullptr if it hasn't...
LLVM_ABI void removeVRegDefAt(LiveInterval &LI, SlotIndex Pos)
Remove value number and related live segments of LI and its subranges that start at position Pos.
LLVM_ABI bool shrinkToUses(LiveInterval *li, SmallVectorImpl< MachineInstr * > *dead=nullptr)
After removing some uses of a register, shrink its live range to just the remaining uses.
LLVM_ABI void extendToIndices(LiveRange &LR, ArrayRef< SlotIndex > Indices, ArrayRef< SlotIndex > Undefs)
Extend the live range LR to reach all points in Indices.
LLVM_ABI void dump() const
LLVM_ABI void removePhysRegDefAt(MCRegister Reg, SlotIndex Pos)
Remove value numbers and related live segments starting at position Pos that are part of any liverang...
MachineBasicBlock * getMBBFromIndex(SlotIndex index) const
bool isLiveInToMBB(const LiveRange &LR, const MachineBasicBlock *mbb) const
SlotIndex ReplaceMachineInstrInMaps(MachineInstr &MI, MachineInstr &NewMI)
Result of a LiveRange query.
VNInfo * valueOutOrDead() const
Returns the value alive at the end of the instruction, if any.
VNInfo * valueIn() const
Return the value that is live-in to the instruction.
VNInfo * valueOut() const
Return the value leaving the instruction, if any.
VNInfo * valueDefined() const
Return the value defined by this instruction, if any.
SlotIndex endPoint() const
Return the end point of the last live range segment to interact with the instruction,...
bool isKill() const
Return true if the live-in value is killed by this instruction.
Callback methods for LiveRangeEdit owners.
SlotIndex rematerializeAt(MachineBasicBlock &MBB, MachineBasicBlock::iterator MI, Register DestReg, const Remat &RM, const TargetRegisterInfo &, bool Late=false, unsigned SubIdx=0, MachineInstr *ReplaceIndexMI=nullptr, LaneBitmask UsedLanes=LaneBitmask::getAll())
rematerializeAt - Rematerialize RM.ParentVNI into DestReg by inserting an instruction into MBB before...
void eliminateDeadDefs(SmallVectorImpl< MachineInstr * > &Dead, ArrayRef< Register > RegsBeingSpilled={})
eliminateDeadDefs - Try to delete machine instructions that are now dead (allDefsAreDead returns true...
This class represents the liveness of a register, stack slot, etc.
VNInfo * getValNumInfo(unsigned ValNo)
getValNumInfo - Returns pointer to the specified val#.
LLVM_ABI iterator addSegment(Segment S)
Add the specified Segment to this range, merging segments as appropriate.
Segments::iterator iterator
const Segment * getSegmentContaining(SlotIndex Idx) const
Return the segment that contains the specified index, or null if there is none.
LLVM_ABI void join(LiveRange &Other, const int *ValNoAssignments, const int *RHSValNoAssignments, SmallVectorImpl< VNInfo * > &NewVNInfo)
join - Join two live ranges (this, and other) together.
bool liveAt(SlotIndex index) const
LLVM_ABI VNInfo * createDeadDef(SlotIndex Def, VNInfo::Allocator &VNIAlloc)
createDeadDef - Make sure the range has a value defined at Def.
LLVM_ABI void removeValNo(VNInfo *ValNo)
removeValNo - Remove all the segments defined by the specified value#.
bool empty() const
bool overlaps(const LiveRange &other) const
overlaps - Return true if the intersection of the two live ranges is not empty.
LiveQueryResult Query(SlotIndex Idx) const
Query Liveness at Idx.
VNInfo * getVNInfoBefore(SlotIndex Idx) const
getVNInfoBefore - Return the VNInfo that is live up to but not necessarily including Idx,...
bool verify() const
Walk the range and assert if any invariants fail to hold.
LLVM_ABI VNInfo * MergeValueNumberInto(VNInfo *V1, VNInfo *V2)
MergeValueNumberInto - This method is called when two value numbers are found to be equivalent.
unsigned getNumValNums() const
iterator begin()
VNInfoList valnos
bool containsOneValue() const
size_t size() const
iterator FindSegmentContaining(SlotIndex Idx)
Return an iterator to the segment that contains the specified index, or end() if there is none.
void assign(const LiveRange &Other, BumpPtrAllocator &Allocator)
Copies values numbers and live segments from Other into this range.
VNInfo * getVNInfoAt(SlotIndex Idx) const
getVNInfoAt - Return the VNInfo that is live at Idx, or NULL.
LLVM_ABI iterator find(SlotIndex Pos)
find - Return an iterator pointing to the first segment that ends after Pos, or end().
Describe properties that are true of each instruction in the target description file.
unsigned getNumOperands() const
Return the number of declared MachineOperands for this MachineInstruction.
MCRegUnitRootIterator enumerates the root registers of a register unit.
bool isValid() const
Check if the iterator is at the end of the list.
LaneBitmask getLaneMask() const
Returns the combination of all lane masks of register in this class.
bool contains(MCRegister Reg) const
contains - Return true if the specified register is included in this register class.
Wrapper class representing physical registers. Should be passed by value.
Definition MCRegister.h:41
An RAII based helper class to modify MachineFunctionProperties when running pass.
bool isInlineAsmBrIndirectTarget() const
Returns true if this is the indirect dest of an INLINEASM_BR.
LLVM_ABI bool hasEHPadSuccessor() const
bool isEHPad() const
Returns true if the block is a landing pad.
LLVM_ABI instr_iterator insert(instr_iterator I, MachineInstr *M)
Insert MI into the instruction list before I, possibly inside a bundle.
LLVM_ABI iterator getFirstTerminator()
Returns an iterator to the first terminator instruction of this basic block.
LLVM_ABI instr_iterator erase(instr_iterator I)
Remove an instruction from the instruction list and delete it.
iterator_range< pred_iterator > predecessors()
void splice(iterator Where, MachineBasicBlock *Other, iterator From)
Take an instruction from MBB 'Other' at the position From, and insert it into this MBB right before '...
MachineInstrBundleIterator< MachineInstr > iterator
LLVM_ABI StringRef getName() const
Return the name of the corresponding LLVM basic block, or an empty string.
MachineFunctionPass - This class adapts the FunctionPass interface to allow convenient creation of pa...
void getAnalysisUsage(AnalysisUsage &AU) const override
getAnalysisUsage - Subclasses that override getAnalysisUsage must call this.
const TargetSubtargetInfo & getSubtarget() const
getSubtarget - Return the subtarget for which this machine code is being compiled.
StringRef getName() const
getName - Return the name of the corresponding LLVM function.
bool exposesReturnsTwice() const
exposesReturnsTwice - Returns true if the function calls setjmp or any other similar functions with a...
MachineRegisterInfo & getRegInfo()
getRegInfo - Return information about the registers currently in use.
bool verify(Pass *p=nullptr, const char *Banner=nullptr, raw_ostream *OS=nullptr, bool AbortOnError=true) const
Run the current MachineFunction through the machine code verifier, useful for debugger use.
DenseMap< unsigned, DebugPHIRegallocPos > DebugPHIPositions
Map of debug instruction numbers to the position of their PHI instructions during register allocation...
const MachineInstrBuilder & addReg(Register RegNo, RegState Flags={}, unsigned SubReg=0) const
Add a new virtual register operand.
Representation of each machine instruction.
unsigned getOpcode() const
Returns the opcode of this MachineInstr.
LLVM_ABI void setRegisterDefReadUndef(Register Reg, bool IsUndef=true)
Mark all subregister defs of register Reg with the undef flag.
bool isImplicitDef() const
bool isCopy() const
const MachineBasicBlock * getParent() const
bool isCopyLike() const
Return true if the instruction behaves like a copy.
filtered_mop_range all_defs()
Returns an iterator range over all operands that are (explicit or implicit) register defs.
LLVM_ABI std::pair< bool, bool > readsWritesVirtualRegister(Register Reg, SmallVectorImpl< unsigned > *Ops=nullptr) const
Return a pair of bools (reads, writes) indicating if this instruction reads or writes Reg.
bool isRegTiedToDefOperand(unsigned UseOpIdx, unsigned *DefOpIdx=nullptr) const
Return true if the use operand of the specified index is tied to a def operand.
LLVM_ABI bool isSafeToMove(bool &SawStore) const
Return true if it is safe to move this instruction.
bool isDebugInstr() const
unsigned getNumOperands() const
Retuns the total number of operands.
LLVM_ABI void addOperand(MachineFunction &MF, const MachineOperand &Op)
Add the specified operand to the instruction.
bool isRegTiedToUseOperand(unsigned DefOpIdx, unsigned *UseOpIdx=nullptr) const
Given the index of a register def operand, check if the register def is tied to a source operand,...
bool isFullCopy() const
LLVM_ABI int findRegisterUseOperandIdx(Register Reg, const TargetRegisterInfo *TRI, bool isKill=false) const
Returns the operand index that is a use of the specific register or -1 if it is not found.
const MCInstrDesc & getDesc() const
Returns the target instruction descriptor of this MachineInstr.
bool isCommutable(QueryType Type=IgnoreBundle) const
Return true if this may be a 2- or 3-address instruction (of the form "X = op Y, Z,...
mop_range operands()
LLVM_ABI void setDesc(const MCInstrDesc &TID)
Replace the instruction descriptor (thus opcode) of the current instruction with a new one.
LLVM_ABI void substituteRegister(Register FromReg, Register ToReg, unsigned SubIdx, const TargetRegisterInfo &RegInfo)
Replace all occurrences of FromReg with ToReg:SubIdx, properly composing subreg indices where necessa...
const DebugLoc & getDebugLoc() const
Returns the debug location id of this MachineInstr.
LLVM_ABI void removeOperand(unsigned OpNo)
Erase an operand from an instruction, leaving it with one fewer operand than it started with.
const MachineOperand & getOperand(unsigned i) const
LLVM_ABI int findRegisterDefOperandIdx(Register Reg, const TargetRegisterInfo *TRI, bool isDead=false, bool Overlap=false) const
Returns the operand index that is a def of the specified register or -1 if it is not found.
LLVM_ABI MachineInstrBundleIterator< MachineInstr > eraseFromParent()
Unlink 'this' from the containing basic block and delete it.
void setDebugLoc(DebugLoc DL)
Replace current source information with new such.
LLVM_ABI bool allDefsAreDead() const
Return true if all the defs of this instruction are dead.
Analysis pass that exposes the MachineLoopInfo for a machine function.
MachineOperand class - Representation of each machine instruction operand.
void setSubReg(unsigned subReg)
unsigned getSubReg() const
LLVM_ABI void substVirtReg(Register Reg, unsigned SubIdx, const TargetRegisterInfo &)
substVirtReg - Substitute the current register with the virtual subregister Reg:SubReg.
bool readsReg() const
readsReg - Returns true if this operand reads the previous value of its register.
bool isReg() const
isReg - Tests if this is a MO_Register operand.
void setIsDead(bool Val=true)
bool isImm() const
isImm - Tests if this is a MO_Immediate operand.
void setIsKill(bool Val=true)
MachineInstr * getParent()
getParent - Return the instruction that this operand belongs to.
LLVM_ABI void substPhysReg(MCRegister Reg, const TargetRegisterInfo &)
substPhysReg - Substitute the current register with the physical register Reg, taking any existing Su...
void setIsUndef(bool Val=true)
bool isEarlyClobber() const
Register getReg() const
getReg - Returns the register number.
static MachineOperand CreateReg(Register Reg, bool isDef, bool isImp=false, bool isKill=false, bool isDead=false, bool isUndef=false, bool isEarlyClobber=false, unsigned SubReg=0, bool isDebug=false, bool isInternalRead=false, bool isRenamable=false)
MachineRegisterInfo - Keep track of information for virtual and physical registers,...
LLVM_ABI bool hasOneNonDBGUse(Register RegNo) const
hasOneNonDBGUse - Return true if there is exactly one non-Debug use of the specified register.
LLVM_ABI bool recomputeRegClass(Register Reg)
recomputeRegClass - Try to find a legal super-class of Reg's register class that still satisfies the ...
reg_instr_iterator reg_instr_begin(Register RegNo) const
const TargetRegisterClass * getRegClass(Register Reg) const
Return the register class of the specified virtual register.
LLVM_ABI void clearKillFlags(Register Reg) const
clearKillFlags - Iterate over all the uses of the given register and clear the kill flag from the Mac...
LLVM_ABI LLVM_READONLY MachineInstr * getVRegDef(Register Reg) const
getVRegDef - Return the machine instr that defines the specified virtual register or null if none is ...
iterator_range< use_nodbg_iterator > use_nodbg_operands(Register Reg) const
static reg_instr_iterator reg_instr_end()
bool use_nodbg_empty(Register RegNo) const
use_nodbg_empty - Return true if there are no non-Debug instructions using the specified register.
bool isReserved(MCRegister PhysReg) const
isReserved - Returns true when PhysReg is a reserved register.
bool reg_nodbg_empty(Register RegNo) const
reg_nodbg_empty - Return true if the only instructions using or defining Reg are Debug instructions.
use_instr_nodbg_iterator use_instr_nodbg_begin(Register RegNo) const
bool shouldTrackSubRegLiveness(const TargetRegisterClass &RC) const
Returns true if liveness for register class RC should be tracked at the subregister level.
LLVM_ABI void setRegClass(Register Reg, const TargetRegisterClass *RC)
setRegClass - Set the register class of the specified virtual register.
LLVM_ABI LaneBitmask getMaxLaneMaskForVReg(Register Reg) const
Returns a mask covering all bits that can appear in lane masks of subregisters of the virtual registe...
LLVM_ABI bool isConstantPhysReg(MCRegister PhysReg) const
Returns true if PhysReg is unallocatable and constant throughout the function.
iterator_range< reg_nodbg_iterator > reg_nodbg_operands(Register Reg) const
defusechain_instr_iterator< true, true, false, true > reg_instr_iterator
reg_instr_iterator/reg_instr_begin/reg_instr_end - Walk all defs and uses of the specified register,...
LLVM_ABI const TargetRegisterClass * constrainRegClass(Register Reg, const TargetRegisterClass *RC, unsigned MinNumRegs=0)
constrainRegClass - Constrain the register class of the specified virtual register to be a common sub...
iterator_range< use_iterator > use_operands(Register Reg) const
iterator_range< reg_instr_nodbg_iterator > reg_nodbg_instructions(Register Reg) const
Represent a mutable reference to an array (0 or more elements consecutively in memory),...
Definition ArrayRef.h:294
A set of analyses that are preserved following a run of a transformation pass.
Definition Analysis.h:112
static PreservedAnalyses all()
Construct a special preserved set that preserves all passes.
Definition Analysis.h:118
bool isProperSubClass(const TargetRegisterClass *RC) const
isProperSubClass - Returns true if RC has a legal super-class with more allocatable registers.
unsigned getNumAllocatableRegs(const TargetRegisterClass *RC) const
getNumAllocatableRegs - Returns the number of actually allocatable registers in RC in the current fun...
LLVM_ABI PreservedAnalyses run(MachineFunction &MF, MachineFunctionAnalysisManager &MFAM)
Wrapper class representing virtual and physical registers.
Definition Register.h:20
MCRegister asMCReg() const
Utility to check-convert this value to a MCRegister.
Definition Register.h:107
constexpr bool isVirtual() const
Return true if the specified register number is in the virtual register namespace.
Definition Register.h:79
constexpr unsigned id() const
Definition Register.h:100
constexpr bool isPhysical() const
Return true if the specified register number is in the physical register namespace.
Definition Register.h:83
SlotIndex - An opaque wrapper around machine indexes.
Definition SlotIndexes.h:66
static bool isSameInstr(SlotIndex A, SlotIndex B)
isSameInstr - Return true if A and B refer to the same instruction.
bool isEarlyClobber() const
isEarlyClobber - Returns true if this is an early-clobber slot.
bool isValid() const
Returns true if this is a valid index.
SlotIndex getBaseIndex() const
Returns the base index for associated with this index.
SlotIndex getPrevSlot() const
Returns the previous slot in the index list.
SlotIndex getRegSlot(bool EC=false) const
Returns the register use/def slot in the current instruction for a normal or early-clobber def.
bool isDead() const
isDead - Returns true if this is a dead def kill slot.
SlotIndexes pass.
MachineBasicBlock * getMBBFromIndex(SlotIndex index) const
Returns the basic block which the given index falls in.
SlotIndex getNextNonNullIndex(SlotIndex Index)
Returns the next non-null index, if one exists.
SlotIndex getInstructionIndex(const MachineInstr &MI, bool IgnoreBundle=false) const
Returns the base index for the given instruction.
SlotIndex getIndexBefore(const MachineInstr &MI) const
getIndexBefore - Returns the index of the last indexed instruction before MI, or the start index of i...
SlotIndex getMBBEndIdx(const MachineBasicBlock *mbb) const
Returns the index past the last valid index in the given basic block.
SlotIndex getMBBStartIdx(const MachineBasicBlock *mbb) const
Returns the first index in the given basic block.
MachineInstr * getInstructionFromIndex(SlotIndex index) const
Returns the instruction for the given index, or null if the given index has no instruction associated...
A templated base class for SmallPtrSet which provides the typesafe interface that is common across al...
bool erase(PtrType Ptr)
Remove pointer from the set.
size_type count(ConstPtrType Ptr) const
count - Return 1 if the specified pointer is in the set, 0 otherwise.
std::pair< iterator, bool > insert(PtrType Ptr)
Inserts Ptr if and only if there is no element in the container equal to Ptr.
SmallPtrSet - This class implements a set which is optimized for holding SmallSize or less elements.
This class consists of common code factored out of the SmallVector class to reduce code duplication b...
void reserve(size_type N)
iterator erase(const_iterator CI)
void append(ItTy in_start, ItTy in_end)
Add the specified range to the end of the SmallVector.
void push_back(const T &Elt)
pointer data()
Return a pointer to the vector's buffer, even if empty().
This is a 'vector' (really, a variable-sized array), optimized for the case when the array is small.
TargetInstrInfo - Interface to description of machine instruction set.
static const unsigned CommuteAnyOperandIndex
TargetRegisterInfo base class - We assume that the target defines a static array of TargetRegisterDes...
TargetSubtargetInfo - Generic base class for all target subtargets.
virtual bool enableJoinGlobalCopies() const
True if the subtarget should enable joining global copies.
virtual const TargetInstrInfo * getInstrInfo() const
virtual const TargetRegisterInfo * getRegisterInfo() const =0
Return the target's register information.
VNInfo - Value Number Information.
void markUnused()
Mark this value as unused.
BumpPtrAllocator Allocator
bool isUnused() const
Returns true if this value is unused.
unsigned id
The ID number of this value.
SlotIndex def
The index of the defining instruction.
bool isPHIDef() const
Returns true if this value is defined by a PHI instruction (or was, PHI instructions may have been el...
static LLVM_ABI bool allUsesAvailableAt(const MachineInstr *MI, SlotIndex UseIdx, const LiveIntervals &LIS, const MachineRegisterInfo &MRI, const TargetInstrInfo &TII)
std::pair< iterator, bool > insert(const ValueT &V)
Definition DenseSet.h:209
size_type count(const_arg_type_t< ValueT > V) const
Return 1 if the specified key is in the set, 0 otherwise.
Definition DenseSet.h:187
self_iterator getIterator()
Definition ilist_node.h:123
Changed
#define llvm_unreachable(msg)
Marks that the current location is not supposed to be reachable.
constexpr std::underlying_type_t< E > Mask()
Get a bitmask with 1s in all places up to the high-order bit of E's largest value.
This namespace contains all of the command line option processing machinery.
Definition MCSchedule.h:35
initializer< Ty > init(const Ty &Val)
PointerTypeMap run(const Module &M)
Compute the PointerTypeMap for the module M.
NodeAddr< DefNode * > Def
Definition RDFGraph.h:384
iterator end() const
Definition BasicBlock.h:89
UseMask
Specifies the way the mask should be analyzed for undefs/poisonous elements in the shuffle mask.
Definition SLPUtils.h:291
This is an optimization pass for GlobalISel generic memory operations.
MachineInstrBuilder BuildMI(MachineFunction &MF, const MIMetadata &MIMD, const MCInstrDesc &MCID)
Builder interface. Specify how to create the initial instruction itself.
LLVM_ABI char & RegisterCoalescerID
RegisterCoalescer - This pass merges live ranges to eliminate copies.
@ Dead
Unused definition.
void append_range(Container &C, Range &&R)
Wrapper function to append range R to container C.
Definition STLExtras.h:2224
iterator_range< early_inc_iterator_impl< detail::IterOfRange< RangeT > > > make_early_inc_range(RangeT &&Range)
Make a range that does early increment to allow mutation of the underlying range without disrupting i...
Definition STLExtras.h:649
Printable PrintLaneMask(LaneBitmask LaneMask)
Create Printable object to print LaneBitmasks on a raw_ostream.
Definition LaneBitmask.h:92
LLVM_ABI Printable printRegUnit(MCRegUnit Unit, const TargetRegisterInfo *TRI)
Create Printable object to print register units on a raw_ostream.
AnalysisManager< MachineFunction > MachineFunctionAnalysisManager
auto unique(Range &&R, Predicate P)
Definition STLExtras.h:2150
auto upper_bound(R &&Range, T &&Value)
Provide wrappers to std::upper_bound which take ranges instead of having to pass begin/end explicitly...
Definition STLExtras.h:2081
LLVM_ABI PreservedAnalyses getMachineFunctionPassPreservedAnalyses()
Returns the minimum set of Analyses that all machine function passes must preserve.
bool any_of(R &&range, UnaryPredicate P)
Provide wrappers to std::any_of which take ranges instead of having to pass begin/end explicitly.
Definition STLExtras.h:1762
void sort(IteratorTy Start, IteratorTy End)
Definition STLExtras.h:1652
LLVM_ABI raw_ostream & dbgs()
dbgs() - This returns a reference to a raw_ostream for debugging messages.
Definition Debug.cpp:209
bool none_of(R &&Range, UnaryPredicate P)
Provide wrappers to std::none_of which take ranges instead of having to pass begin/end explicitly.
Definition STLExtras.h:1769
class LLVM_GSL_OWNER SmallVector
Forward declaration of SmallVector so that calculateSmallVectorDefaultInlinedElements can reference s...
MutableArrayRef(T &OneElt) -> MutableArrayRef< T >
LLVM_ABI raw_fd_ostream & errs()
This returns a reference to a raw_ostream for standard error.
@ Other
Any other memory.
Definition ModRef.h:68
DWARFExpression::Operation Op
auto make_second_range(ContainerTy &&c)
Given a container of pairs, return a range over the second elements.
Definition STLExtras.h:1425
bool is_contained(R &&Range, const E &Element)
Returns true if Element is found in Range.
Definition STLExtras.h:1963
iterator_range< MIBundleOperands > mi_bundle_ops(MachineInstr &MI)
LLVM_ABI void eraseInstrs(ArrayRef< MachineInstr * > DeadInstrs, MachineRegisterInfo &MRI, LostDebugLocObserver *LocObserver=nullptr)
Definition Utils.cpp:1656
void array_pod_sort(IteratorTy Start, IteratorTy End)
array_pod_sort - This sorts an array with the specified start and end extent.
Definition STLExtras.h:1612
BumpPtrAllocatorImpl<> BumpPtrAllocator
The standard BumpPtrAllocator which just uses the default template parameters.
Definition Allocator.h:390
LLVM_ABI Printable printReg(Register Reg, const TargetRegisterInfo *TRI=nullptr, unsigned SubIdx=0, const MachineRegisterInfo *MRI=nullptr)
Prints virtual and physical registers with or without a TRI instance.
LLVM_ABI Printable printMBBReference(const MachineBasicBlock &MBB)
Prints a machine basic block reference.
MCRegisterClass TargetRegisterClass
Definition FastISel.h:58
void swap(llvm::BitVector &LHS, llvm::BitVector &RHS)
Implement std::swap in terms of BitVector swap.
Definition BitVector.h:880
static constexpr LaneBitmask getLane(unsigned Lane)
Definition LaneBitmask.h:83
static constexpr LaneBitmask getAll()
Definition LaneBitmask.h:82
constexpr bool any() const
Definition LaneBitmask.h:53
static constexpr LaneBitmask getNone()
Definition LaneBitmask.h:81
Remat - Information needed to rematerialize at a specific location.
This represents a simple continuous liveness interval for a value.