1 //===- RegisterCoalescer.cpp - Generic Register Coalescing Interface -------==//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
10 // This file implements the generic RegisterCoalescer interface which
11 // is used as the common interface used by all clients and
12 // implementations of register coalescing.
14 //===----------------------------------------------------------------------===//
16 #define DEBUG_TYPE "regalloc"
17 #include "RegisterCoalescer.h"
18 #include "llvm/ADT/STLExtras.h"
19 #include "llvm/ADT/SmallSet.h"
20 #include "llvm/ADT/Statistic.h"
21 #include "llvm/Analysis/AliasAnalysis.h"
22 #include "llvm/CodeGen/LiveIntervalAnalysis.h"
23 #include "llvm/CodeGen/LiveRangeEdit.h"
24 #include "llvm/CodeGen/MachineFrameInfo.h"
25 #include "llvm/CodeGen/MachineInstr.h"
26 #include "llvm/CodeGen/MachineLoopInfo.h"
27 #include "llvm/CodeGen/MachineRegisterInfo.h"
28 #include "llvm/CodeGen/Passes.h"
29 #include "llvm/CodeGen/RegisterClassInfo.h"
30 #include "llvm/CodeGen/VirtRegMap.h"
31 #include "llvm/IR/Value.h"
32 #include "llvm/Pass.h"
33 #include "llvm/Support/CommandLine.h"
34 #include "llvm/Support/Debug.h"
35 #include "llvm/Support/ErrorHandling.h"
36 #include "llvm/Support/raw_ostream.h"
37 #include "llvm/Target/TargetInstrInfo.h"
38 #include "llvm/Target/TargetMachine.h"
39 #include "llvm/Target/TargetRegisterInfo.h"
40 #include "llvm/Target/TargetSubtargetInfo.h"
45 STATISTIC(numJoins , "Number of interval joins performed");
46 STATISTIC(numCrossRCs , "Number of cross class joins performed");
47 STATISTIC(numCommutes , "Number of instruction commuting performed");
48 STATISTIC(numExtends , "Number of copies extended");
49 STATISTIC(NumReMats , "Number of instructions re-materialized");
50 STATISTIC(NumInflated , "Number of register classes inflated");
51 STATISTIC(NumLaneConflicts, "Number of dead lane conflicts tested");
52 STATISTIC(NumLaneResolves, "Number of dead lane conflicts resolved");
55 EnableJoining("join-liveintervals",
56 cl::desc("Coalesce copies (default=true)"),
59 // Temporary flag to test critical edge unsplitting.
61 EnableJoinSplits("join-splitedges",
62 cl::desc("Coalesce copies on split edges (default=subtarget)"), cl::Hidden);
64 // Temporary flag to test global copy optimization.
65 static cl::opt<cl::boolOrDefault>
66 EnableGlobalCopies("join-globalcopies",
67 cl::desc("Coalesce copies that span blocks (default=subtarget)"),
68 cl::init(cl::BOU_UNSET), cl::Hidden);
71 VerifyCoalescing("verify-coalescing",
72 cl::desc("Verify machine instrs before and after register coalescing"),
76 class RegisterCoalescer : public MachineFunctionPass,
77 private LiveRangeEdit::Delegate {
79 MachineRegisterInfo* MRI;
80 const TargetMachine* TM;
81 const TargetRegisterInfo* TRI;
82 const TargetInstrInfo* TII;
84 const MachineLoopInfo* Loops;
86 RegisterClassInfo RegClassInfo;
88 /// \brief True if the coalescer should aggressively coalesce global copies
89 /// in favor of keeping local copies.
90 bool JoinGlobalCopies;
92 /// \brief True if the coalescer should aggressively coalesce fall-thru
93 /// blocks exclusively containing copies.
96 /// WorkList - Copy instructions yet to be coalesced.
97 SmallVector<MachineInstr*, 8> WorkList;
98 SmallVector<MachineInstr*, 8> LocalWorkList;
100 /// ErasedInstrs - Set of instruction pointers that have been erased, and
101 /// that may be present in WorkList.
102 SmallPtrSet<MachineInstr*, 8> ErasedInstrs;
104 /// Dead instructions that are about to be deleted.
105 SmallVector<MachineInstr*, 8> DeadDefs;
107 /// Virtual registers to be considered for register class inflation.
108 SmallVector<unsigned, 8> InflateRegs;
110 /// Recursively eliminate dead defs in DeadDefs.
111 void eliminateDeadDefs();
113 /// LiveRangeEdit callback.
114 void LRE_WillEraseInstruction(MachineInstr *MI) override;
116 /// coalesceLocals - coalesce the LocalWorkList.
117 void coalesceLocals();
119 /// joinAllIntervals - join compatible live intervals
120 void joinAllIntervals();
122 /// copyCoalesceInMBB - Coalesce copies in the specified MBB, putting
123 /// copies that cannot yet be coalesced into WorkList.
124 void copyCoalesceInMBB(MachineBasicBlock *MBB);
126 /// copyCoalesceWorkList - Try to coalesce all copies in CurrList. Return
127 /// true if any progress was made.
128 bool copyCoalesceWorkList(MutableArrayRef<MachineInstr*> CurrList);
130 /// joinCopy - Attempt to join intervals corresponding to SrcReg/DstReg,
131 /// which are the src/dst of the copy instruction CopyMI. This returns
132 /// true if the copy was successfully coalesced away. If it is not
133 /// currently possible to coalesce this interval, but it may be possible if
134 /// other things get coalesced, then it returns true by reference in
136 bool joinCopy(MachineInstr *TheCopy, bool &Again);
138 /// joinIntervals - Attempt to join these two intervals. On failure, this
139 /// returns false. The output "SrcInt" will not have been modified, so we
140 /// can use this information below to update aliases.
141 bool joinIntervals(CoalescerPair &CP);
143 /// Attempt joining two virtual registers. Return true on success.
144 bool joinVirtRegs(CoalescerPair &CP);
146 /// Attempt joining with a reserved physreg.
147 bool joinReservedPhysReg(CoalescerPair &CP);
149 /// adjustCopiesBackFrom - We found a non-trivially-coalescable copy. If
150 /// the source value number is defined by a copy from the destination reg
151 /// see if we can merge these two destination reg valno# into a single
152 /// value number, eliminating a copy.
153 bool adjustCopiesBackFrom(const CoalescerPair &CP, MachineInstr *CopyMI);
155 /// hasOtherReachingDefs - Return true if there are definitions of IntB
156 /// other than BValNo val# that can reach uses of AValno val# of IntA.
157 bool hasOtherReachingDefs(LiveInterval &IntA, LiveInterval &IntB,
158 VNInfo *AValNo, VNInfo *BValNo);
160 /// removeCopyByCommutingDef - We found a non-trivially-coalescable copy.
161 /// If the source value number is defined by a commutable instruction and
162 /// its other operand is coalesced to the copy dest register, see if we
163 /// can transform the copy into a noop by commuting the definition.
164 bool removeCopyByCommutingDef(const CoalescerPair &CP,MachineInstr *CopyMI);
166 /// reMaterializeTrivialDef - If the source of a copy is defined by a
167 /// trivial computation, replace the copy by rematerialize the definition.
168 bool reMaterializeTrivialDef(CoalescerPair &CP, MachineInstr *CopyMI,
171 /// canJoinPhys - Return true if a physreg copy should be joined.
172 bool canJoinPhys(const CoalescerPair &CP);
174 /// updateRegDefsUses - Replace all defs and uses of SrcReg to DstReg and
175 /// update the subregister number if it is not zero. If DstReg is a
176 /// physical register and the existing subregister number of the def / use
177 /// being updated is not zero, make sure to set it to the correct physical
179 void updateRegDefsUses(unsigned SrcReg, unsigned DstReg, unsigned SubIdx);
181 /// eliminateUndefCopy - Handle copies of undef values.
182 bool eliminateUndefCopy(MachineInstr *CopyMI, const CoalescerPair &CP);
185 static char ID; // Class identification, replacement for typeinfo
186 RegisterCoalescer() : MachineFunctionPass(ID) {
187 initializeRegisterCoalescerPass(*PassRegistry::getPassRegistry());
190 void getAnalysisUsage(AnalysisUsage &AU) const override;
192 void releaseMemory() override;
194 /// runOnMachineFunction - pass entry point
195 bool runOnMachineFunction(MachineFunction&) override;
197 /// print - Implement the dump method.
198 void print(raw_ostream &O, const Module* = 0) const override;
200 } /// end anonymous namespace
202 char &llvm::RegisterCoalescerID = RegisterCoalescer::ID;
204 INITIALIZE_PASS_BEGIN(RegisterCoalescer, "simple-register-coalescing",
205 "Simple Register Coalescing", false, false)
206 INITIALIZE_PASS_DEPENDENCY(LiveIntervals)
207 INITIALIZE_PASS_DEPENDENCY(SlotIndexes)
208 INITIALIZE_PASS_DEPENDENCY(MachineLoopInfo)
209 INITIALIZE_AG_DEPENDENCY(AliasAnalysis)
210 INITIALIZE_PASS_END(RegisterCoalescer, "simple-register-coalescing",
211 "Simple Register Coalescing", false, false)
213 char RegisterCoalescer::ID = 0;
215 static bool isMoveInstr(const TargetRegisterInfo &tri, const MachineInstr *MI,
216 unsigned &Src, unsigned &Dst,
217 unsigned &SrcSub, unsigned &DstSub) {
219 Dst = MI->getOperand(0).getReg();
220 DstSub = MI->getOperand(0).getSubReg();
221 Src = MI->getOperand(1).getReg();
222 SrcSub = MI->getOperand(1).getSubReg();
223 } else if (MI->isSubregToReg()) {
224 Dst = MI->getOperand(0).getReg();
225 DstSub = tri.composeSubRegIndices(MI->getOperand(0).getSubReg(),
226 MI->getOperand(3).getImm());
227 Src = MI->getOperand(2).getReg();
228 SrcSub = MI->getOperand(2).getSubReg();
234 // Return true if this block should be vacated by the coalescer to eliminate
235 // branches. The important cases to handle in the coalescer are critical edges
236 // split during phi elimination which contain only copies. Simple blocks that
237 // contain non-branches should also be vacated, but this can be handled by an
238 // earlier pass similar to early if-conversion.
239 static bool isSplitEdge(const MachineBasicBlock *MBB) {
240 if (MBB->pred_size() != 1 || MBB->succ_size() != 1)
243 for (MachineBasicBlock::const_iterator MII = MBB->begin(), E = MBB->end();
245 if (!MII->isCopyLike() && !MII->isUnconditionalBranch())
251 bool CoalescerPair::setRegisters(const MachineInstr *MI) {
255 Flipped = CrossClass = false;
257 unsigned Src, Dst, SrcSub, DstSub;
258 if (!isMoveInstr(TRI, MI, Src, Dst, SrcSub, DstSub))
260 Partial = SrcSub || DstSub;
262 // If one register is a physreg, it must be Dst.
263 if (TargetRegisterInfo::isPhysicalRegister(Src)) {
264 if (TargetRegisterInfo::isPhysicalRegister(Dst))
267 std::swap(SrcSub, DstSub);
271 const MachineRegisterInfo &MRI = MI->getParent()->getParent()->getRegInfo();
273 if (TargetRegisterInfo::isPhysicalRegister(Dst)) {
274 // Eliminate DstSub on a physreg.
276 Dst = TRI.getSubReg(Dst, DstSub);
277 if (!Dst) return false;
281 // Eliminate SrcSub by picking a corresponding Dst superregister.
283 Dst = TRI.getMatchingSuperReg(Dst, SrcSub, MRI.getRegClass(Src));
284 if (!Dst) return false;
285 } else if (!MRI.getRegClass(Src)->contains(Dst)) {
289 // Both registers are virtual.
290 const TargetRegisterClass *SrcRC = MRI.getRegClass(Src);
291 const TargetRegisterClass *DstRC = MRI.getRegClass(Dst);
293 // Both registers have subreg indices.
294 if (SrcSub && DstSub) {
295 // Copies between different sub-registers are never coalescable.
296 if (Src == Dst && SrcSub != DstSub)
299 NewRC = TRI.getCommonSuperRegClass(SrcRC, SrcSub, DstRC, DstSub,
304 // SrcReg will be merged with a sub-register of DstReg.
306 NewRC = TRI.getMatchingSuperRegClass(DstRC, SrcRC, DstSub);
308 // DstReg will be merged with a sub-register of SrcReg.
310 NewRC = TRI.getMatchingSuperRegClass(SrcRC, DstRC, SrcSub);
312 // This is a straight copy without sub-registers.
313 NewRC = TRI.getCommonSubClass(DstRC, SrcRC);
316 // The combined constraint may be impossible to satisfy.
320 // Prefer SrcReg to be a sub-register of DstReg.
321 // FIXME: Coalescer should support subregs symmetrically.
322 if (DstIdx && !SrcIdx) {
324 std::swap(SrcIdx, DstIdx);
328 CrossClass = NewRC != DstRC || NewRC != SrcRC;
330 // Check our invariants
331 assert(TargetRegisterInfo::isVirtualRegister(Src) && "Src must be virtual");
332 assert(!(TargetRegisterInfo::isPhysicalRegister(Dst) && DstSub) &&
333 "Cannot have a physical SubIdx");
339 bool CoalescerPair::flip() {
340 if (TargetRegisterInfo::isPhysicalRegister(DstReg))
342 std::swap(SrcReg, DstReg);
343 std::swap(SrcIdx, DstIdx);
348 bool CoalescerPair::isCoalescable(const MachineInstr *MI) const {
351 unsigned Src, Dst, SrcSub, DstSub;
352 if (!isMoveInstr(TRI, MI, Src, Dst, SrcSub, DstSub))
355 // Find the virtual register that is SrcReg.
358 std::swap(SrcSub, DstSub);
359 } else if (Src != SrcReg) {
363 // Now check that Dst matches DstReg.
364 if (TargetRegisterInfo::isPhysicalRegister(DstReg)) {
365 if (!TargetRegisterInfo::isPhysicalRegister(Dst))
367 assert(!DstIdx && !SrcIdx && "Inconsistent CoalescerPair state.");
368 // DstSub could be set for a physreg from INSERT_SUBREG.
370 Dst = TRI.getSubReg(Dst, DstSub);
373 return DstReg == Dst;
374 // This is a partial register copy. Check that the parts match.
375 return TRI.getSubReg(DstReg, SrcSub) == Dst;
377 // DstReg is virtual.
380 // Registers match, do the subregisters line up?
381 return TRI.composeSubRegIndices(SrcIdx, SrcSub) ==
382 TRI.composeSubRegIndices(DstIdx, DstSub);
386 void RegisterCoalescer::getAnalysisUsage(AnalysisUsage &AU) const {
387 AU.setPreservesCFG();
388 AU.addRequired<AliasAnalysis>();
389 AU.addRequired<LiveIntervals>();
390 AU.addPreserved<LiveIntervals>();
391 AU.addPreserved<SlotIndexes>();
392 AU.addRequired<MachineLoopInfo>();
393 AU.addPreserved<MachineLoopInfo>();
394 AU.addPreservedID(MachineDominatorsID);
395 MachineFunctionPass::getAnalysisUsage(AU);
398 void RegisterCoalescer::eliminateDeadDefs() {
399 SmallVector<unsigned, 8> NewRegs;
400 LiveRangeEdit(0, NewRegs, *MF, *LIS, 0, this).eliminateDeadDefs(DeadDefs);
403 // Callback from eliminateDeadDefs().
404 void RegisterCoalescer::LRE_WillEraseInstruction(MachineInstr *MI) {
405 // MI may be in WorkList. Make sure we don't visit it.
406 ErasedInstrs.insert(MI);
409 /// adjustCopiesBackFrom - We found a non-trivially-coalescable copy with IntA
410 /// being the source and IntB being the dest, thus this defines a value number
411 /// in IntB. If the source value number (in IntA) is defined by a copy from B,
412 /// see if we can merge these two pieces of B into a single value number,
413 /// eliminating a copy. For example:
417 /// B1 = A3 <- this copy
419 /// In this case, B0 can be extended to where the B1 copy lives, allowing the B1
420 /// value number to be replaced with B0 (which simplifies the B liveinterval).
422 /// This returns true if an interval was modified.
424 bool RegisterCoalescer::adjustCopiesBackFrom(const CoalescerPair &CP,
425 MachineInstr *CopyMI) {
426 assert(!CP.isPartial() && "This doesn't work for partial copies.");
427 assert(!CP.isPhys() && "This doesn't work for physreg copies.");
430 LIS->getInterval(CP.isFlipped() ? CP.getDstReg() : CP.getSrcReg());
432 LIS->getInterval(CP.isFlipped() ? CP.getSrcReg() : CP.getDstReg());
433 SlotIndex CopyIdx = LIS->getInstructionIndex(CopyMI).getRegSlot();
435 // BValNo is a value number in B that is defined by a copy from A. 'B1' in
436 // the example above.
437 LiveInterval::iterator BS = IntB.FindSegmentContaining(CopyIdx);
438 if (BS == IntB.end()) return false;
439 VNInfo *BValNo = BS->valno;
441 // Get the location that B is defined at. Two options: either this value has
442 // an unknown definition point or it is defined at CopyIdx. If unknown, we
444 if (BValNo->def != CopyIdx) return false;
446 // AValNo is the value number in A that defines the copy, A3 in the example.
447 SlotIndex CopyUseIdx = CopyIdx.getRegSlot(true);
448 LiveInterval::iterator AS = IntA.FindSegmentContaining(CopyUseIdx);
449 // The live segment might not exist after fun with physreg coalescing.
450 if (AS == IntA.end()) return false;
451 VNInfo *AValNo = AS->valno;
453 // If AValNo is defined as a copy from IntB, we can potentially process this.
454 // Get the instruction that defines this value number.
455 MachineInstr *ACopyMI = LIS->getInstructionFromIndex(AValNo->def);
456 // Don't allow any partial copies, even if isCoalescable() allows them.
457 if (!CP.isCoalescable(ACopyMI) || !ACopyMI->isFullCopy())
460 // Get the Segment in IntB that this value number starts with.
461 LiveInterval::iterator ValS =
462 IntB.FindSegmentContaining(AValNo->def.getPrevSlot());
463 if (ValS == IntB.end())
466 // Make sure that the end of the live segment is inside the same block as
468 MachineInstr *ValSEndInst =
469 LIS->getInstructionFromIndex(ValS->end.getPrevSlot());
470 if (!ValSEndInst || ValSEndInst->getParent() != CopyMI->getParent())
473 // Okay, we now know that ValS ends in the same block that the CopyMI
474 // live-range starts. If there are no intervening live segments between them
475 // in IntB, we can merge them.
476 if (ValS+1 != BS) return false;
478 DEBUG(dbgs() << "Extending: " << PrintReg(IntB.reg, TRI));
480 SlotIndex FillerStart = ValS->end, FillerEnd = BS->start;
481 // We are about to delete CopyMI, so need to remove it as the 'instruction
482 // that defines this value #'. Update the valnum with the new defining
484 BValNo->def = FillerStart;
486 // Okay, we can merge them. We need to insert a new liverange:
487 // [ValS.end, BS.begin) of either value number, then we merge the
488 // two value numbers.
489 IntB.addSegment(LiveInterval::Segment(FillerStart, FillerEnd, BValNo));
491 // Okay, merge "B1" into the same value number as "B0".
492 if (BValNo != ValS->valno)
493 IntB.MergeValueNumberInto(BValNo, ValS->valno);
494 DEBUG(dbgs() << " result = " << IntB << '\n');
496 // If the source instruction was killing the source register before the
497 // merge, unset the isKill marker given the live range has been extended.
498 int UIdx = ValSEndInst->findRegisterUseOperandIdx(IntB.reg, true);
500 ValSEndInst->getOperand(UIdx).setIsKill(false);
503 // Rewrite the copy. If the copy instruction was killing the destination
504 // register before the merge, find the last use and trim the live range. That
505 // will also add the isKill marker.
506 CopyMI->substituteRegister(IntA.reg, IntB.reg, 0, *TRI);
507 if (AS->end == CopyIdx)
508 LIS->shrinkToUses(&IntA);
514 /// hasOtherReachingDefs - Return true if there are definitions of IntB
515 /// other than BValNo val# that can reach uses of AValno val# of IntA.
516 bool RegisterCoalescer::hasOtherReachingDefs(LiveInterval &IntA,
520 // If AValNo has PHI kills, conservatively assume that IntB defs can reach
522 if (LIS->hasPHIKill(IntA, AValNo))
525 for (LiveInterval::iterator AI = IntA.begin(), AE = IntA.end();
527 if (AI->valno != AValNo) continue;
528 LiveInterval::iterator BI =
529 std::upper_bound(IntB.begin(), IntB.end(), AI->start);
530 if (BI != IntB.begin())
532 for (; BI != IntB.end() && AI->end >= BI->start; ++BI) {
533 if (BI->valno == BValNo)
535 if (BI->start <= AI->start && BI->end > AI->start)
537 if (BI->start > AI->start && BI->start < AI->end)
544 /// removeCopyByCommutingDef - We found a non-trivially-coalescable copy with
545 /// IntA being the source and IntB being the dest, thus this defines a value
546 /// number in IntB. If the source value number (in IntA) is defined by a
547 /// commutable instruction and its other operand is coalesced to the copy dest
548 /// register, see if we can transform the copy into a noop by commuting the
549 /// definition. For example,
551 /// A3 = op A2 B0<kill>
553 /// B1 = A3 <- this copy
555 /// = op A3 <- more uses
559 /// B2 = op B0 A2<kill>
561 /// B1 = B2 <- now an identify copy
563 /// = op B2 <- more uses
565 /// This returns true if an interval was modified.
567 bool RegisterCoalescer::removeCopyByCommutingDef(const CoalescerPair &CP,
568 MachineInstr *CopyMI) {
569 assert (!CP.isPhys());
571 SlotIndex CopyIdx = LIS->getInstructionIndex(CopyMI).getRegSlot();
574 LIS->getInterval(CP.isFlipped() ? CP.getDstReg() : CP.getSrcReg());
576 LIS->getInterval(CP.isFlipped() ? CP.getSrcReg() : CP.getDstReg());
578 // BValNo is a value number in B that is defined by a copy from A. 'B1' in
579 // the example above.
580 VNInfo *BValNo = IntB.getVNInfoAt(CopyIdx);
581 if (!BValNo || BValNo->def != CopyIdx)
584 // AValNo is the value number in A that defines the copy, A3 in the example.
585 VNInfo *AValNo = IntA.getVNInfoAt(CopyIdx.getRegSlot(true));
586 assert(AValNo && "COPY source not live");
587 if (AValNo->isPHIDef() || AValNo->isUnused())
589 MachineInstr *DefMI = LIS->getInstructionFromIndex(AValNo->def);
592 if (!DefMI->isCommutable())
594 // If DefMI is a two-address instruction then commuting it will change the
595 // destination register.
596 int DefIdx = DefMI->findRegisterDefOperandIdx(IntA.reg);
597 assert(DefIdx != -1);
599 if (!DefMI->isRegTiedToUseOperand(DefIdx, &UseOpIdx))
601 unsigned Op1, Op2, NewDstIdx;
602 if (!TII->findCommutedOpIndices(DefMI, Op1, Op2))
606 else if (Op2 == UseOpIdx)
611 MachineOperand &NewDstMO = DefMI->getOperand(NewDstIdx);
612 unsigned NewReg = NewDstMO.getReg();
613 if (NewReg != IntB.reg || !IntB.Query(AValNo->def).isKill())
616 // Make sure there are no other definitions of IntB that would reach the
617 // uses which the new definition can reach.
618 if (hasOtherReachingDefs(IntA, IntB, AValNo, BValNo))
621 // If some of the uses of IntA.reg is already coalesced away, return false.
622 // It's not possible to determine whether it's safe to perform the coalescing.
623 for (MachineOperand &MO : MRI->use_nodbg_operands(IntA.reg)) {
624 MachineInstr *UseMI = MO.getParent();
625 unsigned OpNo = &MO - &UseMI->getOperand(0);
626 SlotIndex UseIdx = LIS->getInstructionIndex(UseMI);
627 LiveInterval::iterator US = IntA.FindSegmentContaining(UseIdx);
628 if (US == IntA.end() || US->valno != AValNo)
630 // If this use is tied to a def, we can't rewrite the register.
631 if (UseMI->isRegTiedToDefOperand(OpNo))
635 DEBUG(dbgs() << "\tremoveCopyByCommutingDef: " << AValNo->def << '\t'
638 // At this point we have decided that it is legal to do this
639 // transformation. Start by commuting the instruction.
640 MachineBasicBlock *MBB = DefMI->getParent();
641 MachineInstr *NewMI = TII->commuteInstruction(DefMI);
644 if (TargetRegisterInfo::isVirtualRegister(IntA.reg) &&
645 TargetRegisterInfo::isVirtualRegister(IntB.reg) &&
646 !MRI->constrainRegClass(IntB.reg, MRI->getRegClass(IntA.reg)))
648 if (NewMI != DefMI) {
649 LIS->ReplaceMachineInstrInMaps(DefMI, NewMI);
650 MachineBasicBlock::iterator Pos = DefMI;
651 MBB->insert(Pos, NewMI);
654 unsigned OpIdx = NewMI->findRegisterUseOperandIdx(IntA.reg, false);
655 NewMI->getOperand(OpIdx).setIsKill();
657 // If ALR and BLR overlaps and end of BLR extends beyond end of ALR, e.g.
666 // Update uses of IntA of the specific Val# with IntB.
667 for (MachineRegisterInfo::use_iterator UI = MRI->use_begin(IntA.reg),
668 UE = MRI->use_end(); UI != UE;) {
669 MachineOperand &UseMO = *UI;
670 MachineInstr *UseMI = UseMO.getParent();
672 if (UseMI->isDebugValue()) {
673 // FIXME These don't have an instruction index. Not clear we have enough
674 // info to decide whether to do this replacement or not. For now do it.
675 UseMO.setReg(NewReg);
678 SlotIndex UseIdx = LIS->getInstructionIndex(UseMI).getRegSlot(true);
679 LiveInterval::iterator US = IntA.FindSegmentContaining(UseIdx);
680 if (US == IntA.end() || US->valno != AValNo)
682 // Kill flags are no longer accurate. They are recomputed after RA.
683 UseMO.setIsKill(false);
684 if (TargetRegisterInfo::isPhysicalRegister(NewReg))
685 UseMO.substPhysReg(NewReg, *TRI);
687 UseMO.setReg(NewReg);
690 if (!UseMI->isCopy())
692 if (UseMI->getOperand(0).getReg() != IntB.reg ||
693 UseMI->getOperand(0).getSubReg())
696 // This copy will become a noop. If it's defining a new val#, merge it into
698 SlotIndex DefIdx = UseIdx.getRegSlot();
699 VNInfo *DVNI = IntB.getVNInfoAt(DefIdx);
702 DEBUG(dbgs() << "\t\tnoop: " << DefIdx << '\t' << *UseMI);
703 assert(DVNI->def == DefIdx);
704 BValNo = IntB.MergeValueNumberInto(BValNo, DVNI);
705 ErasedInstrs.insert(UseMI);
706 LIS->RemoveMachineInstrFromMaps(UseMI);
707 UseMI->eraseFromParent();
710 // Extend BValNo by merging in IntA live segments of AValNo. Val# definition
712 VNInfo *ValNo = BValNo;
713 ValNo->def = AValNo->def;
714 for (LiveInterval::iterator AI = IntA.begin(), AE = IntA.end();
716 if (AI->valno != AValNo) continue;
717 IntB.addSegment(LiveInterval::Segment(AI->start, AI->end, ValNo));
719 DEBUG(dbgs() << "\t\textended: " << IntB << '\n');
721 IntA.removeValNo(AValNo);
722 DEBUG(dbgs() << "\t\ttrimmed: " << IntA << '\n');
727 /// reMaterializeTrivialDef - If the source of a copy is defined by a trivial
728 /// computation, replace the copy by rematerialize the definition.
729 bool RegisterCoalescer::reMaterializeTrivialDef(CoalescerPair &CP,
730 MachineInstr *CopyMI,
733 unsigned SrcReg = CP.isFlipped() ? CP.getDstReg() : CP.getSrcReg();
734 unsigned SrcIdx = CP.isFlipped() ? CP.getDstIdx() : CP.getSrcIdx();
735 unsigned DstReg = CP.isFlipped() ? CP.getSrcReg() : CP.getDstReg();
736 unsigned DstIdx = CP.isFlipped() ? CP.getSrcIdx() : CP.getDstIdx();
737 if (TargetRegisterInfo::isPhysicalRegister(SrcReg))
740 LiveInterval &SrcInt = LIS->getInterval(SrcReg);
741 SlotIndex CopyIdx = LIS->getInstructionIndex(CopyMI);
742 VNInfo *ValNo = SrcInt.Query(CopyIdx).valueIn();
743 assert(ValNo && "CopyMI input register not live");
744 if (ValNo->isPHIDef() || ValNo->isUnused())
746 MachineInstr *DefMI = LIS->getInstructionFromIndex(ValNo->def);
749 if (DefMI->isCopyLike()) {
753 if (!DefMI->isAsCheapAsAMove())
755 if (!TII->isTriviallyReMaterializable(DefMI, AA))
757 bool SawStore = false;
758 if (!DefMI->isSafeToMove(TII, AA, SawStore))
760 const MCInstrDesc &MCID = DefMI->getDesc();
761 if (MCID.getNumDefs() != 1)
763 // Only support subregister destinations when the def is read-undef.
764 MachineOperand &DstOperand = CopyMI->getOperand(0);
765 unsigned CopyDstReg = DstOperand.getReg();
766 if (DstOperand.getSubReg() && !DstOperand.isUndef())
769 // If both SrcIdx and DstIdx are set, correct rematerialization would widen
770 // the register substantially (beyond both source and dest size). This is bad
771 // for performance since it can cascade through a function, introducing many
772 // extra spills and fills (e.g. ARM can easily end up copying QQQQPR registers
773 // around after a few subreg copies).
774 if (SrcIdx && DstIdx)
777 const TargetRegisterClass *DefRC = TII->getRegClass(MCID, 0, TRI, *MF);
778 if (!DefMI->isImplicitDef()) {
779 if (TargetRegisterInfo::isPhysicalRegister(DstReg)) {
780 unsigned NewDstReg = DstReg;
782 unsigned NewDstIdx = TRI->composeSubRegIndices(CP.getSrcIdx(),
783 DefMI->getOperand(0).getSubReg());
785 NewDstReg = TRI->getSubReg(DstReg, NewDstIdx);
787 // Finally, make sure that the physical subregister that will be
788 // constructed later is permitted for the instruction.
789 if (!DefRC->contains(NewDstReg))
792 // Theoretically, some stack frame reference could exist. Just make sure
793 // it hasn't actually happened.
794 assert(TargetRegisterInfo::isVirtualRegister(DstReg) &&
795 "Only expect to deal with virtual or physical registers");
799 MachineBasicBlock *MBB = CopyMI->getParent();
800 MachineBasicBlock::iterator MII =
801 std::next(MachineBasicBlock::iterator(CopyMI));
802 TII->reMaterialize(*MBB, MII, DstReg, SrcIdx, DefMI, *TRI);
803 MachineInstr *NewMI = std::prev(MII);
805 LIS->ReplaceMachineInstrInMaps(CopyMI, NewMI);
806 CopyMI->eraseFromParent();
807 ErasedInstrs.insert(CopyMI);
809 // NewMI may have dead implicit defs (E.g. EFLAGS for MOV<bits>r0 on X86).
810 // We need to remember these so we can add intervals once we insert
811 // NewMI into SlotIndexes.
812 SmallVector<unsigned, 4> NewMIImplDefs;
813 for (unsigned i = NewMI->getDesc().getNumOperands(),
814 e = NewMI->getNumOperands(); i != e; ++i) {
815 MachineOperand &MO = NewMI->getOperand(i);
817 assert(MO.isDef() && MO.isImplicit() && MO.isDead() &&
818 TargetRegisterInfo::isPhysicalRegister(MO.getReg()));
819 NewMIImplDefs.push_back(MO.getReg());
823 if (TargetRegisterInfo::isVirtualRegister(DstReg)) {
824 const TargetRegisterClass *NewRC = CP.getNewRC();
825 unsigned NewIdx = NewMI->getOperand(0).getSubReg();
828 NewRC = TRI->getMatchingSuperRegClass(NewRC, DefRC, NewIdx);
830 NewRC = TRI->getCommonSubClass(NewRC, DefRC);
832 assert(NewRC && "subreg chosen for remat incompatible with instruction");
833 MRI->setRegClass(DstReg, NewRC);
835 updateRegDefsUses(DstReg, DstReg, DstIdx);
836 NewMI->getOperand(0).setSubReg(NewIdx);
837 } else if (NewMI->getOperand(0).getReg() != CopyDstReg) {
838 // The New instruction may be defining a sub-register of what's actually
839 // been asked for. If so it must implicitly define the whole thing.
840 assert(TargetRegisterInfo::isPhysicalRegister(DstReg) &&
841 "Only expect virtual or physical registers in remat");
842 NewMI->getOperand(0).setIsDead(true);
843 NewMI->addOperand(MachineOperand::CreateReg(CopyDstReg,
849 if (NewMI->getOperand(0).getSubReg())
850 NewMI->getOperand(0).setIsUndef();
852 // CopyMI may have implicit operands, transfer them over to the newly
853 // rematerialized instruction. And update implicit def interval valnos.
854 for (unsigned i = CopyMI->getDesc().getNumOperands(),
855 e = CopyMI->getNumOperands(); i != e; ++i) {
856 MachineOperand &MO = CopyMI->getOperand(i);
858 assert(MO.isImplicit() && "No explicit operands after implict operands.");
859 // Discard VReg implicit defs.
860 if (TargetRegisterInfo::isPhysicalRegister(MO.getReg())) {
861 NewMI->addOperand(MO);
866 SlotIndex NewMIIdx = LIS->getInstructionIndex(NewMI);
867 for (unsigned i = 0, e = NewMIImplDefs.size(); i != e; ++i) {
868 unsigned Reg = NewMIImplDefs[i];
869 for (MCRegUnitIterator Units(Reg, TRI); Units.isValid(); ++Units)
870 if (LiveRange *LR = LIS->getCachedRegUnit(*Units))
871 LR->createDeadDef(NewMIIdx.getRegSlot(), LIS->getVNInfoAllocator());
874 DEBUG(dbgs() << "Remat: " << *NewMI);
877 // The source interval can become smaller because we removed a use.
878 LIS->shrinkToUses(&SrcInt, &DeadDefs);
879 if (!DeadDefs.empty())
885 /// eliminateUndefCopy - ProcessImpicitDefs may leave some copies of <undef>
886 /// values, it only removes local variables. When we have a copy like:
888 /// %vreg1 = COPY %vreg2<undef>
890 /// We delete the copy and remove the corresponding value number from %vreg1.
891 /// Any uses of that value number are marked as <undef>.
892 bool RegisterCoalescer::eliminateUndefCopy(MachineInstr *CopyMI,
893 const CoalescerPair &CP) {
894 SlotIndex Idx = LIS->getInstructionIndex(CopyMI);
895 LiveInterval *SrcInt = &LIS->getInterval(CP.getSrcReg());
896 if (SrcInt->liveAt(Idx))
898 LiveInterval *DstInt = &LIS->getInterval(CP.getDstReg());
899 if (DstInt->liveAt(Idx))
902 // No intervals are live-in to CopyMI - it is undef.
907 VNInfo *DeadVNI = DstInt->getVNInfoAt(Idx.getRegSlot());
908 assert(DeadVNI && "No value defined in DstInt");
909 DstInt->removeValNo(DeadVNI);
911 // Find new undef uses.
912 for (MachineOperand &MO : MRI->reg_nodbg_operands(DstInt->reg)) {
913 if (MO.isDef() || MO.isUndef())
915 MachineInstr *MI = MO.getParent();
916 SlotIndex Idx = LIS->getInstructionIndex(MI);
917 if (DstInt->liveAt(Idx))
920 DEBUG(dbgs() << "\tnew undef: " << Idx << '\t' << *MI);
925 /// updateRegDefsUses - Replace all defs and uses of SrcReg to DstReg and
926 /// update the subregister number if it is not zero. If DstReg is a
927 /// physical register and the existing subregister number of the def / use
928 /// being updated is not zero, make sure to set it to the correct physical
930 void RegisterCoalescer::updateRegDefsUses(unsigned SrcReg,
933 bool DstIsPhys = TargetRegisterInfo::isPhysicalRegister(DstReg);
934 LiveInterval *DstInt = DstIsPhys ? 0 : &LIS->getInterval(DstReg);
936 SmallPtrSet<MachineInstr*, 8> Visited;
937 for (MachineRegisterInfo::reg_instr_iterator
938 I = MRI->reg_instr_begin(SrcReg), E = MRI->reg_instr_end();
940 MachineInstr *UseMI = &*(I++);
942 // Each instruction can only be rewritten once because sub-register
943 // composition is not always idempotent. When SrcReg != DstReg, rewriting
944 // the UseMI operands removes them from the SrcReg use-def chain, but when
945 // SrcReg is DstReg we could encounter UseMI twice if it has multiple
946 // operands mentioning the virtual register.
947 if (SrcReg == DstReg && !Visited.insert(UseMI))
950 SmallVector<unsigned,8> Ops;
952 std::tie(Reads, Writes) = UseMI->readsWritesVirtualRegister(SrcReg, &Ops);
954 // If SrcReg wasn't read, it may still be the case that DstReg is live-in
955 // because SrcReg is a sub-register.
956 if (DstInt && !Reads && SubIdx)
957 Reads = DstInt->liveAt(LIS->getInstructionIndex(UseMI));
959 // Replace SrcReg with DstReg in all UseMI operands.
960 for (unsigned i = 0, e = Ops.size(); i != e; ++i) {
961 MachineOperand &MO = UseMI->getOperand(Ops[i]);
963 // Adjust <undef> flags in case of sub-register joins. We don't want to
964 // turn a full def into a read-modify-write sub-register def and vice
966 if (SubIdx && MO.isDef())
967 MO.setIsUndef(!Reads);
970 MO.substPhysReg(DstReg, *TRI);
972 MO.substVirtReg(DstReg, SubIdx, *TRI);
976 dbgs() << "\t\tupdated: ";
977 if (!UseMI->isDebugValue())
978 dbgs() << LIS->getInstructionIndex(UseMI) << "\t";
984 /// canJoinPhys - Return true if a copy involving a physreg should be joined.
985 bool RegisterCoalescer::canJoinPhys(const CoalescerPair &CP) {
986 /// Always join simple intervals that are defined by a single copy from a
987 /// reserved register. This doesn't increase register pressure, so it is
988 /// always beneficial.
989 if (!MRI->isReserved(CP.getDstReg())) {
990 DEBUG(dbgs() << "\tCan only merge into reserved registers.\n");
994 LiveInterval &JoinVInt = LIS->getInterval(CP.getSrcReg());
995 if (CP.isFlipped() && JoinVInt.containsOneValue())
998 DEBUG(dbgs() << "\tCannot join defs into reserved register.\n");
1002 /// joinCopy - Attempt to join intervals corresponding to SrcReg/DstReg,
1003 /// which are the src/dst of the copy instruction CopyMI. This returns true
1004 /// if the copy was successfully coalesced away. If it is not currently
1005 /// possible to coalesce this interval, but it may be possible if other
1006 /// things get coalesced, then it returns true by reference in 'Again'.
1007 bool RegisterCoalescer::joinCopy(MachineInstr *CopyMI, bool &Again) {
1010 DEBUG(dbgs() << LIS->getInstructionIndex(CopyMI) << '\t' << *CopyMI);
1012 CoalescerPair CP(*TRI);
1013 if (!CP.setRegisters(CopyMI)) {
1014 DEBUG(dbgs() << "\tNot coalescable.\n");
1018 // Dead code elimination. This really should be handled by MachineDCE, but
1019 // sometimes dead copies slip through, and we can't generate invalid live
1021 if (!CP.isPhys() && CopyMI->allDefsAreDead()) {
1022 DEBUG(dbgs() << "\tCopy is dead.\n");
1023 DeadDefs.push_back(CopyMI);
1024 eliminateDeadDefs();
1028 // Eliminate undefs.
1029 if (!CP.isPhys() && eliminateUndefCopy(CopyMI, CP)) {
1030 DEBUG(dbgs() << "\tEliminated copy of <undef> value.\n");
1031 LIS->RemoveMachineInstrFromMaps(CopyMI);
1032 CopyMI->eraseFromParent();
1033 return false; // Not coalescable.
1036 // Coalesced copies are normally removed immediately, but transformations
1037 // like removeCopyByCommutingDef() can inadvertently create identity copies.
1038 // When that happens, just join the values and remove the copy.
1039 if (CP.getSrcReg() == CP.getDstReg()) {
1040 LiveInterval &LI = LIS->getInterval(CP.getSrcReg());
1041 DEBUG(dbgs() << "\tCopy already coalesced: " << LI << '\n');
1042 LiveQueryResult LRQ = LI.Query(LIS->getInstructionIndex(CopyMI));
1043 if (VNInfo *DefVNI = LRQ.valueDefined()) {
1044 VNInfo *ReadVNI = LRQ.valueIn();
1045 assert(ReadVNI && "No value before copy and no <undef> flag.");
1046 assert(ReadVNI != DefVNI && "Cannot read and define the same value.");
1047 LI.MergeValueNumberInto(DefVNI, ReadVNI);
1048 DEBUG(dbgs() << "\tMerged values: " << LI << '\n');
1050 LIS->RemoveMachineInstrFromMaps(CopyMI);
1051 CopyMI->eraseFromParent();
1055 // Enforce policies.
1057 DEBUG(dbgs() << "\tConsidering merging " << PrintReg(CP.getSrcReg(), TRI)
1058 << " with " << PrintReg(CP.getDstReg(), TRI, CP.getSrcIdx())
1060 if (!canJoinPhys(CP)) {
1061 // Before giving up coalescing, if definition of source is defined by
1062 // trivial computation, try rematerializing it.
1064 if (reMaterializeTrivialDef(CP, CopyMI, IsDefCopy))
1067 Again = true; // May be possible to coalesce later.
1072 dbgs() << "\tConsidering merging to " << CP.getNewRC()->getName()
1074 if (CP.getDstIdx() && CP.getSrcIdx())
1075 dbgs() << PrintReg(CP.getDstReg()) << " in "
1076 << TRI->getSubRegIndexName(CP.getDstIdx()) << " and "
1077 << PrintReg(CP.getSrcReg()) << " in "
1078 << TRI->getSubRegIndexName(CP.getSrcIdx()) << '\n';
1080 dbgs() << PrintReg(CP.getSrcReg(), TRI) << " in "
1081 << PrintReg(CP.getDstReg(), TRI, CP.getSrcIdx()) << '\n';
1084 // When possible, let DstReg be the larger interval.
1085 if (!CP.isPartial() && LIS->getInterval(CP.getSrcReg()).size() >
1086 LIS->getInterval(CP.getDstReg()).size())
1090 // Okay, attempt to join these two intervals. On failure, this returns false.
1091 // Otherwise, if one of the intervals being joined is a physreg, this method
1092 // always canonicalizes DstInt to be it. The output "SrcInt" will not have
1093 // been modified, so we can use this information below to update aliases.
1094 if (!joinIntervals(CP)) {
1095 // Coalescing failed.
1097 // If definition of source is defined by trivial computation, try
1098 // rematerializing it.
1100 if (reMaterializeTrivialDef(CP, CopyMI, IsDefCopy))
1103 // If we can eliminate the copy without merging the live segments, do so
1105 if (!CP.isPartial() && !CP.isPhys()) {
1106 if (adjustCopiesBackFrom(CP, CopyMI) ||
1107 removeCopyByCommutingDef(CP, CopyMI)) {
1108 LIS->RemoveMachineInstrFromMaps(CopyMI);
1109 CopyMI->eraseFromParent();
1110 DEBUG(dbgs() << "\tTrivial!\n");
1115 // Otherwise, we are unable to join the intervals.
1116 DEBUG(dbgs() << "\tInterference!\n");
1117 Again = true; // May be possible to coalesce later.
1121 // Coalescing to a virtual register that is of a sub-register class of the
1122 // other. Make sure the resulting register is set to the right register class.
1123 if (CP.isCrossClass()) {
1125 MRI->setRegClass(CP.getDstReg(), CP.getNewRC());
1128 // Removing sub-register copies can ease the register class constraints.
1129 // Make sure we attempt to inflate the register class of DstReg.
1130 if (!CP.isPhys() && RegClassInfo.isProperSubClass(CP.getNewRC()))
1131 InflateRegs.push_back(CP.getDstReg());
1133 // CopyMI has been erased by joinIntervals at this point. Remove it from
1134 // ErasedInstrs since copyCoalesceWorkList() won't add a successful join back
1135 // to the work list. This keeps ErasedInstrs from growing needlessly.
1136 ErasedInstrs.erase(CopyMI);
1138 // Rewrite all SrcReg operands to DstReg.
1139 // Also update DstReg operands to include DstIdx if it is set.
1141 updateRegDefsUses(CP.getDstReg(), CP.getDstReg(), CP.getDstIdx());
1142 updateRegDefsUses(CP.getSrcReg(), CP.getDstReg(), CP.getSrcIdx());
1144 // SrcReg is guaranteed to be the register whose live interval that is
1146 LIS->removeInterval(CP.getSrcReg());
1148 // Update regalloc hint.
1149 TRI->UpdateRegAllocHint(CP.getSrcReg(), CP.getDstReg(), *MF);
1152 dbgs() << "\tJoined. Result = ";
1154 dbgs() << PrintReg(CP.getDstReg(), TRI);
1156 dbgs() << LIS->getInterval(CP.getDstReg());
1164 /// Attempt joining with a reserved physreg.
1165 bool RegisterCoalescer::joinReservedPhysReg(CoalescerPair &CP) {
1166 assert(CP.isPhys() && "Must be a physreg copy");
1167 assert(MRI->isReserved(CP.getDstReg()) && "Not a reserved register");
1168 LiveInterval &RHS = LIS->getInterval(CP.getSrcReg());
1169 DEBUG(dbgs() << "\t\tRHS = " << RHS << '\n');
1171 assert(CP.isFlipped() && RHS.containsOneValue() &&
1172 "Invalid join with reserved register");
1174 // Optimization for reserved registers like ESP. We can only merge with a
1175 // reserved physreg if RHS has a single value that is a copy of CP.DstReg().
1176 // The live range of the reserved register will look like a set of dead defs
1177 // - we don't properly track the live range of reserved registers.
1179 // Deny any overlapping intervals. This depends on all the reserved
1180 // register live ranges to look like dead defs.
1181 for (MCRegUnitIterator UI(CP.getDstReg(), TRI); UI.isValid(); ++UI)
1182 if (RHS.overlaps(LIS->getRegUnit(*UI))) {
1183 DEBUG(dbgs() << "\t\tInterference: " << PrintRegUnit(*UI, TRI) << '\n');
1187 // Skip any value computations, we are not adding new values to the
1188 // reserved register. Also skip merging the live ranges, the reserved
1189 // register live range doesn't need to be accurate as long as all the
1192 // Delete the identity copy.
1193 MachineInstr *CopyMI = MRI->getVRegDef(RHS.reg);
1194 LIS->RemoveMachineInstrFromMaps(CopyMI);
1195 CopyMI->eraseFromParent();
1197 // We don't track kills for reserved registers.
1198 MRI->clearKillFlags(CP.getSrcReg());
1203 //===----------------------------------------------------------------------===//
1204 // Interference checking and interval joining
1205 //===----------------------------------------------------------------------===//
1207 // In the easiest case, the two live ranges being joined are disjoint, and
1208 // there is no interference to consider. It is quite common, though, to have
1209 // overlapping live ranges, and we need to check if the interference can be
1212 // The live range of a single SSA value forms a sub-tree of the dominator tree.
1213 // This means that two SSA values overlap if and only if the def of one value
1214 // is contained in the live range of the other value. As a special case, the
1215 // overlapping values can be defined at the same index.
1217 // The interference from an overlapping def can be resolved in these cases:
1219 // 1. Coalescable copies. The value is defined by a copy that would become an
1220 // identity copy after joining SrcReg and DstReg. The copy instruction will
1221 // be removed, and the value will be merged with the source value.
1223 // There can be several copies back and forth, causing many values to be
1224 // merged into one. We compute a list of ultimate values in the joined live
1225 // range as well as a mappings from the old value numbers.
1227 // 2. IMPLICIT_DEF. This instruction is only inserted to ensure all PHI
1228 // predecessors have a live out value. It doesn't cause real interference,
1229 // and can be merged into the value it overlaps. Like a coalescable copy, it
1230 // can be erased after joining.
1232 // 3. Copy of external value. The overlapping def may be a copy of a value that
1233 // is already in the other register. This is like a coalescable copy, but
1234 // the live range of the source register must be trimmed after erasing the
1235 // copy instruction:
1238 // %dst = COPY %ext <-- Remove this COPY, trim the live range of %ext.
1240 // 4. Clobbering undefined lanes. Vector registers are sometimes built by
1241 // defining one lane at a time:
1243 // %dst:ssub0<def,read-undef> = FOO
1245 // %dst:ssub1<def> = COPY %src
1247 // The live range of %src overlaps the %dst value defined by FOO, but
1248 // merging %src into %dst:ssub1 is only going to clobber the ssub1 lane
1249 // which was undef anyway.
1251 // The value mapping is more complicated in this case. The final live range
1252 // will have different value numbers for both FOO and BAR, but there is no
1253 // simple mapping from old to new values. It may even be necessary to add
1256 // 5. Clobbering dead lanes. A def may clobber a lane of a vector register that
1257 // is live, but never read. This can happen because we don't compute
1258 // individual live ranges per lane.
1262 // %dst:ssub1<def> = COPY %src
1264 // This kind of interference is only resolved locally. If the clobbered
1265 // lane value escapes the block, the join is aborted.
1268 /// Track information about values in a single virtual register about to be
1269 /// joined. Objects of this class are always created in pairs - one for each
1270 /// side of the CoalescerPair.
1274 // Location of this register in the final joined register.
1275 // Either CP.DstIdx or CP.SrcIdx.
1278 // Values that will be present in the final live range.
1279 SmallVectorImpl<VNInfo*> &NewVNInfo;
1281 const CoalescerPair &CP;
1283 SlotIndexes *Indexes;
1284 const TargetRegisterInfo *TRI;
1286 // Value number assignments. Maps value numbers in LI to entries in NewVNInfo.
1287 // This is suitable for passing to LiveInterval::join().
1288 SmallVector<int, 8> Assignments;
1290 // Conflict resolution for overlapping values.
1291 enum ConflictResolution {
1292 // No overlap, simply keep this value.
1295 // Merge this value into OtherVNI and erase the defining instruction.
1296 // Used for IMPLICIT_DEF, coalescable copies, and copies from external
1300 // Merge this value into OtherVNI but keep the defining instruction.
1301 // This is for the special case where OtherVNI is defined by the same
1305 // Keep this value, and have it replace OtherVNI where possible. This
1306 // complicates value mapping since OtherVNI maps to two different values
1307 // before and after this def.
1308 // Used when clobbering undefined or dead lanes.
1311 // Unresolved conflict. Visit later when all values have been mapped.
1314 // Unresolvable conflict. Abort the join.
1318 // Per-value info for LI. The lane bit masks are all relative to the final
1319 // joined register, so they can be compared directly between SrcReg and
1322 ConflictResolution Resolution;
1324 // Lanes written by this def, 0 for unanalyzed values.
1325 unsigned WriteLanes;
1327 // Lanes with defined values in this register. Other lanes are undef and
1329 unsigned ValidLanes;
1331 // Value in LI being redefined by this def.
1334 // Value in the other live range that overlaps this def, if any.
1337 // Is this value an IMPLICIT_DEF that can be erased?
1339 // IMPLICIT_DEF values should only exist at the end of a basic block that
1340 // is a predecessor to a phi-value. These IMPLICIT_DEF instructions can be
1341 // safely erased if they are overlapping a live value in the other live
1344 // Weird control flow graphs and incomplete PHI handling in
1345 // ProcessImplicitDefs can very rarely create IMPLICIT_DEF values with
1346 // longer live ranges. Such IMPLICIT_DEF values should be treated like
1348 bool ErasableImplicitDef;
1350 // True when the live range of this value will be pruned because of an
1351 // overlapping CR_Replace value in the other live range.
1354 // True once Pruned above has been computed.
1355 bool PrunedComputed;
1357 Val() : Resolution(CR_Keep), WriteLanes(0), ValidLanes(0),
1358 RedefVNI(0), OtherVNI(0), ErasableImplicitDef(false),
1359 Pruned(false), PrunedComputed(false) {}
1361 bool isAnalyzed() const { return WriteLanes != 0; }
1364 // One entry per value number in LI.
1365 SmallVector<Val, 8> Vals;
1367 unsigned computeWriteLanes(const MachineInstr *DefMI, bool &Redef);
1368 VNInfo *stripCopies(VNInfo *VNI);
1369 ConflictResolution analyzeValue(unsigned ValNo, JoinVals &Other);
1370 void computeAssignment(unsigned ValNo, JoinVals &Other);
1371 bool taintExtent(unsigned, unsigned, JoinVals&,
1372 SmallVectorImpl<std::pair<SlotIndex, unsigned> >&);
1373 bool usesLanes(MachineInstr *MI, unsigned, unsigned, unsigned);
1374 bool isPrunedValue(unsigned ValNo, JoinVals &Other);
1377 JoinVals(LiveInterval &li, unsigned subIdx,
1378 SmallVectorImpl<VNInfo*> &newVNInfo,
1379 const CoalescerPair &cp,
1381 const TargetRegisterInfo *tri)
1382 : LI(li), SubIdx(subIdx), NewVNInfo(newVNInfo), CP(cp), LIS(lis),
1383 Indexes(LIS->getSlotIndexes()), TRI(tri),
1384 Assignments(LI.getNumValNums(), -1), Vals(LI.getNumValNums())
1387 /// Analyze defs in LI and compute a value mapping in NewVNInfo.
1388 /// Returns false if any conflicts were impossible to resolve.
1389 bool mapValues(JoinVals &Other);
1391 /// Try to resolve conflicts that require all values to be mapped.
1392 /// Returns false if any conflicts were impossible to resolve.
1393 bool resolveConflicts(JoinVals &Other);
1395 /// Prune the live range of values in Other.LI where they would conflict with
1396 /// CR_Replace values in LI. Collect end points for restoring the live range
1398 void pruneValues(JoinVals &Other, SmallVectorImpl<SlotIndex> &EndPoints);
1400 /// Erase any machine instructions that have been coalesced away.
1401 /// Add erased instructions to ErasedInstrs.
1402 /// Add foreign virtual registers to ShrinkRegs if their live range ended at
1403 /// the erased instrs.
1404 void eraseInstrs(SmallPtrSet<MachineInstr*, 8> &ErasedInstrs,
1405 SmallVectorImpl<unsigned> &ShrinkRegs);
1407 /// Get the value assignments suitable for passing to LiveInterval::join.
1408 const int *getAssignments() const { return Assignments.data(); }
1410 } // end anonymous namespace
1412 /// Compute the bitmask of lanes actually written by DefMI.
1413 /// Set Redef if there are any partial register definitions that depend on the
1414 /// previous value of the register.
1415 unsigned JoinVals::computeWriteLanes(const MachineInstr *DefMI, bool &Redef) {
1417 for (ConstMIOperands MO(DefMI); MO.isValid(); ++MO) {
1418 if (!MO->isReg() || MO->getReg() != LI.reg || !MO->isDef())
1420 L |= TRI->getSubRegIndexLaneMask(
1421 TRI->composeSubRegIndices(SubIdx, MO->getSubReg()));
1428 /// Find the ultimate value that VNI was copied from.
1429 VNInfo *JoinVals::stripCopies(VNInfo *VNI) {
1430 while (!VNI->isPHIDef()) {
1431 MachineInstr *MI = Indexes->getInstructionFromIndex(VNI->def);
1432 assert(MI && "No defining instruction");
1433 if (!MI->isFullCopy())
1435 unsigned Reg = MI->getOperand(1).getReg();
1436 if (!TargetRegisterInfo::isVirtualRegister(Reg))
1438 LiveQueryResult LRQ = LIS->getInterval(Reg).Query(VNI->def);
1441 VNI = LRQ.valueIn();
1446 /// Analyze ValNo in this live range, and set all fields of Vals[ValNo].
1447 /// Return a conflict resolution when possible, but leave the hard cases as
1449 /// Recursively calls computeAssignment() on this and Other, guaranteeing that
1450 /// both OtherVNI and RedefVNI have been analyzed and mapped before returning.
1451 /// The recursion always goes upwards in the dominator tree, making loops
1453 JoinVals::ConflictResolution
1454 JoinVals::analyzeValue(unsigned ValNo, JoinVals &Other) {
1455 Val &V = Vals[ValNo];
1456 assert(!V.isAnalyzed() && "Value has already been analyzed!");
1457 VNInfo *VNI = LI.getValNumInfo(ValNo);
1458 if (VNI->isUnused()) {
1463 // Get the instruction defining this value, compute the lanes written.
1464 const MachineInstr *DefMI = 0;
1465 if (VNI->isPHIDef()) {
1466 // Conservatively assume that all lanes in a PHI are valid.
1467 V.ValidLanes = V.WriteLanes = TRI->getSubRegIndexLaneMask(SubIdx);
1469 DefMI = Indexes->getInstructionFromIndex(VNI->def);
1471 V.ValidLanes = V.WriteLanes = computeWriteLanes(DefMI, Redef);
1473 // If this is a read-modify-write instruction, there may be more valid
1474 // lanes than the ones written by this instruction.
1475 // This only covers partial redef operands. DefMI may have normal use
1476 // operands reading the register. They don't contribute valid lanes.
1478 // This adds ssub1 to the set of valid lanes in %src:
1480 // %src:ssub1<def> = FOO
1482 // This leaves only ssub1 valid, making any other lanes undef:
1484 // %src:ssub1<def,read-undef> = FOO %src:ssub2
1486 // The <read-undef> flag on the def operand means that old lane values are
1489 V.RedefVNI = LI.Query(VNI->def).valueIn();
1490 assert(V.RedefVNI && "Instruction is reading nonexistent value");
1491 computeAssignment(V.RedefVNI->id, Other);
1492 V.ValidLanes |= Vals[V.RedefVNI->id].ValidLanes;
1495 // An IMPLICIT_DEF writes undef values.
1496 if (DefMI->isImplicitDef()) {
1497 // We normally expect IMPLICIT_DEF values to be live only until the end
1498 // of their block. If the value is really live longer and gets pruned in
1499 // another block, this flag is cleared again.
1500 V.ErasableImplicitDef = true;
1501 V.ValidLanes &= ~V.WriteLanes;
1505 // Find the value in Other that overlaps VNI->def, if any.
1506 LiveQueryResult OtherLRQ = Other.LI.Query(VNI->def);
1508 // It is possible that both values are defined by the same instruction, or
1509 // the values are PHIs defined in the same block. When that happens, the two
1510 // values should be merged into one, but not into any preceding value.
1511 // The first value defined or visited gets CR_Keep, the other gets CR_Merge.
1512 if (VNInfo *OtherVNI = OtherLRQ.valueDefined()) {
1513 assert(SlotIndex::isSameInstr(VNI->def, OtherVNI->def) && "Broken LRQ");
1515 // One value stays, the other is merged. Keep the earlier one, or the first
1517 if (OtherVNI->def < VNI->def)
1518 Other.computeAssignment(OtherVNI->id, *this);
1519 else if (VNI->def < OtherVNI->def && OtherLRQ.valueIn()) {
1520 // This is an early-clobber def overlapping a live-in value in the other
1521 // register. Not mergeable.
1522 V.OtherVNI = OtherLRQ.valueIn();
1523 return CR_Impossible;
1525 V.OtherVNI = OtherVNI;
1526 Val &OtherV = Other.Vals[OtherVNI->id];
1527 // Keep this value, check for conflicts when analyzing OtherVNI.
1528 if (!OtherV.isAnalyzed())
1530 // Both sides have been analyzed now.
1531 // Allow overlapping PHI values. Any real interference would show up in a
1532 // predecessor, the PHI itself can't introduce any conflicts.
1533 if (VNI->isPHIDef())
1535 if (V.ValidLanes & OtherV.ValidLanes)
1536 // Overlapping lanes can't be resolved.
1537 return CR_Impossible;
1542 // No simultaneous def. Is Other live at the def?
1543 V.OtherVNI = OtherLRQ.valueIn();
1545 // No overlap, no conflict.
1548 assert(!SlotIndex::isSameInstr(VNI->def, V.OtherVNI->def) && "Broken LRQ");
1550 // We have overlapping values, or possibly a kill of Other.
1551 // Recursively compute assignments up the dominator tree.
1552 Other.computeAssignment(V.OtherVNI->id, *this);
1553 Val &OtherV = Other.Vals[V.OtherVNI->id];
1555 // Check if OtherV is an IMPLICIT_DEF that extends beyond its basic block.
1556 // This shouldn't normally happen, but ProcessImplicitDefs can leave such
1557 // IMPLICIT_DEF instructions behind, and there is nothing wrong with it
1560 // WHen it happens, treat that IMPLICIT_DEF as a normal value, and don't try
1561 // to erase the IMPLICIT_DEF instruction.
1562 if (OtherV.ErasableImplicitDef && DefMI &&
1563 DefMI->getParent() != Indexes->getMBBFromIndex(V.OtherVNI->def)) {
1564 DEBUG(dbgs() << "IMPLICIT_DEF defined at " << V.OtherVNI->def
1565 << " extends into BB#" << DefMI->getParent()->getNumber()
1566 << ", keeping it.\n");
1567 OtherV.ErasableImplicitDef = false;
1570 // Allow overlapping PHI values. Any real interference would show up in a
1571 // predecessor, the PHI itself can't introduce any conflicts.
1572 if (VNI->isPHIDef())
1575 // Check for simple erasable conflicts.
1576 if (DefMI->isImplicitDef())
1579 // Include the non-conflict where DefMI is a coalescable copy that kills
1580 // OtherVNI. We still want the copy erased and value numbers merged.
1581 if (CP.isCoalescable(DefMI)) {
1582 // Some of the lanes copied from OtherVNI may be undef, making them undef
1584 V.ValidLanes &= ~V.WriteLanes | OtherV.ValidLanes;
1588 // This may not be a real conflict if DefMI simply kills Other and defines
1590 if (OtherLRQ.isKill() && OtherLRQ.endPoint() <= VNI->def)
1593 // Handle the case where VNI and OtherVNI can be proven to be identical:
1595 // %other = COPY %ext
1596 // %this = COPY %ext <-- Erase this copy
1598 if (DefMI->isFullCopy() && !CP.isPartial() &&
1599 stripCopies(VNI) == stripCopies(V.OtherVNI))
1602 // If the lanes written by this instruction were all undef in OtherVNI, it is
1603 // still safe to join the live ranges. This can't be done with a simple value
1604 // mapping, though - OtherVNI will map to multiple values:
1606 // 1 %dst:ssub0 = FOO <-- OtherVNI
1607 // 2 %src = BAR <-- VNI
1608 // 3 %dst:ssub1 = COPY %src<kill> <-- Eliminate this copy.
1610 // 5 QUUX %src<kill>
1612 // Here OtherVNI will map to itself in [1;2), but to VNI in [2;5). CR_Replace
1613 // handles this complex value mapping.
1614 if ((V.WriteLanes & OtherV.ValidLanes) == 0)
1617 // If the other live range is killed by DefMI and the live ranges are still
1618 // overlapping, it must be because we're looking at an early clobber def:
1620 // %dst<def,early-clobber> = ASM %src<kill>
1622 // In this case, it is illegal to merge the two live ranges since the early
1623 // clobber def would clobber %src before it was read.
1624 if (OtherLRQ.isKill()) {
1625 // This case where the def doesn't overlap the kill is handled above.
1626 assert(VNI->def.isEarlyClobber() &&
1627 "Only early clobber defs can overlap a kill");
1628 return CR_Impossible;
1631 // VNI is clobbering live lanes in OtherVNI, but there is still the
1632 // possibility that no instructions actually read the clobbered lanes.
1633 // If we're clobbering all the lanes in OtherVNI, at least one must be read.
1634 // Otherwise Other.LI wouldn't be live here.
1635 if ((TRI->getSubRegIndexLaneMask(Other.SubIdx) & ~V.WriteLanes) == 0)
1636 return CR_Impossible;
1638 // We need to verify that no instructions are reading the clobbered lanes. To
1639 // save compile time, we'll only check that locally. Don't allow the tainted
1640 // value to escape the basic block.
1641 MachineBasicBlock *MBB = Indexes->getMBBFromIndex(VNI->def);
1642 if (OtherLRQ.endPoint() >= Indexes->getMBBEndIdx(MBB))
1643 return CR_Impossible;
1645 // There are still some things that could go wrong besides clobbered lanes
1646 // being read, for example OtherVNI may be only partially redefined in MBB,
1647 // and some clobbered lanes could escape the block. Save this analysis for
1648 // resolveConflicts() when all values have been mapped. We need to know
1649 // RedefVNI and WriteLanes for any later defs in MBB, and we can't compute
1650 // that now - the recursive analyzeValue() calls must go upwards in the
1652 return CR_Unresolved;
1655 /// Compute the value assignment for ValNo in LI.
1656 /// This may be called recursively by analyzeValue(), but never for a ValNo on
1658 void JoinVals::computeAssignment(unsigned ValNo, JoinVals &Other) {
1659 Val &V = Vals[ValNo];
1660 if (V.isAnalyzed()) {
1661 // Recursion should always move up the dominator tree, so ValNo is not
1662 // supposed to reappear before it has been assigned.
1663 assert(Assignments[ValNo] != -1 && "Bad recursion?");
1666 switch ((V.Resolution = analyzeValue(ValNo, Other))) {
1669 // Merge this ValNo into OtherVNI.
1670 assert(V.OtherVNI && "OtherVNI not assigned, can't merge.");
1671 assert(Other.Vals[V.OtherVNI->id].isAnalyzed() && "Missing recursion");
1672 Assignments[ValNo] = Other.Assignments[V.OtherVNI->id];
1673 DEBUG(dbgs() << "\t\tmerge " << PrintReg(LI.reg) << ':' << ValNo << '@'
1674 << LI.getValNumInfo(ValNo)->def << " into "
1675 << PrintReg(Other.LI.reg) << ':' << V.OtherVNI->id << '@'
1676 << V.OtherVNI->def << " --> @"
1677 << NewVNInfo[Assignments[ValNo]]->def << '\n');
1681 // The other value is going to be pruned if this join is successful.
1682 assert(V.OtherVNI && "OtherVNI not assigned, can't prune");
1683 Other.Vals[V.OtherVNI->id].Pruned = true;
1686 // This value number needs to go in the final joined live range.
1687 Assignments[ValNo] = NewVNInfo.size();
1688 NewVNInfo.push_back(LI.getValNumInfo(ValNo));
1693 bool JoinVals::mapValues(JoinVals &Other) {
1694 for (unsigned i = 0, e = LI.getNumValNums(); i != e; ++i) {
1695 computeAssignment(i, Other);
1696 if (Vals[i].Resolution == CR_Impossible) {
1697 DEBUG(dbgs() << "\t\tinterference at " << PrintReg(LI.reg) << ':' << i
1698 << '@' << LI.getValNumInfo(i)->def << '\n');
1705 /// Assuming ValNo is going to clobber some valid lanes in Other.LI, compute
1706 /// the extent of the tainted lanes in the block.
1708 /// Multiple values in Other.LI can be affected since partial redefinitions can
1709 /// preserve previously tainted lanes.
1711 /// 1 %dst = VLOAD <-- Define all lanes in %dst
1712 /// 2 %src = FOO <-- ValNo to be joined with %dst:ssub0
1713 /// 3 %dst:ssub1 = BAR <-- Partial redef doesn't clear taint in ssub0
1714 /// 4 %dst:ssub0 = COPY %src <-- Conflict resolved, ssub0 wasn't read
1716 /// For each ValNo in Other that is affected, add an (EndIndex, TaintedLanes)
1717 /// entry to TaintedVals.
1719 /// Returns false if the tainted lanes extend beyond the basic block.
1721 taintExtent(unsigned ValNo, unsigned TaintedLanes, JoinVals &Other,
1722 SmallVectorImpl<std::pair<SlotIndex, unsigned> > &TaintExtent) {
1723 VNInfo *VNI = LI.getValNumInfo(ValNo);
1724 MachineBasicBlock *MBB = Indexes->getMBBFromIndex(VNI->def);
1725 SlotIndex MBBEnd = Indexes->getMBBEndIdx(MBB);
1727 // Scan Other.LI from VNI.def to MBBEnd.
1728 LiveInterval::iterator OtherI = Other.LI.find(VNI->def);
1729 assert(OtherI != Other.LI.end() && "No conflict?");
1731 // OtherI is pointing to a tainted value. Abort the join if the tainted
1732 // lanes escape the block.
1733 SlotIndex End = OtherI->end;
1734 if (End >= MBBEnd) {
1735 DEBUG(dbgs() << "\t\ttaints global " << PrintReg(Other.LI.reg) << ':'
1736 << OtherI->valno->id << '@' << OtherI->start << '\n');
1739 DEBUG(dbgs() << "\t\ttaints local " << PrintReg(Other.LI.reg) << ':'
1740 << OtherI->valno->id << '@' << OtherI->start
1741 << " to " << End << '\n');
1742 // A dead def is not a problem.
1745 TaintExtent.push_back(std::make_pair(End, TaintedLanes));
1747 // Check for another def in the MBB.
1748 if (++OtherI == Other.LI.end() || OtherI->start >= MBBEnd)
1751 // Lanes written by the new def are no longer tainted.
1752 const Val &OV = Other.Vals[OtherI->valno->id];
1753 TaintedLanes &= ~OV.WriteLanes;
1756 } while (TaintedLanes);
1760 /// Return true if MI uses any of the given Lanes from Reg.
1761 /// This does not include partial redefinitions of Reg.
1762 bool JoinVals::usesLanes(MachineInstr *MI, unsigned Reg, unsigned SubIdx,
1764 if (MI->isDebugValue())
1766 for (ConstMIOperands MO(MI); MO.isValid(); ++MO) {
1767 if (!MO->isReg() || MO->isDef() || MO->getReg() != Reg)
1769 if (!MO->readsReg())
1771 if (Lanes & TRI->getSubRegIndexLaneMask(
1772 TRI->composeSubRegIndices(SubIdx, MO->getSubReg())))
1778 bool JoinVals::resolveConflicts(JoinVals &Other) {
1779 for (unsigned i = 0, e = LI.getNumValNums(); i != e; ++i) {
1781 assert (V.Resolution != CR_Impossible && "Unresolvable conflict");
1782 if (V.Resolution != CR_Unresolved)
1784 DEBUG(dbgs() << "\t\tconflict at " << PrintReg(LI.reg) << ':' << i
1785 << '@' << LI.getValNumInfo(i)->def << '\n');
1787 assert(V.OtherVNI && "Inconsistent conflict resolution.");
1788 VNInfo *VNI = LI.getValNumInfo(i);
1789 const Val &OtherV = Other.Vals[V.OtherVNI->id];
1791 // VNI is known to clobber some lanes in OtherVNI. If we go ahead with the
1792 // join, those lanes will be tainted with a wrong value. Get the extent of
1793 // the tainted lanes.
1794 unsigned TaintedLanes = V.WriteLanes & OtherV.ValidLanes;
1795 SmallVector<std::pair<SlotIndex, unsigned>, 8> TaintExtent;
1796 if (!taintExtent(i, TaintedLanes, Other, TaintExtent))
1797 // Tainted lanes would extend beyond the basic block.
1800 assert(!TaintExtent.empty() && "There should be at least one conflict.");
1802 // Now look at the instructions from VNI->def to TaintExtent (inclusive).
1803 MachineBasicBlock *MBB = Indexes->getMBBFromIndex(VNI->def);
1804 MachineBasicBlock::iterator MI = MBB->begin();
1805 if (!VNI->isPHIDef()) {
1806 MI = Indexes->getInstructionFromIndex(VNI->def);
1807 // No need to check the instruction defining VNI for reads.
1810 assert(!SlotIndex::isSameInstr(VNI->def, TaintExtent.front().first) &&
1811 "Interference ends on VNI->def. Should have been handled earlier");
1812 MachineInstr *LastMI =
1813 Indexes->getInstructionFromIndex(TaintExtent.front().first);
1814 assert(LastMI && "Range must end at a proper instruction");
1815 unsigned TaintNum = 0;
1817 assert(MI != MBB->end() && "Bad LastMI");
1818 if (usesLanes(MI, Other.LI.reg, Other.SubIdx, TaintedLanes)) {
1819 DEBUG(dbgs() << "\t\ttainted lanes used by: " << *MI);
1822 // LastMI is the last instruction to use the current value.
1823 if (&*MI == LastMI) {
1824 if (++TaintNum == TaintExtent.size())
1826 LastMI = Indexes->getInstructionFromIndex(TaintExtent[TaintNum].first);
1827 assert(LastMI && "Range must end at a proper instruction");
1828 TaintedLanes = TaintExtent[TaintNum].second;
1833 // The tainted lanes are unused.
1834 V.Resolution = CR_Replace;
1840 // Determine if ValNo is a copy of a value number in LI or Other.LI that will
1844 // %src = COPY %dst <-- This value to be pruned.
1845 // %dst = COPY %src <-- This value is a copy of a pruned value.
1847 bool JoinVals::isPrunedValue(unsigned ValNo, JoinVals &Other) {
1848 Val &V = Vals[ValNo];
1849 if (V.Pruned || V.PrunedComputed)
1852 if (V.Resolution != CR_Erase && V.Resolution != CR_Merge)
1855 // Follow copies up the dominator tree and check if any intermediate value
1857 V.PrunedComputed = true;
1858 V.Pruned = Other.isPrunedValue(V.OtherVNI->id, *this);
1862 void JoinVals::pruneValues(JoinVals &Other,
1863 SmallVectorImpl<SlotIndex> &EndPoints) {
1864 for (unsigned i = 0, e = LI.getNumValNums(); i != e; ++i) {
1865 SlotIndex Def = LI.getValNumInfo(i)->def;
1866 switch (Vals[i].Resolution) {
1870 // This value takes precedence over the value in Other.LI.
1871 LIS->pruneValue(&Other.LI, Def, &EndPoints);
1872 // Check if we're replacing an IMPLICIT_DEF value. The IMPLICIT_DEF
1873 // instructions are only inserted to provide a live-out value for PHI
1874 // predecessors, so the instruction should simply go away once its value
1875 // has been replaced.
1876 Val &OtherV = Other.Vals[Vals[i].OtherVNI->id];
1877 bool EraseImpDef = OtherV.ErasableImplicitDef &&
1878 OtherV.Resolution == CR_Keep;
1879 if (!Def.isBlock()) {
1880 // Remove <def,read-undef> flags. This def is now a partial redef.
1881 // Also remove <def,dead> flags since the joined live range will
1882 // continue past this instruction.
1883 for (MIOperands MO(Indexes->getInstructionFromIndex(Def));
1885 if (MO->isReg() && MO->isDef() && MO->getReg() == LI.reg) {
1886 MO->setIsUndef(EraseImpDef);
1887 MO->setIsDead(false);
1889 // This value will reach instructions below, but we need to make sure
1890 // the live range also reaches the instruction at Def.
1892 EndPoints.push_back(Def);
1894 DEBUG(dbgs() << "\t\tpruned " << PrintReg(Other.LI.reg) << " at " << Def
1895 << ": " << Other.LI << '\n');
1900 if (isPrunedValue(i, Other)) {
1901 // This value is ultimately a copy of a pruned value in LI or Other.LI.
1902 // We can no longer trust the value mapping computed by
1903 // computeAssignment(), the value that was originally copied could have
1905 LIS->pruneValue(&LI, Def, &EndPoints);
1906 DEBUG(dbgs() << "\t\tpruned all of " << PrintReg(LI.reg) << " at "
1907 << Def << ": " << LI << '\n');
1912 llvm_unreachable("Unresolved conflicts");
1917 void JoinVals::eraseInstrs(SmallPtrSet<MachineInstr*, 8> &ErasedInstrs,
1918 SmallVectorImpl<unsigned> &ShrinkRegs) {
1919 for (unsigned i = 0, e = LI.getNumValNums(); i != e; ++i) {
1920 // Get the def location before markUnused() below invalidates it.
1921 SlotIndex Def = LI.getValNumInfo(i)->def;
1922 switch (Vals[i].Resolution) {
1924 // If an IMPLICIT_DEF value is pruned, it doesn't serve a purpose any
1925 // longer. The IMPLICIT_DEF instructions are only inserted by
1926 // PHIElimination to guarantee that all PHI predecessors have a value.
1927 if (!Vals[i].ErasableImplicitDef || !Vals[i].Pruned)
1929 // Remove value number i from LI. Note that this VNInfo is still present
1930 // in NewVNInfo, so it will appear as an unused value number in the final
1932 LI.getValNumInfo(i)->markUnused();
1933 LI.removeValNo(LI.getValNumInfo(i));
1934 DEBUG(dbgs() << "\t\tremoved " << i << '@' << Def << ": " << LI << '\n');
1938 MachineInstr *MI = Indexes->getInstructionFromIndex(Def);
1939 assert(MI && "No instruction to erase");
1941 unsigned Reg = MI->getOperand(1).getReg();
1942 if (TargetRegisterInfo::isVirtualRegister(Reg) &&
1943 Reg != CP.getSrcReg() && Reg != CP.getDstReg())
1944 ShrinkRegs.push_back(Reg);
1946 ErasedInstrs.insert(MI);
1947 DEBUG(dbgs() << "\t\terased:\t" << Def << '\t' << *MI);
1948 LIS->RemoveMachineInstrFromMaps(MI);
1949 MI->eraseFromParent();
1958 bool RegisterCoalescer::joinVirtRegs(CoalescerPair &CP) {
1959 SmallVector<VNInfo*, 16> NewVNInfo;
1960 LiveInterval &RHS = LIS->getInterval(CP.getSrcReg());
1961 LiveInterval &LHS = LIS->getInterval(CP.getDstReg());
1962 JoinVals RHSVals(RHS, CP.getSrcIdx(), NewVNInfo, CP, LIS, TRI);
1963 JoinVals LHSVals(LHS, CP.getDstIdx(), NewVNInfo, CP, LIS, TRI);
1965 DEBUG(dbgs() << "\t\tRHS = " << RHS
1966 << "\n\t\tLHS = " << LHS
1969 // First compute NewVNInfo and the simple value mappings.
1970 // Detect impossible conflicts early.
1971 if (!LHSVals.mapValues(RHSVals) || !RHSVals.mapValues(LHSVals))
1974 // Some conflicts can only be resolved after all values have been mapped.
1975 if (!LHSVals.resolveConflicts(RHSVals) || !RHSVals.resolveConflicts(LHSVals))
1978 // All clear, the live ranges can be merged.
1980 // The merging algorithm in LiveInterval::join() can't handle conflicting
1981 // value mappings, so we need to remove any live ranges that overlap a
1982 // CR_Replace resolution. Collect a set of end points that can be used to
1983 // restore the live range after joining.
1984 SmallVector<SlotIndex, 8> EndPoints;
1985 LHSVals.pruneValues(RHSVals, EndPoints);
1986 RHSVals.pruneValues(LHSVals, EndPoints);
1988 // Erase COPY and IMPLICIT_DEF instructions. This may cause some external
1989 // registers to require trimming.
1990 SmallVector<unsigned, 8> ShrinkRegs;
1991 LHSVals.eraseInstrs(ErasedInstrs, ShrinkRegs);
1992 RHSVals.eraseInstrs(ErasedInstrs, ShrinkRegs);
1993 while (!ShrinkRegs.empty())
1994 LIS->shrinkToUses(&LIS->getInterval(ShrinkRegs.pop_back_val()));
1996 // Join RHS into LHS.
1997 LHS.join(RHS, LHSVals.getAssignments(), RHSVals.getAssignments(), NewVNInfo);
1999 // Kill flags are going to be wrong if the live ranges were overlapping.
2000 // Eventually, we should simply clear all kill flags when computing live
2001 // ranges. They are reinserted after register allocation.
2002 MRI->clearKillFlags(LHS.reg);
2003 MRI->clearKillFlags(RHS.reg);
2005 if (EndPoints.empty())
2008 // Recompute the parts of the live range we had to remove because of
2009 // CR_Replace conflicts.
2010 DEBUG(dbgs() << "\t\trestoring liveness to " << EndPoints.size()
2011 << " points: " << LHS << '\n');
2012 LIS->extendToIndices(LHS, EndPoints);
2016 /// joinIntervals - Attempt to join these two intervals. On failure, this
2018 bool RegisterCoalescer::joinIntervals(CoalescerPair &CP) {
2019 return CP.isPhys() ? joinReservedPhysReg(CP) : joinVirtRegs(CP);
2023 // Information concerning MBB coalescing priority.
2024 struct MBBPriorityInfo {
2025 MachineBasicBlock *MBB;
2029 MBBPriorityInfo(MachineBasicBlock *mbb, unsigned depth, bool issplit)
2030 : MBB(mbb), Depth(depth), IsSplit(issplit) {}
2034 // C-style comparator that sorts first based on the loop depth of the basic
2035 // block (the unsigned), and then on the MBB number.
2037 // EnableGlobalCopies assumes that the primary sort key is loop depth.
2038 static int compareMBBPriority(const MBBPriorityInfo *LHS,
2039 const MBBPriorityInfo *RHS) {
2040 // Deeper loops first
2041 if (LHS->Depth != RHS->Depth)
2042 return LHS->Depth > RHS->Depth ? -1 : 1;
2044 // Try to unsplit critical edges next.
2045 if (LHS->IsSplit != RHS->IsSplit)
2046 return LHS->IsSplit ? -1 : 1;
2048 // Prefer blocks that are more connected in the CFG. This takes care of
2049 // the most difficult copies first while intervals are short.
2050 unsigned cl = LHS->MBB->pred_size() + LHS->MBB->succ_size();
2051 unsigned cr = RHS->MBB->pred_size() + RHS->MBB->succ_size();
2053 return cl > cr ? -1 : 1;
2055 // As a last resort, sort by block number.
2056 return LHS->MBB->getNumber() < RHS->MBB->getNumber() ? -1 : 1;
2059 /// \returns true if the given copy uses or defines a local live range.
2060 static bool isLocalCopy(MachineInstr *Copy, const LiveIntervals *LIS) {
2061 if (!Copy->isCopy())
2064 if (Copy->getOperand(1).isUndef())
2067 unsigned SrcReg = Copy->getOperand(1).getReg();
2068 unsigned DstReg = Copy->getOperand(0).getReg();
2069 if (TargetRegisterInfo::isPhysicalRegister(SrcReg)
2070 || TargetRegisterInfo::isPhysicalRegister(DstReg))
2073 return LIS->intervalIsInOneMBB(LIS->getInterval(SrcReg))
2074 || LIS->intervalIsInOneMBB(LIS->getInterval(DstReg));
2077 // Try joining WorkList copies starting from index From.
2078 // Null out any successful joins.
2079 bool RegisterCoalescer::
2080 copyCoalesceWorkList(MutableArrayRef<MachineInstr*> CurrList) {
2081 bool Progress = false;
2082 for (unsigned i = 0, e = CurrList.size(); i != e; ++i) {
2085 // Skip instruction pointers that have already been erased, for example by
2086 // dead code elimination.
2087 if (ErasedInstrs.erase(CurrList[i])) {
2092 bool Success = joinCopy(CurrList[i], Again);
2093 Progress |= Success;
2094 if (Success || !Again)
2101 RegisterCoalescer::copyCoalesceInMBB(MachineBasicBlock *MBB) {
2102 DEBUG(dbgs() << MBB->getName() << ":\n");
2104 // Collect all copy-like instructions in MBB. Don't start coalescing anything
2105 // yet, it might invalidate the iterator.
2106 const unsigned PrevSize = WorkList.size();
2107 if (JoinGlobalCopies) {
2108 // Coalesce copies bottom-up to coalesce local defs before local uses. They
2109 // are not inherently easier to resolve, but slightly preferable until we
2110 // have local live range splitting. In particular this is required by
2111 // cmp+jmp macro fusion.
2112 for (MachineBasicBlock::iterator MII = MBB->begin(), E = MBB->end();
2114 if (!MII->isCopyLike())
2116 if (isLocalCopy(&(*MII), LIS))
2117 LocalWorkList.push_back(&(*MII));
2119 WorkList.push_back(&(*MII));
2123 for (MachineBasicBlock::iterator MII = MBB->begin(), E = MBB->end();
2125 if (MII->isCopyLike())
2126 WorkList.push_back(MII);
2128 // Try coalescing the collected copies immediately, and remove the nulls.
2129 // This prevents the WorkList from getting too large since most copies are
2130 // joinable on the first attempt.
2131 MutableArrayRef<MachineInstr*>
2132 CurrList(WorkList.begin() + PrevSize, WorkList.end());
2133 if (copyCoalesceWorkList(CurrList))
2134 WorkList.erase(std::remove(WorkList.begin() + PrevSize, WorkList.end(),
2135 (MachineInstr*)0), WorkList.end());
2138 void RegisterCoalescer::coalesceLocals() {
2139 copyCoalesceWorkList(LocalWorkList);
2140 for (unsigned j = 0, je = LocalWorkList.size(); j != je; ++j) {
2141 if (LocalWorkList[j])
2142 WorkList.push_back(LocalWorkList[j]);
2144 LocalWorkList.clear();
2147 void RegisterCoalescer::joinAllIntervals() {
2148 DEBUG(dbgs() << "********** JOINING INTERVALS ***********\n");
2149 assert(WorkList.empty() && LocalWorkList.empty() && "Old data still around.");
2151 std::vector<MBBPriorityInfo> MBBs;
2152 MBBs.reserve(MF->size());
2153 for (MachineFunction::iterator I = MF->begin(), E = MF->end();I != E;++I){
2154 MachineBasicBlock *MBB = I;
2155 MBBs.push_back(MBBPriorityInfo(MBB, Loops->getLoopDepth(MBB),
2156 JoinSplitEdges && isSplitEdge(MBB)));
2158 array_pod_sort(MBBs.begin(), MBBs.end(), compareMBBPriority);
2160 // Coalesce intervals in MBB priority order.
2161 unsigned CurrDepth = UINT_MAX;
2162 for (unsigned i = 0, e = MBBs.size(); i != e; ++i) {
2163 // Try coalescing the collected local copies for deeper loops.
2164 if (JoinGlobalCopies && MBBs[i].Depth < CurrDepth) {
2166 CurrDepth = MBBs[i].Depth;
2168 copyCoalesceInMBB(MBBs[i].MBB);
2172 // Joining intervals can allow other intervals to be joined. Iteratively join
2173 // until we make no progress.
2174 while (copyCoalesceWorkList(WorkList))
2178 void RegisterCoalescer::releaseMemory() {
2179 ErasedInstrs.clear();
2182 InflateRegs.clear();
2185 bool RegisterCoalescer::runOnMachineFunction(MachineFunction &fn) {
2187 MRI = &fn.getRegInfo();
2188 TM = &fn.getTarget();
2189 TRI = TM->getRegisterInfo();
2190 TII = TM->getInstrInfo();
2191 LIS = &getAnalysis<LiveIntervals>();
2192 AA = &getAnalysis<AliasAnalysis>();
2193 Loops = &getAnalysis<MachineLoopInfo>();
2195 const TargetSubtargetInfo &ST = TM->getSubtarget<TargetSubtargetInfo>();
2196 if (EnableGlobalCopies == cl::BOU_UNSET)
2197 JoinGlobalCopies = ST.useMachineScheduler();
2199 JoinGlobalCopies = (EnableGlobalCopies == cl::BOU_TRUE);
2201 // The MachineScheduler does not currently require JoinSplitEdges. This will
2202 // either be enabled unconditionally or replaced by a more general live range
2203 // splitting optimization.
2204 JoinSplitEdges = EnableJoinSplits;
2206 DEBUG(dbgs() << "********** SIMPLE REGISTER COALESCING **********\n"
2207 << "********** Function: " << MF->getName() << '\n');
2209 if (VerifyCoalescing)
2210 MF->verify(this, "Before register coalescing");
2212 RegClassInfo.runOnMachineFunction(fn);
2214 // Join (coalesce) intervals if requested.
2218 // After deleting a lot of copies, register classes may be less constrained.
2219 // Removing sub-register operands may allow GR32_ABCD -> GR32 and DPR_VFP2 ->
2221 array_pod_sort(InflateRegs.begin(), InflateRegs.end());
2222 InflateRegs.erase(std::unique(InflateRegs.begin(), InflateRegs.end()),
2224 DEBUG(dbgs() << "Trying to inflate " << InflateRegs.size() << " regs.\n");
2225 for (unsigned i = 0, e = InflateRegs.size(); i != e; ++i) {
2226 unsigned Reg = InflateRegs[i];
2227 if (MRI->reg_nodbg_empty(Reg))
2229 if (MRI->recomputeRegClass(Reg, *TM)) {
2230 DEBUG(dbgs() << PrintReg(Reg) << " inflated to "
2231 << MRI->getRegClass(Reg)->getName() << '\n');
2237 if (VerifyCoalescing)
2238 MF->verify(this, "After register coalescing");
2242 /// print - Implement the dump method.
2243 void RegisterCoalescer::print(raw_ostream &O, const Module* m) const {