LLVM 23.0.0git
TwoAddressInstructionPass.cpp
Go to the documentation of this file.
1//===- TwoAddressInstructionPass.cpp - Two-Address instruction pass -------===//
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 TwoAddress instruction pass which is used
10// by most register allocators. Two-Address instructions are rewritten
11// from:
12//
13// A = B op C
14//
15// to:
16//
17// A = B
18// A op= C
19//
20// Note that if a register allocator chooses to use this pass, that it
21// has to be capable of handling the non-SSA nature of these rewritten
22// virtual registers.
23//
24// It is also worth noting that the duplicate operand of the two
25// address instruction is removed.
26//
27//===----------------------------------------------------------------------===//
28
30#include "llvm/ADT/DenseMap.h"
33#include "llvm/ADT/Statistic.h"
48#include "llvm/CodeGen/Passes.h"
54#include "llvm/MC/MCInstrDesc.h"
55#include "llvm/Pass.h"
58#include "llvm/Support/Debug.h"
62#include <cassert>
63#include <iterator>
64#include <utility>
65
66using namespace llvm;
67
68#define DEBUG_TYPE "twoaddressinstruction"
69
70STATISTIC(NumTwoAddressInstrs, "Number of two-address instructions");
71STATISTIC(NumCommuted , "Number of instructions commuted to coalesce");
72STATISTIC(NumAggrCommuted , "Number of instructions aggressively commuted");
73STATISTIC(NumConvertedTo3Addr, "Number of instructions promoted to 3-address");
74STATISTIC(NumReSchedUps, "Number of instructions re-scheduled up");
75STATISTIC(NumReSchedDowns, "Number of instructions re-scheduled down");
76
77// Temporary flag to disable rescheduling.
78static cl::opt<bool>
79EnableRescheduling("twoaddr-reschedule",
80 cl::desc("Coalesce copies by rescheduling (default=true)"),
81 cl::init(true), cl::Hidden);
82
83// Limit the number of dataflow edges to traverse when evaluating the benefit
84// of commuting operands.
86 "dataflow-edge-limit", cl::Hidden, cl::init(3),
87 cl::desc("Maximum number of dataflow edges to traverse when evaluating "
88 "the benefit of commuting operands"));
89
90namespace {
91
92class TwoAddressInstructionImpl {
93 MachineFunction *MF = nullptr;
94 const TargetInstrInfo *TII = nullptr;
95 const TargetRegisterInfo *TRI = nullptr;
96 const InstrItineraryData *InstrItins = nullptr;
97 MachineRegisterInfo *MRI = nullptr;
98 LiveVariables *LV = nullptr;
99 LiveIntervals *LIS = nullptr;
101
102 // The current basic block being processed.
103 MachineBasicBlock *MBB = nullptr;
104
105 // Keep track the distance of a MI from the start of the current basic block.
107
108 // Set of already processed instructions in the current block.
110
111 // A map from virtual registers to physical registers which are likely targets
112 // to be coalesced to due to copies from physical registers to virtual
113 // registers. e.g. v1024 = move r0.
115
116 // A map from virtual registers to physical registers which are likely targets
117 // to be coalesced to due to copies to physical registers from virtual
118 // registers. e.g. r1 = move v1024.
120
121 MachineInstr *getSingleDef(Register Reg, MachineBasicBlock *BB) const;
122
123 bool isRevCopyChain(Register FromReg, Register ToReg, int Maxlen);
124
125 bool noUseAfterLastDef(Register Reg, unsigned Dist, unsigned &LastDef);
126
127 bool isCopyToReg(MachineInstr &MI, Register &SrcReg, Register &DstReg,
128 bool &IsSrcPhys, bool &IsDstPhys) const;
129
130 bool isPlainlyKilled(const MachineInstr *MI, LiveRange &LR) const;
131 bool isPlainlyKilled(const MachineInstr *MI, Register Reg) const;
132 bool isPlainlyKilled(const MachineOperand &MO) const;
133
134 bool isKilled(MachineInstr &MI, Register Reg, bool allowFalsePositives) const;
135
136 MachineInstr *findOnlyInterestingUse(Register Reg, MachineBasicBlock *MBB,
137 bool &IsCopy, Register &DstReg,
138 bool &IsDstPhys) const;
139
140 bool regsAreCompatible(Register RegA, Register RegB) const;
141
142 void removeMapRegEntry(const MachineOperand &MO,
143 DenseMap<Register, Register> &RegMap) const;
144
145 void removeClobberedSrcRegMap(MachineInstr *MI);
146
147 bool regOverlapsSet(const SmallVectorImpl<Register> &Set, Register Reg) const;
148
149 bool isProfitableToCommute(Register RegA, Register RegB, Register RegC,
150 MachineInstr *MI, unsigned Dist);
151
152 bool commuteInstruction(MachineInstr *MI, unsigned DstIdx,
153 unsigned RegBIdx, unsigned RegCIdx, unsigned Dist);
154
155 bool isProfitableToConv3Addr(Register RegA, Register RegB);
156
157 bool convertInstTo3Addr(MachineBasicBlock::iterator &mi,
159 Register RegB, unsigned &Dist);
160
161 bool isDefTooClose(Register Reg, unsigned Dist, MachineInstr *MI);
162
163 bool rescheduleMIBelowKill(MachineBasicBlock::iterator &mi,
165 bool rescheduleKillAboveMI(MachineBasicBlock::iterator &mi,
167
168 bool tryInstructionTransform(MachineBasicBlock::iterator &mi,
170 unsigned SrcIdx, unsigned DstIdx,
171 unsigned &Dist, bool shouldOnlyCommute);
172
173 bool tryInstructionCommute(MachineInstr *MI,
174 unsigned DstOpIdx,
175 unsigned BaseOpIdx,
176 bool BaseOpKilled,
177 unsigned Dist);
178 void scanUses(Register DstReg);
179
180 void processCopy(MachineInstr *MI);
181
182 using TiedPairList = SmallVector<std::pair<unsigned, unsigned>, 4>;
183 using TiedOperandMap = SmallDenseMap<Register, TiedPairList>;
184
185 bool collectTiedOperands(MachineInstr *MI, TiedOperandMap&);
186 void processTiedPairs(MachineInstr *MI, TiedPairList&, unsigned &Dist);
187 void eliminateRegSequence(MachineBasicBlock::iterator&);
188 bool processStatepoint(MachineInstr *MI, TiedOperandMap &TiedOperands);
189
190public:
191 TwoAddressInstructionImpl(MachineFunction &MF, MachineFunctionPass *P);
192 TwoAddressInstructionImpl(MachineFunction &MF,
194 LiveIntervals *LIS);
195 void setOptLevel(CodeGenOptLevel Level) { OptLevel = Level; }
196 bool run();
197};
198
199class TwoAddressInstructionLegacyPass : public MachineFunctionPass {
200public:
201 static char ID; // Pass identification, replacement for typeid
202
203 TwoAddressInstructionLegacyPass() : MachineFunctionPass(ID) {
206 }
207
208 /// Pass entry point.
209 bool runOnMachineFunction(MachineFunction &MF) override {
210 TwoAddressInstructionImpl Impl(MF, this);
211 // Disable optimizations if requested. We cannot skip the whole pass as some
212 // fixups are necessary for correctness.
213 if (skipFunction(MF.getFunction()))
214 Impl.setOptLevel(CodeGenOptLevel::None);
215 return Impl.run();
216 }
217
218 void getAnalysisUsage(AnalysisUsage &AU) const override {
219 AU.setPreservesCFG();
220 AU.addUsedIfAvailable<LiveVariablesWrapperPass>();
221 AU.addPreserved<LiveVariablesWrapperPass>();
222 AU.addPreserved<SlotIndexesWrapperPass>();
223 AU.addPreserved<LiveIntervalsWrapperPass>();
227 }
228};
229
230} // end anonymous namespace
231
235 // Disable optimizations if requested. We cannot skip the whole pass as some
236 // fixups are necessary for correctness.
238
239 TwoAddressInstructionImpl Impl(MF, MFAM, LIS);
240 if (MF.getFunction().hasOptNone())
241 Impl.setOptLevel(CodeGenOptLevel::None);
242
243 MFPropsModifier _(*this, MF);
244 bool Changed = Impl.run();
245 if (!Changed)
246 return PreservedAnalyses::all();
248
249 // SlotIndexes are only maintained when LiveIntervals is available. Only
250 // preserve SlotIndexes if we had LiveIntervals available and updated them.
251 if (LIS)
252 PA.preserve<SlotIndexesAnalysis>();
253
254 PA.preserve<LiveVariablesAnalysis>();
255 PA.preserve<LiveIntervalsAnalysis>();
256 PA.preserve<MachineDominatorTreeAnalysis>();
257 PA.preserve<MachineLoopAnalysis>();
258 PA.preserveSet<CFGAnalyses>();
259 return PA;
260}
261
262char TwoAddressInstructionLegacyPass::ID = 0;
263
264char &llvm::TwoAddressInstructionPassID = TwoAddressInstructionLegacyPass::ID;
265
266INITIALIZE_PASS(TwoAddressInstructionLegacyPass, DEBUG_TYPE,
267 "Two-Address instruction pass", false, false)
268
269TwoAddressInstructionImpl::TwoAddressInstructionImpl(
271 LiveIntervals *LIS)
272 : MF(&Func), TII(Func.getSubtarget().getInstrInfo()),
273 TRI(Func.getSubtarget().getRegisterInfo()),
274 InstrItins(Func.getSubtarget().getInstrItineraryData()),
275 MRI(&Func.getRegInfo()),
276 LV(MFAM.getCachedResult<LiveVariablesAnalysis>(Func)), LIS(LIS),
277 OptLevel(Func.getTarget().getOptLevel()) {}
278
279TwoAddressInstructionImpl::TwoAddressInstructionImpl(MachineFunction &Func,
281 : MF(&Func), TII(Func.getSubtarget().getInstrInfo()),
282 TRI(Func.getSubtarget().getRegisterInfo()),
283 InstrItins(Func.getSubtarget().getInstrItineraryData()),
284 MRI(&Func.getRegInfo()), OptLevel(Func.getTarget().getOptLevel()) {
285 auto *LVWrapper = P->getAnalysisIfAvailable<LiveVariablesWrapperPass>();
286 LV = LVWrapper ? &LVWrapper->getLV() : nullptr;
287 auto *LISWrapper = P->getAnalysisIfAvailable<LiveIntervalsWrapperPass>();
288 LIS = LISWrapper ? &LISWrapper->getLIS() : nullptr;
289}
290
291/// Return the MachineInstr* if it is the single def of the Reg in current BB.
293TwoAddressInstructionImpl::getSingleDef(Register Reg,
294 MachineBasicBlock *BB) const {
295 MachineInstr *Ret = nullptr;
296 for (MachineInstr &DefMI : MRI->def_instructions(Reg)) {
297 if (DefMI.getParent() != BB || DefMI.isDebugValue())
298 continue;
299 if (!Ret)
300 Ret = &DefMI;
301 else if (Ret != &DefMI)
302 return nullptr;
303 }
304 return Ret;
305}
306
307/// Check if there is a reversed copy chain from FromReg to ToReg:
308/// %Tmp1 = copy %Tmp2;
309/// %FromReg = copy %Tmp1;
310/// %ToReg = add %FromReg ...
311/// %Tmp2 = copy %ToReg;
312/// MaxLen specifies the maximum length of the copy chain the func
313/// can walk through.
314bool TwoAddressInstructionImpl::isRevCopyChain(Register FromReg, Register ToReg,
315 int Maxlen) {
316 Register TmpReg = FromReg;
317 for (int i = 0; i < Maxlen; i++) {
318 MachineInstr *Def = getSingleDef(TmpReg, MBB);
319 if (!Def || !Def->isCopy())
320 return false;
321
322 TmpReg = Def->getOperand(1).getReg();
323
324 if (TmpReg == ToReg)
325 return true;
326 }
327 return false;
328}
329
330/// Return true if there are no intervening uses between the last instruction
331/// in the MBB that defines the specified register and the two-address
332/// instruction which is being processed. It also returns the last def location
333/// by reference.
334bool TwoAddressInstructionImpl::noUseAfterLastDef(Register Reg, unsigned Dist,
335 unsigned &LastDef) {
336 LastDef = 0;
337 unsigned LastUse = Dist;
338 for (MachineOperand &MO : MRI->reg_operands(Reg)) {
339 MachineInstr *MI = MO.getParent();
340 if (MI->getParent() != MBB || MI->isDebugValue())
341 continue;
342 DenseMap<MachineInstr*, unsigned>::iterator DI = DistanceMap.find(MI);
343 if (DI == DistanceMap.end())
344 continue;
345 if (MO.isUse() && DI->second < LastUse)
346 LastUse = DI->second;
347 if (MO.isDef() && DI->second > LastDef)
348 LastDef = DI->second;
349 }
350
351 return !(LastUse > LastDef && LastUse < Dist);
352}
353
354/// Return true if the specified MI is a copy instruction or an extract_subreg
355/// instruction. It also returns the source and destination registers and
356/// whether they are physical registers by reference.
357bool TwoAddressInstructionImpl::isCopyToReg(MachineInstr &MI, Register &SrcReg,
358 Register &DstReg, bool &IsSrcPhys,
359 bool &IsDstPhys) const {
360 SrcReg = 0;
361 DstReg = 0;
362 if (MI.isCopy()) {
363 DstReg = MI.getOperand(0).getReg();
364 SrcReg = MI.getOperand(1).getReg();
365 } else if (MI.isInsertSubreg() || MI.isSubregToReg()) {
366 DstReg = MI.getOperand(0).getReg();
367 SrcReg = MI.getOperand(2).getReg();
368 } else {
369 return false;
370 }
371
372 IsSrcPhys = SrcReg.isPhysical();
373 IsDstPhys = DstReg.isPhysical();
374 return true;
375}
376
377bool TwoAddressInstructionImpl::isPlainlyKilled(const MachineInstr *MI,
378 LiveRange &LR) const {
379 // This is to match the kill flag version where undefs don't have kill flags.
380 if (!LR.hasAtLeastOneValue())
381 return false;
382
383 SlotIndex useIdx = LIS->getInstructionIndex(*MI);
384 LiveInterval::const_iterator I = LR.find(useIdx);
385 assert(I != LR.end() && "Reg must be live-in to use.");
386 return !I->end.isBlock() && SlotIndex::isSameInstr(I->end, useIdx);
387}
388
389/// Test if the given register value, which is used by the
390/// given instruction, is killed by the given instruction.
391bool TwoAddressInstructionImpl::isPlainlyKilled(const MachineInstr *MI,
392 Register Reg) const {
393 // FIXME: Sometimes tryInstructionTransform() will add instructions and
394 // test whether they can be folded before keeping them. In this case it
395 // sets a kill before recursively calling tryInstructionTransform() again.
396 // If there is no interval available, we assume that this instruction is
397 // one of those. A kill flag is manually inserted on the operand so the
398 // check below will handle it.
399 if (LIS && !LIS->isNotInMIMap(*MI)) {
400 if (Reg.isVirtual())
401 return isPlainlyKilled(MI, LIS->getInterval(Reg));
402 // Reserved registers are considered always live.
403 if (MRI->isReserved(Reg))
404 return false;
405 return all_of(TRI->regunits(Reg), [&](MCRegUnit U) {
406 return isPlainlyKilled(MI, LIS->getRegUnit(U));
407 });
408 }
409
410 return MI->killsRegister(Reg, /*TRI=*/nullptr);
411}
412
413/// Test if the register used by the given operand is killed by the operand's
414/// instruction.
415bool TwoAddressInstructionImpl::isPlainlyKilled(
416 const MachineOperand &MO) const {
417 return MO.isKill() || isPlainlyKilled(MO.getParent(), MO.getReg());
418}
419
420/// Test if the given register value, which is used by the given
421/// instruction, is killed by the given instruction. This looks through
422/// coalescable copies to see if the original value is potentially not killed.
423///
424/// For example, in this code:
425///
426/// %reg1034 = copy %reg1024
427/// %reg1035 = copy killed %reg1025
428/// %reg1036 = add killed %reg1034, killed %reg1035
429///
430/// %reg1034 is not considered to be killed, since it is copied from a
431/// register which is not killed. Treating it as not killed lets the
432/// normal heuristics commute the (two-address) add, which lets
433/// coalescing eliminate the extra copy.
434///
435/// If allowFalsePositives is true then likely kills are treated as kills even
436/// if it can't be proven that they are kills.
437bool TwoAddressInstructionImpl::isKilled(MachineInstr &MI, Register Reg,
438 bool allowFalsePositives) const {
439 MachineInstr *DefMI = &MI;
440 while (true) {
441 // All uses of physical registers are likely to be kills.
442 if (Reg.isPhysical() && (allowFalsePositives || MRI->hasOneUse(Reg)))
443 return true;
444 if (!isPlainlyKilled(DefMI, Reg))
445 return false;
446 if (Reg.isPhysical())
447 return true;
448 MachineRegisterInfo::def_iterator Begin = MRI->def_begin(Reg);
449 // If there are multiple defs, we can't do a simple analysis, so just
450 // go with what the kill flag says.
451 if (std::next(Begin) != MRI->def_end())
452 return true;
453 DefMI = Begin->getParent();
454 bool IsSrcPhys, IsDstPhys;
455 Register SrcReg, DstReg;
456 // If the def is something other than a copy, then it isn't going to
457 // be coalesced, so follow the kill flag.
458 if (!isCopyToReg(*DefMI, SrcReg, DstReg, IsSrcPhys, IsDstPhys))
459 return true;
460 Reg = SrcReg;
461 }
462}
463
464/// Return true if the specified MI uses the specified register as a two-address
465/// use. If so, return the destination register by reference.
467 for (unsigned i = 0, NumOps = MI.getNumOperands(); i != NumOps; ++i) {
468 const MachineOperand &MO = MI.getOperand(i);
469 if (!MO.isReg() || !MO.isUse() || MO.getReg() != Reg)
470 continue;
471 unsigned ti;
472 if (MI.isRegTiedToDefOperand(i, &ti)) {
473 DstReg = MI.getOperand(ti).getReg();
474 return true;
475 }
476 }
477 return false;
478}
479
480/// Given a register, if all its uses are in the same basic block, return the
481/// last use instruction if it's a copy or a two-address use.
482MachineInstr *TwoAddressInstructionImpl::findOnlyInterestingUse(
483 Register Reg, MachineBasicBlock *MBB, bool &IsCopy, Register &DstReg,
484 bool &IsDstPhys) const {
485 MachineOperand *UseOp = nullptr;
486 for (MachineOperand &MO : MRI->use_nodbg_operands(Reg)) {
487 if (MO.isUndef())
488 continue;
489
490 MachineInstr *MI = MO.getParent();
491 if (MI->getParent() != MBB)
492 return nullptr;
493 if (isPlainlyKilled(MI, Reg))
494 UseOp = &MO;
495 }
496 if (!UseOp)
497 return nullptr;
498 MachineInstr &UseMI = *UseOp->getParent();
499
500 Register SrcReg;
501 bool IsSrcPhys;
502 if (isCopyToReg(UseMI, SrcReg, DstReg, IsSrcPhys, IsDstPhys)) {
503 IsCopy = true;
504 return &UseMI;
505 }
506 IsDstPhys = false;
507 if (isTwoAddrUse(UseMI, Reg, DstReg)) {
508 IsDstPhys = DstReg.isPhysical();
509 return &UseMI;
510 }
511 if (UseMI.isCommutable()) {
513 unsigned Src2 = UseOp->getOperandNo();
514 if (TII->findCommutedOpIndices(UseMI, Src1, Src2)) {
515 MachineOperand &MO = UseMI.getOperand(Src1);
516 if (MO.isReg() && MO.isUse() &&
517 isTwoAddrUse(UseMI, MO.getReg(), DstReg)) {
518 IsDstPhys = DstReg.isPhysical();
519 return &UseMI;
520 }
521 }
522 }
523 return nullptr;
524}
525
526/// Return the physical register the specified virtual register might be mapped
527/// to.
530 while (Reg.isVirtual()) {
532 if (SI == RegMap.end())
533 return 0;
534 Reg = SI->second;
535 }
536 if (Reg.isPhysical())
537 return Reg;
538 return 0;
539}
540
541/// Return true if the two registers are equal or aliased.
542bool TwoAddressInstructionImpl::regsAreCompatible(Register RegA,
543 Register RegB) const {
544 if (RegA == RegB)
545 return true;
546 if (!RegA || !RegB)
547 return false;
548 return TRI->regsOverlap(RegA, RegB);
549}
550
551/// From RegMap remove entries mapped to a physical register which overlaps MO.
552void TwoAddressInstructionImpl::removeMapRegEntry(
553 const MachineOperand &MO, DenseMap<Register, Register> &RegMap) const {
554 assert(
555 (MO.isReg() || MO.isRegMask()) &&
556 "removeMapRegEntry must be called with a register or regmask operand.");
557
559 for (auto SI : RegMap) {
560 Register ToReg = SI.second;
561 if (ToReg.isVirtual())
562 continue;
563
564 if (MO.isReg()) {
565 Register Reg = MO.getReg();
566 if (TRI->regsOverlap(ToReg, Reg))
567 Srcs.push_back(SI.first);
568 } else if (MO.clobbersPhysReg(ToReg))
569 Srcs.push_back(SI.first);
570 }
571
572 for (auto SrcReg : Srcs)
573 RegMap.erase(SrcReg);
574}
575
576/// If a physical register is clobbered, old entries mapped to it should be
577/// deleted. For example
578///
579/// %2:gr64 = COPY killed $rdx
580/// MUL64r %3:gr64, implicit-def $rax, implicit-def $rdx
581///
582/// After the MUL instruction, $rdx contains different value than in the COPY
583/// instruction. So %2 should not map to $rdx after MUL.
584void TwoAddressInstructionImpl::removeClobberedSrcRegMap(MachineInstr *MI) {
585 if (MI->isCopy()) {
586 // If a virtual register is copied to its mapped physical register, it
587 // doesn't change the potential coalescing between them, so we don't remove
588 // entries mapped to the physical register. For example
589 //
590 // %100 = COPY $r8
591 // ...
592 // $r8 = COPY %100
593 //
594 // The first copy constructs SrcRegMap[%100] = $r8, the second copy doesn't
595 // destroy the content of $r8, and should not impact SrcRegMap.
596 Register Dst = MI->getOperand(0).getReg();
597 if (!Dst || Dst.isVirtual())
598 return;
599
600 Register Src = MI->getOperand(1).getReg();
601 if (regsAreCompatible(Dst, getMappedReg(Src, SrcRegMap)))
602 return;
603 }
604
605 for (const MachineOperand &MO : MI->operands()) {
606 if (MO.isRegMask()) {
607 removeMapRegEntry(MO, SrcRegMap);
608 continue;
609 }
610 if (!MO.isReg() || !MO.isDef())
611 continue;
612 Register Reg = MO.getReg();
613 if (!Reg || Reg.isVirtual())
614 continue;
615 removeMapRegEntry(MO, SrcRegMap);
616 }
617}
618
619// Returns true if Reg is equal or aliased to at least one register in Set.
620bool TwoAddressInstructionImpl::regOverlapsSet(
621 const SmallVectorImpl<Register> &Set, Register Reg) const {
622 for (Register R : Set)
623 if (TRI->regsOverlap(R, Reg))
624 return true;
625
626 return false;
627}
628
629/// Return true if it's potentially profitable to commute the two-address
630/// instruction that's being processed.
631bool TwoAddressInstructionImpl::isProfitableToCommute(Register RegA,
632 Register RegB,
633 Register RegC,
634 MachineInstr *MI,
635 unsigned Dist) {
636 if (OptLevel == CodeGenOptLevel::None)
637 return false;
638
639 // Determine if it's profitable to commute this two address instruction. In
640 // general, we want no uses between this instruction and the definition of
641 // the two-address register.
642 // e.g.
643 // %reg1028 = EXTRACT_SUBREG killed %reg1027, 1
644 // %reg1029 = COPY %reg1028
645 // %reg1029 = SHR8ri %reg1029, 7, implicit dead %eflags
646 // insert => %reg1030 = COPY %reg1028
647 // %reg1030 = ADD8rr killed %reg1028, killed %reg1029, implicit dead %eflags
648 // In this case, it might not be possible to coalesce the second COPY
649 // instruction if the first one is coalesced. So it would be profitable to
650 // commute it:
651 // %reg1028 = EXTRACT_SUBREG killed %reg1027, 1
652 // %reg1029 = COPY %reg1028
653 // %reg1029 = SHR8ri %reg1029, 7, implicit dead %eflags
654 // insert => %reg1030 = COPY %reg1029
655 // %reg1030 = ADD8rr killed %reg1029, killed %reg1028, implicit dead %eflags
656
657 if (!isPlainlyKilled(MI, RegC))
658 return false;
659
660 // Ok, we have something like:
661 // %reg1030 = ADD8rr killed %reg1028, killed %reg1029, implicit dead %eflags
662 // let's see if it's worth commuting it.
663
664 // Look for situations like this:
665 // %reg1024 = MOV r1
666 // %reg1025 = MOV r0
667 // %reg1026 = ADD %reg1024, %reg1025
668 // r0 = MOV %reg1026
669 // Commute the ADD to hopefully eliminate an otherwise unavoidable copy.
670 MCRegister ToRegA = getMappedReg(RegA, DstRegMap);
671 if (ToRegA) {
672 MCRegister FromRegB = getMappedReg(RegB, SrcRegMap);
673 MCRegister FromRegC = getMappedReg(RegC, SrcRegMap);
674 bool CompB = FromRegB && regsAreCompatible(FromRegB, ToRegA);
675 bool CompC = FromRegC && regsAreCompatible(FromRegC, ToRegA);
676
677 // Compute if any of the following are true:
678 // -RegB is not tied to a register and RegC is compatible with RegA.
679 // -RegB is tied to the wrong physical register, but RegC is.
680 // -RegB is tied to the wrong physical register, and RegC isn't tied.
681 if ((!FromRegB && CompC) || (FromRegB && !CompB && (!FromRegC || CompC)))
682 return true;
683 // Don't compute if any of the following are true:
684 // -RegC is not tied to a register and RegB is compatible with RegA.
685 // -RegC is tied to the wrong physical register, but RegB is.
686 // -RegC is tied to the wrong physical register, and RegB isn't tied.
687 if ((!FromRegC && CompB) || (FromRegC && !CompC && (!FromRegB || CompB)))
688 return false;
689 }
690
691 // If there is a use of RegC between its last def (could be livein) and this
692 // instruction, then bail.
693 unsigned LastDefC = 0;
694 if (!noUseAfterLastDef(RegC, Dist, LastDefC))
695 return false;
696
697 // If there is a use of RegB between its last def (could be livein) and this
698 // instruction, then go ahead and make this transformation.
699 unsigned LastDefB = 0;
700 if (!noUseAfterLastDef(RegB, Dist, LastDefB))
701 return true;
702
703 // Look for situation like this:
704 // %reg101 = MOV %reg100
705 // %reg102 = ...
706 // %reg103 = ADD %reg102, %reg101
707 // ... = %reg103 ...
708 // %reg100 = MOV %reg103
709 // If there is a reversed copy chain from reg101 to reg103, commute the ADD
710 // to eliminate an otherwise unavoidable copy.
711 // FIXME:
712 // We can extend the logic further: If an pair of operands in an insn has
713 // been merged, the insn could be regarded as a virtual copy, and the virtual
714 // copy could also be used to construct a copy chain.
715 // To more generally minimize register copies, ideally the logic of two addr
716 // instruction pass should be integrated with register allocation pass where
717 // interference graph is available.
718 if (isRevCopyChain(RegC, RegA, MaxDataFlowEdge))
719 return true;
720
721 if (isRevCopyChain(RegB, RegA, MaxDataFlowEdge))
722 return false;
723
724 // Look for other target specific commute preference.
725 bool Commute;
726 if (TII->hasCommutePreference(*MI, Commute))
727 return Commute;
728
729 // Since there are no intervening uses for both registers, then commute
730 // if the def of RegC is closer. Its live interval is shorter.
731 return LastDefB && LastDefC && LastDefC > LastDefB;
732}
733
734/// Commute a two-address instruction and update the basic block, distance map,
735/// and live variables if needed. Return true if it is successful.
736bool TwoAddressInstructionImpl::commuteInstruction(MachineInstr *MI,
737 unsigned DstIdx,
738 unsigned RegBIdx,
739 unsigned RegCIdx,
740 unsigned Dist) {
741 Register RegC = MI->getOperand(RegCIdx).getReg();
742 LLVM_DEBUG(dbgs() << "2addr: COMMUTING : " << *MI);
743 MachineInstr *NewMI = TII->commuteInstruction(*MI, false, RegBIdx, RegCIdx);
744
745 if (NewMI == nullptr) {
746 LLVM_DEBUG(dbgs() << "2addr: COMMUTING FAILED!\n");
747 return false;
748 }
749
750 LLVM_DEBUG(dbgs() << "2addr: COMMUTED TO: " << *NewMI);
751 assert(NewMI == MI &&
752 "TargetInstrInfo::commuteInstruction() should not return a new "
753 "instruction unless it was requested.");
754
755 // Update source register map.
756 MCRegister FromRegC = getMappedReg(RegC, SrcRegMap);
757 if (FromRegC) {
758 Register RegA = MI->getOperand(DstIdx).getReg();
759 SrcRegMap[RegA] = FromRegC;
760 }
761
762 return true;
763}
764
765/// Return true if it is profitable to convert the given 2-address instruction
766/// to a 3-address one.
767bool TwoAddressInstructionImpl::isProfitableToConv3Addr(Register RegA,
768 Register RegB) {
769 // Look for situations like this:
770 // %reg1024 = MOV r1
771 // %reg1025 = MOV r0
772 // %reg1026 = ADD %reg1024, %reg1025
773 // r2 = MOV %reg1026
774 // Turn ADD into a 3-address instruction to avoid a copy.
775 MCRegister FromRegB = getMappedReg(RegB, SrcRegMap);
776 if (!FromRegB)
777 return false;
778 MCRegister ToRegA = getMappedReg(RegA, DstRegMap);
779 return (ToRegA && !regsAreCompatible(FromRegB, ToRegA));
780}
781
782/// Convert the specified two-address instruction into a three address one.
783/// Return true if this transformation was successful.
784bool TwoAddressInstructionImpl::convertInstTo3Addr(
786 Register RegA, Register RegB, unsigned &Dist) {
787 MachineInstrSpan MIS(mi, MBB);
788 MachineInstr *NewMI = TII->convertToThreeAddress(*mi, LV, LIS);
789 if (!NewMI)
790 return false;
791
792 for (MachineInstr &MI : MIS)
793 DistanceMap.insert(std::make_pair(&MI, Dist++));
794
795 if (&*mi == NewMI) {
796 LLVM_DEBUG(dbgs() << "2addr: CONVERTED IN-PLACE TO 3-ADDR: " << *mi);
797 } else {
798 LLVM_DEBUG({
799 dbgs() << "2addr: CONVERTING 2-ADDR: " << *mi;
800 dbgs() << "2addr: TO 3-ADDR: " << *NewMI;
801 });
802
803 // If the old instruction is debug value tracked, an update is required.
804 if (auto OldInstrNum = mi->peekDebugInstrNum()) {
805 assert(mi->getNumExplicitDefs() == 1);
806 assert(NewMI->getNumExplicitDefs() == 1);
807
808 // Find the old and new def location.
809 unsigned OldIdx = mi->defs().begin()->getOperandNo();
810 unsigned NewIdx = NewMI->defs().begin()->getOperandNo();
811
812 // Record that one def has been replaced by the other.
813 unsigned NewInstrNum = NewMI->getDebugInstrNum();
814 MF->makeDebugValueSubstitution(std::make_pair(OldInstrNum, OldIdx),
815 std::make_pair(NewInstrNum, NewIdx));
816 }
817
818 MBB->erase(mi); // Nuke the old inst.
819 Dist--;
820 }
821
822 mi = NewMI;
823 nmi = std::next(mi);
824
825 // Update source and destination register maps.
826 SrcRegMap.erase(RegA);
827 DstRegMap.erase(RegB);
828 return true;
829}
830
831/// Scan forward recursively for only uses, update maps if the use is a copy or
832/// a two-address instruction.
833void TwoAddressInstructionImpl::scanUses(Register DstReg) {
834 SmallVector<Register, 4> VirtRegPairs;
835 bool IsDstPhys;
836 bool IsCopy = false;
837 Register NewReg;
838 Register Reg = DstReg;
839 while (MachineInstr *UseMI =
840 findOnlyInterestingUse(Reg, MBB, IsCopy, NewReg, IsDstPhys)) {
841 if (IsCopy && !Processed.insert(UseMI).second)
842 break;
843
844 DenseMap<MachineInstr*, unsigned>::iterator DI = DistanceMap.find(UseMI);
845 if (DI != DistanceMap.end())
846 // Earlier in the same MBB.Reached via a back edge.
847 break;
848
849 if (IsDstPhys) {
850 VirtRegPairs.push_back(NewReg);
851 break;
852 }
853 SrcRegMap[NewReg] = Reg;
854 VirtRegPairs.push_back(NewReg);
855 Reg = NewReg;
856 }
857
858 if (!VirtRegPairs.empty()) {
859 Register ToReg = VirtRegPairs.pop_back_val();
860 while (!VirtRegPairs.empty()) {
861 Register FromReg = VirtRegPairs.pop_back_val();
862 bool isNew = DstRegMap.insert(std::make_pair(FromReg, ToReg)).second;
863 if (!isNew)
864 assert(DstRegMap[FromReg] == ToReg &&"Can't map to two dst registers!");
865 ToReg = FromReg;
866 }
867 bool isNew = DstRegMap.insert(std::make_pair(DstReg, ToReg)).second;
868 if (!isNew)
869 assert(DstRegMap[DstReg] == ToReg && "Can't map to two dst registers!");
870 }
871}
872
873/// If the specified instruction is not yet processed, process it if it's a
874/// copy. For a copy instruction, we find the physical registers the
875/// source and destination registers might be mapped to. These are kept in
876/// point-to maps used to determine future optimizations. e.g.
877/// v1024 = mov r0
878/// v1025 = mov r1
879/// v1026 = add v1024, v1025
880/// r1 = mov r1026
881/// If 'add' is a two-address instruction, v1024, v1026 are both potentially
882/// coalesced to r0 (from the input side). v1025 is mapped to r1. v1026 is
883/// potentially joined with r1 on the output side. It's worthwhile to commute
884/// 'add' to eliminate a copy.
885void TwoAddressInstructionImpl::processCopy(MachineInstr *MI) {
886 if (Processed.count(MI))
887 return;
888
889 bool IsSrcPhys, IsDstPhys;
890 Register SrcReg, DstReg;
891 if (!isCopyToReg(*MI, SrcReg, DstReg, IsSrcPhys, IsDstPhys))
892 return;
893
894 if (IsDstPhys && !IsSrcPhys) {
895 DstRegMap.insert(std::make_pair(SrcReg, DstReg));
896 } else if (!IsDstPhys && IsSrcPhys) {
897 bool isNew = SrcRegMap.insert(std::make_pair(DstReg, SrcReg)).second;
898 if (!isNew)
899 assert(SrcRegMap[DstReg] == SrcReg &&
900 "Can't map to two src physical registers!");
901
902 scanUses(DstReg);
903 }
904
905 Processed.insert(MI);
906}
907
908/// If there is one more local instruction that reads 'Reg' and it kills 'Reg,
909/// consider moving the instruction below the kill instruction in order to
910/// eliminate the need for the copy.
911bool TwoAddressInstructionImpl::rescheduleMIBelowKill(
913 Register Reg) {
914 // Bail immediately if we don't have LV or LIS available. We use them to find
915 // kills efficiently.
916 if (!LV && !LIS)
917 return false;
918
919 MachineInstr *MI = &*mi;
920 DenseMap<MachineInstr*, unsigned>::iterator DI = DistanceMap.find(MI);
921 if (DI == DistanceMap.end())
922 // Must be created from unfolded load. Don't waste time trying this.
923 return false;
924
925 MachineInstr *KillMI = nullptr;
926 if (LIS) {
927 LiveInterval &LI = LIS->getInterval(Reg);
928 assert(LI.end() != LI.begin() &&
929 "Reg should not have empty live interval.");
930
931 SlotIndex MBBEndIdx = LIS->getMBBEndIdx(MBB).getPrevSlot();
932 LiveInterval::const_iterator I = LI.find(MBBEndIdx);
933 if (I != LI.end() && I->start < MBBEndIdx)
934 return false;
935
936 --I;
937 KillMI = LIS->getInstructionFromIndex(I->end);
938 } else {
939 KillMI = LV->getVarInfo(Reg).findKill(MBB);
940 }
941 if (!KillMI || MI == KillMI || KillMI->isCopy() || KillMI->isCopyLike())
942 // Don't mess with copies, they may be coalesced later.
943 return false;
944
945 if (KillMI->hasUnmodeledSideEffects() || KillMI->isCall() ||
946 KillMI->isBranch() || KillMI->isTerminator())
947 // Don't move pass calls, etc.
948 return false;
949
950 Register DstReg;
951 if (isTwoAddrUse(*KillMI, Reg, DstReg))
952 return false;
953
954 bool SeenStore = true;
955 if (!MI->isSafeToMove(SeenStore))
956 return false;
957
958 if (TII->getInstrLatency(InstrItins, *MI) > 1)
959 // FIXME: Needs more sophisticated heuristics.
960 return false;
961
965 for (const MachineOperand &MO : MI->operands()) {
966 if (!MO.isReg())
967 continue;
968 Register MOReg = MO.getReg();
969 if (!MOReg)
970 continue;
971 if (MO.isDef())
972 Defs.push_back(MOReg);
973 else {
974 Uses.push_back(MOReg);
975 if (MOReg != Reg && isPlainlyKilled(MO))
976 Kills.push_back(MOReg);
977 }
978 }
979
980 // Move the copies connected to MI down as well.
982 MachineBasicBlock::iterator AfterMI = std::next(Begin);
983 MachineBasicBlock::iterator End = AfterMI;
984 while (End != MBB->end()) {
985 End = skipDebugInstructionsForward(End, MBB->end());
986 if (End->isCopy() && regOverlapsSet(Defs, End->getOperand(1).getReg()))
987 Defs.push_back(End->getOperand(0).getReg());
988 else
989 break;
990 ++End;
991 }
992
993 // Check if the reschedule will not break dependencies.
994 unsigned NumVisited = 0;
995 MachineBasicBlock::iterator KillPos = KillMI;
996 ++KillPos;
997 for (MachineInstr &OtherMI : make_range(End, KillPos)) {
998 // Debug or pseudo instructions cannot be counted against the limit.
999 if (OtherMI.isDebugOrPseudoInstr())
1000 continue;
1001 if (NumVisited > 10) // FIXME: Arbitrary limit to reduce compile time cost.
1002 return false;
1003 ++NumVisited;
1004 if (OtherMI.hasUnmodeledSideEffects() || OtherMI.isCall() ||
1005 OtherMI.isBranch() || OtherMI.isTerminator())
1006 // Don't move pass calls, etc.
1007 return false;
1008 for (const MachineOperand &MO : OtherMI.operands()) {
1009 if (!MO.isReg())
1010 continue;
1011 Register MOReg = MO.getReg();
1012 if (!MOReg)
1013 continue;
1014 if (MO.isDef()) {
1015 if (regOverlapsSet(Uses, MOReg))
1016 // Physical register use would be clobbered.
1017 return false;
1018 if (!MO.isDead() && regOverlapsSet(Defs, MOReg))
1019 // May clobber a physical register def.
1020 // FIXME: This may be too conservative. It's ok if the instruction
1021 // is sunken completely below the use.
1022 return false;
1023 } else {
1024 if (regOverlapsSet(Defs, MOReg))
1025 return false;
1026 bool isKill = isPlainlyKilled(MO);
1027 if (MOReg != Reg && ((isKill && regOverlapsSet(Uses, MOReg)) ||
1028 regOverlapsSet(Kills, MOReg)))
1029 // Don't want to extend other live ranges and update kills.
1030 return false;
1031 if (MOReg == Reg && !isKill)
1032 // We can't schedule across a use of the register in question.
1033 return false;
1034 // Ensure that if this is register in question, its the kill we expect.
1035 assert((MOReg != Reg || &OtherMI == KillMI) &&
1036 "Found multiple kills of a register in a basic block");
1037 }
1038 }
1039 }
1040
1041 // Move debug info as well.
1042 while (Begin != MBB->begin() && std::prev(Begin)->isDebugInstr())
1043 --Begin;
1044
1045 nmi = End;
1046 MachineBasicBlock::iterator InsertPos = KillPos;
1047 if (LIS) {
1048 // We have to move the copies (and any interleaved debug instructions)
1049 // first so that the MBB is still well-formed when calling handleMove().
1050 for (MachineBasicBlock::iterator MBBI = AfterMI; MBBI != End;) {
1051 auto CopyMI = MBBI++;
1052 MBB->splice(InsertPos, MBB, CopyMI);
1053 if (!CopyMI->isDebugOrPseudoInstr())
1054 LIS->handleMove(*CopyMI);
1055 InsertPos = CopyMI;
1056 }
1057 End = std::next(MachineBasicBlock::iterator(MI));
1058 }
1059
1060 // Copies following MI may have been moved as well.
1061 MBB->splice(InsertPos, MBB, Begin, End);
1062 DistanceMap.erase(DI);
1063
1064 // Update live variables
1065 if (LIS) {
1066 LIS->handleMove(*MI);
1067 } else {
1068 LV->removeVirtualRegisterKilled(Reg, *KillMI);
1070 }
1071
1072 LLVM_DEBUG(dbgs() << "\trescheduled below kill: " << *KillMI);
1073 return true;
1074}
1075
1076/// Return true if the re-scheduling will put the given instruction too close
1077/// to the defs of its register dependencies.
1078bool TwoAddressInstructionImpl::isDefTooClose(Register Reg, unsigned Dist,
1079 MachineInstr *MI) {
1080 for (MachineInstr &DefMI : MRI->def_instructions(Reg)) {
1081 if (DefMI.getParent() != MBB || DefMI.isCopy() || DefMI.isCopyLike())
1082 continue;
1083 if (&DefMI == MI)
1084 return true; // MI is defining something KillMI uses
1085 DenseMap<MachineInstr*, unsigned>::iterator DDI = DistanceMap.find(&DefMI);
1086 if (DDI == DistanceMap.end())
1087 return true; // Below MI
1088 unsigned DefDist = DDI->second;
1089 assert(Dist > DefDist && "Visited def already?");
1090 if (TII->getInstrLatency(InstrItins, DefMI) > (Dist - DefDist))
1091 return true;
1092 }
1093 return false;
1094}
1095
1096/// If there is one more local instruction that reads 'Reg' and it kills 'Reg,
1097/// consider moving the kill instruction above the current two-address
1098/// instruction in order to eliminate the need for the copy.
1099bool TwoAddressInstructionImpl::rescheduleKillAboveMI(
1101 Register Reg) {
1102 // Bail immediately if we don't have LV or LIS available. We use them to find
1103 // kills efficiently.
1104 if (!LV && !LIS)
1105 return false;
1106
1107 MachineInstr *MI = &*mi;
1108 DenseMap<MachineInstr*, unsigned>::iterator DI = DistanceMap.find(MI);
1109 if (DI == DistanceMap.end())
1110 // Must be created from unfolded load. Don't waste time trying this.
1111 return false;
1112
1113 MachineInstr *KillMI = nullptr;
1114 if (LIS) {
1115 LiveInterval &LI = LIS->getInterval(Reg);
1116 assert(LI.end() != LI.begin() &&
1117 "Reg should not have empty live interval.");
1118
1119 SlotIndex MBBEndIdx = LIS->getMBBEndIdx(MBB).getPrevSlot();
1120 LiveInterval::const_iterator I = LI.find(MBBEndIdx);
1121 if (I != LI.end() && I->start < MBBEndIdx)
1122 return false;
1123
1124 --I;
1125 KillMI = LIS->getInstructionFromIndex(I->end);
1126 } else {
1127 KillMI = LV->getVarInfo(Reg).findKill(MBB);
1128 }
1129 if (!KillMI || MI == KillMI || KillMI->isCopy() || KillMI->isCopyLike())
1130 // Don't mess with copies, they may be coalesced later.
1131 return false;
1132
1133 Register DstReg;
1134 if (isTwoAddrUse(*KillMI, Reg, DstReg))
1135 return false;
1136
1137 bool SeenStore = true;
1138 if (!KillMI->isSafeToMove(SeenStore))
1139 return false;
1140
1144 SmallVector<Register, 2> LiveDefs;
1145 for (const MachineOperand &MO : KillMI->operands()) {
1146 if (!MO.isReg())
1147 continue;
1148 Register MOReg = MO.getReg();
1149 if (MO.isUse()) {
1150 if (!MOReg)
1151 continue;
1152 if (isDefTooClose(MOReg, DI->second, MI))
1153 return false;
1154 bool isKill = isPlainlyKilled(MO);
1155 if (MOReg == Reg && !isKill)
1156 return false;
1157 Uses.push_back(MOReg);
1158 if (isKill && MOReg != Reg)
1159 Kills.push_back(MOReg);
1160 } else if (MOReg.isPhysical()) {
1161 Defs.push_back(MOReg);
1162 if (!MO.isDead())
1163 LiveDefs.push_back(MOReg);
1164 }
1165 }
1166
1167 // Check if the reschedule will not break dependencies.
1168 unsigned NumVisited = 0;
1169 for (MachineInstr &OtherMI :
1171 // Debug or pseudo instructions cannot be counted against the limit.
1172 if (OtherMI.isDebugOrPseudoInstr())
1173 continue;
1174 if (NumVisited > 10) // FIXME: Arbitrary limit to reduce compile time cost.
1175 return false;
1176 ++NumVisited;
1177 if (OtherMI.hasUnmodeledSideEffects() || OtherMI.isCall() ||
1178 OtherMI.isBranch() || OtherMI.isTerminator())
1179 // Don't move pass calls, etc.
1180 return false;
1181 SmallVector<Register, 2> OtherDefs;
1182 for (const MachineOperand &MO : OtherMI.operands()) {
1183 if (!MO.isReg())
1184 continue;
1185 Register MOReg = MO.getReg();
1186 if (!MOReg)
1187 continue;
1188 if (MO.isUse()) {
1189 if (regOverlapsSet(Defs, MOReg))
1190 // Moving KillMI can clobber the physical register if the def has
1191 // not been seen.
1192 return false;
1193 if (regOverlapsSet(Kills, MOReg))
1194 // Don't want to extend other live ranges and update kills.
1195 return false;
1196 if (&OtherMI != MI && MOReg == Reg && !isPlainlyKilled(MO))
1197 // We can't schedule across a use of the register in question.
1198 return false;
1199 } else {
1200 OtherDefs.push_back(MOReg);
1201 }
1202 }
1203
1204 for (Register MOReg : OtherDefs) {
1205 if (regOverlapsSet(Uses, MOReg))
1206 return false;
1207 if (MOReg.isPhysical() && regOverlapsSet(LiveDefs, MOReg))
1208 return false;
1209 // Physical register def is seen.
1210 llvm::erase(Defs, MOReg);
1211 }
1212 }
1213
1214 // Move the old kill above MI, don't forget to move debug info as well.
1215 MachineBasicBlock::iterator InsertPos = mi;
1216 while (InsertPos != MBB->begin() && std::prev(InsertPos)->isDebugInstr())
1217 --InsertPos;
1218 MachineBasicBlock::iterator From = KillMI;
1219 MachineBasicBlock::iterator To = std::next(From);
1220 while (std::prev(From)->isDebugInstr())
1221 --From;
1222 MBB->splice(InsertPos, MBB, From, To);
1223
1224 nmi = std::prev(InsertPos); // Backtrack so we process the moved instr.
1225 DistanceMap.erase(DI);
1226
1227 // Update live variables
1228 if (LIS) {
1229 LIS->handleMove(*KillMI);
1230 } else {
1231 LV->removeVirtualRegisterKilled(Reg, *KillMI);
1233 }
1234
1235 LLVM_DEBUG(dbgs() << "\trescheduled kill: " << *KillMI);
1236 return true;
1237}
1238
1239/// Tries to commute the operand 'BaseOpIdx' and some other operand in the
1240/// given machine instruction to improve opportunities for coalescing and
1241/// elimination of a register to register copy.
1242///
1243/// 'DstOpIdx' specifies the index of MI def operand.
1244/// 'BaseOpKilled' specifies if the register associated with 'BaseOpIdx'
1245/// operand is killed by the given instruction.
1246/// The 'Dist' arguments provides the distance of MI from the start of the
1247/// current basic block and it is used to determine if it is profitable
1248/// to commute operands in the instruction.
1249///
1250/// Returns true if the transformation happened. Otherwise, returns false.
1251bool TwoAddressInstructionImpl::tryInstructionCommute(MachineInstr *MI,
1252 unsigned DstOpIdx,
1253 unsigned BaseOpIdx,
1254 bool BaseOpKilled,
1255 unsigned Dist) {
1256 if (!MI->isCommutable())
1257 return false;
1258
1259 bool MadeChange = false;
1260 Register DstOpReg = MI->getOperand(DstOpIdx).getReg();
1261 Register BaseOpReg = MI->getOperand(BaseOpIdx).getReg();
1262 unsigned OpsNum = MI->getDesc().getNumOperands();
1263 unsigned OtherOpIdx = MI->getDesc().getNumDefs();
1264 for (; OtherOpIdx < OpsNum; OtherOpIdx++) {
1265 // The call of findCommutedOpIndices below only checks if BaseOpIdx
1266 // and OtherOpIdx are commutable, it does not really search for
1267 // other commutable operands and does not change the values of passed
1268 // variables.
1269 if (OtherOpIdx == BaseOpIdx || !MI->getOperand(OtherOpIdx).isReg() ||
1270 !TII->findCommutedOpIndices(*MI, BaseOpIdx, OtherOpIdx))
1271 continue;
1272
1273 Register OtherOpReg = MI->getOperand(OtherOpIdx).getReg();
1274 bool AggressiveCommute = false;
1275
1276 // If OtherOp dies but BaseOp does not, swap the OtherOp and BaseOp
1277 // operands. This makes the live ranges of DstOp and OtherOp joinable.
1278 bool OtherOpKilled = isKilled(*MI, OtherOpReg, false);
1279 bool DoCommute = !BaseOpKilled && OtherOpKilled;
1280
1281 if (!DoCommute &&
1282 isProfitableToCommute(DstOpReg, BaseOpReg, OtherOpReg, MI, Dist)) {
1283 DoCommute = true;
1284 AggressiveCommute = true;
1285 }
1286
1287 // If it's profitable to commute, try to do so.
1288 if (DoCommute && commuteInstruction(MI, DstOpIdx, BaseOpIdx, OtherOpIdx,
1289 Dist)) {
1290 MadeChange = true;
1291 ++NumCommuted;
1292 if (AggressiveCommute)
1293 ++NumAggrCommuted;
1294
1295 // There might be more than two commutable operands, update BaseOp and
1296 // continue scanning.
1297 // FIXME: This assumes that the new instruction's operands are in the
1298 // same positions and were simply swapped.
1299 BaseOpReg = OtherOpReg;
1300 BaseOpKilled = OtherOpKilled;
1301 // Resamples OpsNum in case the number of operands was reduced. This
1302 // happens with X86.
1303 OpsNum = MI->getDesc().getNumOperands();
1304 }
1305 }
1306 return MadeChange;
1307}
1308
1309/// For the case where an instruction has a single pair of tied register
1310/// operands, attempt some transformations that may either eliminate the tied
1311/// operands or improve the opportunities for coalescing away the register copy.
1312/// Returns true if no copy needs to be inserted to untie mi's operands
1313/// (either because they were untied, or because mi was rescheduled, and will
1314/// be visited again later). If the shouldOnlyCommute flag is true, only
1315/// instruction commutation is attempted.
1316bool TwoAddressInstructionImpl::tryInstructionTransform(
1318 unsigned SrcIdx, unsigned DstIdx, unsigned &Dist, bool shouldOnlyCommute) {
1319 if (OptLevel == CodeGenOptLevel::None)
1320 return false;
1321
1322 MachineInstr &MI = *mi;
1323 Register regA = MI.getOperand(DstIdx).getReg();
1324 Register regB = MI.getOperand(SrcIdx).getReg();
1325
1326 assert(regB.isVirtual() && "cannot make instruction into two-address form");
1327 bool regBKilled = isKilled(MI, regB, true);
1328
1329 if (regA.isVirtual())
1330 scanUses(regA);
1331
1332 bool Commuted = tryInstructionCommute(&MI, DstIdx, SrcIdx, regBKilled, Dist);
1333
1334 // Give targets a chance to convert bundled instructions.
1335 bool ConvertibleTo3Addr = MI.isConvertibleTo3Addr(MachineInstr::AnyInBundle);
1336
1337 // If the instruction is convertible to 3 Addr, instead
1338 // of returning try 3 Addr transformation aggressively and
1339 // use this variable to check later. Because it might be better.
1340 // For example, we can just use `leal (%rsi,%rdi), %eax` and `ret`
1341 // instead of the following code.
1342 // addl %esi, %edi
1343 // movl %edi, %eax
1344 // ret
1345 if (Commuted && !ConvertibleTo3Addr)
1346 return false;
1347
1348 if (shouldOnlyCommute)
1349 return false;
1350
1351 // If there is one more use of regB later in the same MBB, consider
1352 // re-schedule this MI below it.
1353 if (!Commuted && EnableRescheduling && rescheduleMIBelowKill(mi, nmi, regB)) {
1354 ++NumReSchedDowns;
1355 return true;
1356 }
1357
1358 // If we commuted, regB may have changed so we should re-sample it to avoid
1359 // confusing the three address conversion below.
1360 if (Commuted) {
1361 regB = MI.getOperand(SrcIdx).getReg();
1362 regBKilled = isKilled(MI, regB, true);
1363 }
1364
1365 if (ConvertibleTo3Addr) {
1366 // This instruction is potentially convertible to a true
1367 // three-address instruction. Check if it is profitable.
1368 if (!regBKilled || isProfitableToConv3Addr(regA, regB)) {
1369 // Try to convert it.
1370 if (convertInstTo3Addr(mi, nmi, regA, regB, Dist)) {
1371 ++NumConvertedTo3Addr;
1372 return true; // Done with this instruction.
1373 }
1374 }
1375 }
1376
1377 // Return if it is commuted but 3 addr conversion is failed.
1378 if (Commuted)
1379 return false;
1380
1381 // If there is one more use of regB later in the same MBB, consider
1382 // re-schedule it before this MI if it's legal.
1383 if (EnableRescheduling && rescheduleKillAboveMI(mi, nmi, regB)) {
1384 ++NumReSchedUps;
1385 return true;
1386 }
1387
1388 // If this is an instruction with a load folded into it, try unfolding
1389 // the load, e.g. avoid this:
1390 // movq %rdx, %rcx
1391 // addq (%rax), %rcx
1392 // in favor of this:
1393 // movq (%rax), %rcx
1394 // addq %rdx, %rcx
1395 // because it's preferable to schedule a load than a register copy.
1396 if (MI.mayLoad() && !regBKilled) {
1397 // Determine if a load can be unfolded.
1398 unsigned LoadRegIndex;
1399 unsigned NewOpc =
1400 TII->getOpcodeAfterMemoryUnfold(MI.getOpcode(),
1401 /*UnfoldLoad=*/true,
1402 /*UnfoldStore=*/false,
1403 &LoadRegIndex);
1404 if (NewOpc != 0) {
1405 const MCInstrDesc &UnfoldMCID = TII->get(NewOpc);
1406 if (UnfoldMCID.getNumDefs() == 1) {
1407 // Unfold the load.
1408 LLVM_DEBUG(dbgs() << "2addr: UNFOLDING: " << MI);
1409 const TargetRegisterClass *RC = TRI->getAllocatableClass(
1410 TII->getRegClass(UnfoldMCID, LoadRegIndex));
1411 Register Reg = MRI->createVirtualRegister(RC);
1412 SmallVector<MachineInstr *, 2> NewMIs;
1413 if (!TII->unfoldMemoryOperand(*MF, MI, Reg,
1414 /*UnfoldLoad=*/true,
1415 /*UnfoldStore=*/false, NewMIs)) {
1416 LLVM_DEBUG(dbgs() << "2addr: ABANDONING UNFOLD\n");
1417 return false;
1418 }
1419 assert(NewMIs.size() == 2 &&
1420 "Unfolded a load into multiple instructions!");
1421 // The load was previously folded, so this is the only use.
1422 NewMIs[1]->addRegisterKilled(Reg, TRI);
1423
1424 // Tentatively insert the instructions into the block so that they
1425 // look "normal" to the transformation logic.
1426 MBB->insert(mi, NewMIs[0]);
1427 MBB->insert(mi, NewMIs[1]);
1428 DistanceMap.insert(std::make_pair(NewMIs[0], Dist++));
1429 DistanceMap.insert(std::make_pair(NewMIs[1], Dist));
1430
1431 LLVM_DEBUG(dbgs() << "2addr: NEW LOAD: " << *NewMIs[0]
1432 << "2addr: NEW INST: " << *NewMIs[1]);
1433
1434 // Transform the instruction, now that it no longer has a load.
1435 unsigned NewDstIdx =
1436 NewMIs[1]->findRegisterDefOperandIdx(regA, /*TRI=*/nullptr);
1437 unsigned NewSrcIdx =
1438 NewMIs[1]->findRegisterUseOperandIdx(regB, /*TRI=*/nullptr);
1439 MachineBasicBlock::iterator NewMI = NewMIs[1];
1440 bool TransformResult =
1441 tryInstructionTransform(NewMI, mi, NewSrcIdx, NewDstIdx, Dist, true);
1442 (void)TransformResult;
1443 assert(!TransformResult &&
1444 "tryInstructionTransform() should return false.");
1445 if (NewMIs[1]->getOperand(NewSrcIdx).isKill()) {
1446 // Success, or at least we made an improvement. Keep the unfolded
1447 // instructions and discard the original.
1448 if (LV) {
1449 for (const MachineOperand &MO : MI.operands()) {
1450 if (MO.isReg() && MO.getReg().isVirtual()) {
1451 if (MO.isUse()) {
1452 if (MO.isKill()) {
1453 if (NewMIs[0]->killsRegister(MO.getReg(), /*TRI=*/nullptr))
1454 LV->replaceKillInstruction(MO.getReg(), MI, *NewMIs[0]);
1455 else {
1456 assert(NewMIs[1]->killsRegister(MO.getReg(),
1457 /*TRI=*/nullptr) &&
1458 "Kill missing after load unfold!");
1459 LV->replaceKillInstruction(MO.getReg(), MI, *NewMIs[1]);
1460 }
1461 }
1462 } else if (LV->removeVirtualRegisterDead(MO.getReg(), MI)) {
1463 if (NewMIs[1]->registerDefIsDead(MO.getReg(),
1464 /*TRI=*/nullptr))
1465 LV->addVirtualRegisterDead(MO.getReg(), *NewMIs[1]);
1466 else {
1467 assert(NewMIs[0]->registerDefIsDead(MO.getReg(),
1468 /*TRI=*/nullptr) &&
1469 "Dead flag missing after load unfold!");
1470 LV->addVirtualRegisterDead(MO.getReg(), *NewMIs[0]);
1471 }
1472 }
1473 }
1474 }
1475 LV->addVirtualRegisterKilled(Reg, *NewMIs[1]);
1476 }
1477
1478 SmallVector<Register, 4> OrigRegs;
1479 if (LIS) {
1480 for (const MachineOperand &MO : MI.operands()) {
1481 if (MO.isReg())
1482 OrigRegs.push_back(MO.getReg());
1483 }
1484
1486 }
1487
1488 MI.eraseFromParent();
1489 DistanceMap.erase(&MI);
1490
1491 // Update LiveIntervals.
1492 if (LIS) {
1493 MachineBasicBlock::iterator Begin(NewMIs[0]);
1494 MachineBasicBlock::iterator End(NewMIs[1]);
1495 LIS->repairIntervalsInRange(MBB, Begin, End, OrigRegs);
1496 }
1497
1498 mi = NewMIs[1];
1499 } else {
1500 // Transforming didn't eliminate the tie and didn't lead to an
1501 // improvement. Clean up the unfolded instructions and keep the
1502 // original.
1503 LLVM_DEBUG(dbgs() << "2addr: ABANDONING UNFOLD\n");
1504 NewMIs[0]->eraseFromParent();
1505 NewMIs[1]->eraseFromParent();
1506 DistanceMap.erase(NewMIs[0]);
1507 DistanceMap.erase(NewMIs[1]);
1508 Dist--;
1509 }
1510 }
1511 }
1512 }
1513
1514 return false;
1515}
1516
1517// Collect tied operands of MI that need to be handled.
1518// Rewrite trivial cases immediately.
1519// Return true if any tied operands where found, including the trivial ones.
1520bool TwoAddressInstructionImpl::collectTiedOperands(
1521 MachineInstr *MI, TiedOperandMap &TiedOperands) {
1522 bool AnyOps = false;
1523 unsigned NumOps = MI->getNumOperands();
1524
1525 for (unsigned SrcIdx = 0; SrcIdx < NumOps; ++SrcIdx) {
1526 unsigned DstIdx = 0;
1527 if (!MI->isRegTiedToDefOperand(SrcIdx, &DstIdx))
1528 continue;
1529 AnyOps = true;
1530 MachineOperand &SrcMO = MI->getOperand(SrcIdx);
1531 MachineOperand &DstMO = MI->getOperand(DstIdx);
1532 Register SrcReg = SrcMO.getReg();
1533 Register DstReg = DstMO.getReg();
1534 // Tied constraint already satisfied?
1535 if (SrcReg == DstReg)
1536 continue;
1537
1538 assert(SrcReg && SrcMO.isUse() && "two address instruction invalid");
1539
1540 // Deal with undef uses immediately - simply rewrite the src operand.
1541 if (SrcMO.isUndef() && !DstMO.getSubReg()) {
1542 // Constrain the DstReg register class if required.
1543 if (DstReg.isVirtual()) {
1544 const TargetRegisterClass *RC = MRI->getRegClass(SrcReg);
1545 MRI->constrainRegClass(DstReg, RC);
1546 }
1547 SrcMO.setReg(DstReg);
1548 SrcMO.setSubReg(0);
1549 LLVM_DEBUG(dbgs() << "\t\trewrite undef:\t" << *MI);
1550 continue;
1551 }
1552 TiedOperands[SrcReg].push_back(std::make_pair(SrcIdx, DstIdx));
1553 }
1554 return AnyOps;
1555}
1556
1557// Process a list of tied MI operands that all use the same source register.
1558// The tied pairs are of the form (SrcIdx, DstIdx).
1559void TwoAddressInstructionImpl::processTiedPairs(MachineInstr *MI,
1560 TiedPairList &TiedPairs,
1561 unsigned &Dist) {
1562 bool IsEarlyClobber = llvm::any_of(TiedPairs, [MI](auto const &TP) {
1563 return MI->getOperand(TP.second).isEarlyClobber();
1564 });
1565
1566 bool RemovedKillFlag = false;
1567 bool AllUsesCopied = true;
1568 Register LastCopiedReg;
1569 SlotIndex LastCopyIdx;
1570 Register RegB = 0;
1571 unsigned SubRegB = 0;
1572 for (auto &TP : TiedPairs) {
1573 unsigned SrcIdx = TP.first;
1574 unsigned DstIdx = TP.second;
1575
1576 const MachineOperand &DstMO = MI->getOperand(DstIdx);
1577 Register RegA = DstMO.getReg();
1578
1579 // Grab RegB from the instruction because it may have changed if the
1580 // instruction was commuted.
1581 RegB = MI->getOperand(SrcIdx).getReg();
1582 SubRegB = MI->getOperand(SrcIdx).getSubReg();
1583
1584 if (RegA == RegB) {
1585 // The register is tied to multiple destinations (or else we would
1586 // not have continued this far), but this use of the register
1587 // already matches the tied destination. Leave it.
1588 AllUsesCopied = false;
1589 continue;
1590 }
1591 LastCopiedReg = RegA;
1592
1593 assert(RegB.isVirtual() && "cannot make instruction into two-address form");
1594
1595#ifndef NDEBUG
1596 // First, verify that we don't have a use of "a" in the instruction
1597 // (a = b + a for example) because our transformation will not
1598 // work. This should never occur because we are in SSA form.
1599 for (unsigned i = 0; i != MI->getNumOperands(); ++i)
1600 assert(i == DstIdx ||
1601 !MI->getOperand(i).isReg() ||
1602 MI->getOperand(i).getReg() != RegA);
1603#endif
1604
1605 // Emit a copy.
1606 MachineInstrBuilder MIB = BuildMI(*MI->getParent(), MI, MI->getDebugLoc(),
1607 TII->get(TargetOpcode::COPY), RegA);
1608 // If this operand is folding a truncation, the truncation now moves to the
1609 // copy so that the register classes remain valid for the operands.
1610 MIB.addReg(RegB, 0, SubRegB);
1611 const TargetRegisterClass *RC = MRI->getRegClass(RegB);
1612 if (SubRegB) {
1613 if (RegA.isVirtual()) {
1614 assert(TRI->getMatchingSuperRegClass(RC, MRI->getRegClass(RegA),
1615 SubRegB) &&
1616 "tied subregister must be a truncation");
1617 // The superreg class will not be used to constrain the subreg class.
1618 RC = nullptr;
1619 } else {
1620 assert(TRI->getMatchingSuperReg(RegA, SubRegB, MRI->getRegClass(RegB))
1621 && "tied subregister must be a truncation");
1622 }
1623 }
1624
1625 // Update DistanceMap.
1627 --PrevMI;
1628 DistanceMap.insert(std::make_pair(&*PrevMI, Dist));
1629 DistanceMap[MI] = ++Dist;
1630
1631 if (LIS) {
1632 LastCopyIdx = LIS->InsertMachineInstrInMaps(*PrevMI).getRegSlot();
1633
1634 SlotIndex endIdx =
1635 LIS->getInstructionIndex(*MI).getRegSlot(IsEarlyClobber);
1636 if (RegA.isVirtual()) {
1637 LiveInterval &LI = LIS->getInterval(RegA);
1638 VNInfo *VNI = LI.getNextValue(LastCopyIdx, LIS->getVNInfoAllocator());
1639 LI.addSegment(LiveRange::Segment(LastCopyIdx, endIdx, VNI));
1640 for (auto &S : LI.subranges()) {
1641 VNI = S.getNextValue(LastCopyIdx, LIS->getVNInfoAllocator());
1642 S.addSegment(LiveRange::Segment(LastCopyIdx, endIdx, VNI));
1643 }
1644 } else {
1645 for (MCRegUnit Unit : TRI->regunits(RegA)) {
1646 if (LiveRange *LR = LIS->getCachedRegUnit(Unit)) {
1647 VNInfo *VNI =
1648 LR->getNextValue(LastCopyIdx, LIS->getVNInfoAllocator());
1649 LR->addSegment(LiveRange::Segment(LastCopyIdx, endIdx, VNI));
1650 }
1651 }
1652 }
1653 }
1654
1655 LLVM_DEBUG(dbgs() << "\t\tprepend:\t" << *MIB);
1656
1657 MachineOperand &MO = MI->getOperand(SrcIdx);
1658 assert(MO.isReg() && MO.getReg() == RegB && MO.isUse() &&
1659 "inconsistent operand info for 2-reg pass");
1660 if (isPlainlyKilled(MO)) {
1661 MO.setIsKill(false);
1662 RemovedKillFlag = true;
1663 }
1664
1665 // Make sure regA is a legal regclass for the SrcIdx operand.
1666 if (RegA.isVirtual() && RegB.isVirtual())
1667 MRI->constrainRegClass(RegA, RC);
1668 MO.setReg(RegA);
1669 // The getMatchingSuper asserts guarantee that the register class projected
1670 // by SubRegB is compatible with RegA with no subregister. So regardless of
1671 // whether the dest oper writes a subreg, the source oper should not.
1672 MO.setSubReg(0);
1673
1674 // Update uses of RegB to uses of RegA inside the bundle.
1675 if (MI->isBundle()) {
1676 for (MachineOperand &MO : mi_bundle_ops(*MI)) {
1677 if (MO.isReg() && MO.getReg() == RegB) {
1678 assert(MO.getSubReg() == 0 && SubRegB == 0 &&
1679 "tied subregister uses in bundled instructions not supported");
1680 MO.setReg(RegA);
1681 }
1682 }
1683 }
1684 }
1685
1686 if (AllUsesCopied) {
1687 LaneBitmask RemainingUses = LaneBitmask::getNone();
1688 // Replace other (un-tied) uses of regB with LastCopiedReg.
1689 for (MachineOperand &MO : MI->all_uses()) {
1690 if (MO.getReg() == RegB) {
1691 if (MO.getSubReg() == SubRegB && !IsEarlyClobber) {
1692 if (isPlainlyKilled(MO)) {
1693 MO.setIsKill(false);
1694 RemovedKillFlag = true;
1695 }
1696 MO.setReg(LastCopiedReg);
1697 MO.setSubReg(0);
1698 } else {
1699 RemainingUses |= TRI->getSubRegIndexLaneMask(MO.getSubReg());
1700 }
1701 }
1702 }
1703
1704 // Update live variables for regB.
1705 if (RemovedKillFlag && RemainingUses.none() && LV &&
1706 LV->getVarInfo(RegB).removeKill(*MI)) {
1708 --PrevMI;
1709 LV->addVirtualRegisterKilled(RegB, *PrevMI);
1710 }
1711
1712 if (RemovedKillFlag && RemainingUses.none())
1713 SrcRegMap[LastCopiedReg] = RegB;
1714
1715 // Update LiveIntervals.
1716 if (LIS) {
1717 SlotIndex UseIdx = LIS->getInstructionIndex(*MI);
1718 auto Shrink = [=](LiveRange &LR, LaneBitmask LaneMask) {
1719 LiveRange::Segment *S = LR.getSegmentContaining(LastCopyIdx);
1720 if (!S)
1721 return true;
1722 if ((LaneMask & RemainingUses).any())
1723 return false;
1724 if (S->end.getBaseIndex() != UseIdx)
1725 return false;
1726 S->end = LastCopyIdx;
1727 return true;
1728 };
1729
1730 LiveInterval &LI = LIS->getInterval(RegB);
1731 bool ShrinkLI = true;
1732 for (auto &S : LI.subranges())
1733 ShrinkLI &= Shrink(S, S.LaneMask);
1734 if (ShrinkLI)
1735 Shrink(LI, LaneBitmask::getAll());
1736 }
1737 } else if (RemovedKillFlag) {
1738 // Some tied uses of regB matched their destination registers, so
1739 // regB is still used in this instruction, but a kill flag was
1740 // removed from a different tied use of regB, so now we need to add
1741 // a kill flag to one of the remaining uses of regB.
1742 for (MachineOperand &MO : MI->all_uses()) {
1743 if (MO.getReg() == RegB) {
1744 MO.setIsKill(true);
1745 break;
1746 }
1747 }
1748 }
1749}
1750
1751// For every tied operand pair this function transforms statepoint from
1752// RegA = STATEPOINT ... RegB(tied-def N)
1753// to
1754// RegB = STATEPOINT ... RegB(tied-def N)
1755// and replaces all uses of RegA with RegB.
1756// No extra COPY instruction is necessary because tied use is killed at
1757// STATEPOINT.
1758bool TwoAddressInstructionImpl::processStatepoint(
1759 MachineInstr *MI, TiedOperandMap &TiedOperands) {
1760
1761 bool NeedCopy = false;
1762 for (auto &TO : TiedOperands) {
1763 Register RegB = TO.first;
1764 if (TO.second.size() != 1) {
1765 NeedCopy = true;
1766 continue;
1767 }
1768
1769 unsigned SrcIdx = TO.second[0].first;
1770 unsigned DstIdx = TO.second[0].second;
1771
1772 MachineOperand &DstMO = MI->getOperand(DstIdx);
1773 Register RegA = DstMO.getReg();
1774
1775 assert(RegB == MI->getOperand(SrcIdx).getReg());
1776
1777 if (RegA == RegB)
1778 continue;
1779
1780 // CodeGenPrepare can sink pointer compare past statepoint, which
1781 // breaks assumption that statepoint kills tied-use register when
1782 // in SSA form (see note in IR/SafepointIRVerifier.cpp). Fall back
1783 // to generic tied register handling to avoid assertion failures.
1784 // TODO: Recompute LIS/LV information for new range here.
1785 if (LIS) {
1786 const auto &UseLI = LIS->getInterval(RegB);
1787 const auto &DefLI = LIS->getInterval(RegA);
1788 if (DefLI.overlaps(UseLI)) {
1789 LLVM_DEBUG(dbgs() << "LIS: " << printReg(RegB, TRI, 0)
1790 << " UseLI overlaps with DefLI\n");
1791 NeedCopy = true;
1792 continue;
1793 }
1794 } else if (LV && LV->getVarInfo(RegB).findKill(MI->getParent()) != MI) {
1795 // Note that MachineOperand::isKill does not work here, because it
1796 // is set only on first register use in instruction and for statepoint
1797 // tied-use register will usually be found in preceeding deopt bundle.
1798 LLVM_DEBUG(dbgs() << "LV: " << printReg(RegB, TRI, 0)
1799 << " not killed by statepoint\n");
1800 NeedCopy = true;
1801 continue;
1802 }
1803
1804 if (!MRI->constrainRegClass(RegB, MRI->getRegClass(RegA))) {
1805 LLVM_DEBUG(dbgs() << "MRI: couldn't constrain" << printReg(RegB, TRI, 0)
1806 << " to register class of " << printReg(RegA, TRI, 0)
1807 << '\n');
1808 NeedCopy = true;
1809 continue;
1810 }
1811 MRI->replaceRegWith(RegA, RegB);
1812
1813 if (LIS) {
1815 LiveInterval &LI = LIS->getInterval(RegB);
1816 LiveInterval &Other = LIS->getInterval(RegA);
1817 SmallVector<VNInfo *> NewVNIs;
1818 for (const VNInfo *VNI : Other.valnos) {
1819 assert(VNI->id == NewVNIs.size() && "assumed");
1820 NewVNIs.push_back(LI.createValueCopy(VNI, A));
1821 }
1822 for (auto &S : Other) {
1823 VNInfo *VNI = NewVNIs[S.valno->id];
1824 LiveRange::Segment NewSeg(S.start, S.end, VNI);
1825 LI.addSegment(NewSeg);
1826 }
1827 LIS->removeInterval(RegA);
1828 }
1829
1830 if (LV) {
1831 if (MI->getOperand(SrcIdx).isKill())
1832 LV->removeVirtualRegisterKilled(RegB, *MI);
1833 LiveVariables::VarInfo &SrcInfo = LV->getVarInfo(RegB);
1834 LiveVariables::VarInfo &DstInfo = LV->getVarInfo(RegA);
1835 SrcInfo.AliveBlocks |= DstInfo.AliveBlocks;
1836 DstInfo.AliveBlocks.clear();
1837 for (auto *KillMI : DstInfo.Kills)
1838 LV->addVirtualRegisterKilled(RegB, *KillMI, false);
1839 }
1840 }
1841 return !NeedCopy;
1842}
1843
1844/// Reduce two-address instructions to two operands.
1845bool TwoAddressInstructionImpl::run() {
1846 bool MadeChange = false;
1847
1848 LLVM_DEBUG(dbgs() << "********** REWRITING TWO-ADDR INSTRS **********\n");
1849 LLVM_DEBUG(dbgs() << "********** Function: " << MF->getName() << '\n');
1850
1851 // This pass takes the function out of SSA form.
1852 MRI->leaveSSA();
1853
1854 // This pass will rewrite the tied-def to meet the RegConstraint.
1855 MF->getProperties().setTiedOpsRewritten();
1856
1857 TiedOperandMap TiedOperands;
1858 for (MachineBasicBlock &MBBI : *MF) {
1859 MBB = &MBBI;
1860 unsigned Dist = 0;
1861 DistanceMap.clear();
1862 SrcRegMap.clear();
1863 DstRegMap.clear();
1864 Processed.clear();
1865 for (MachineBasicBlock::iterator mi = MBB->begin(), me = MBB->end();
1866 mi != me; ) {
1867 MachineBasicBlock::iterator nmi = std::next(mi);
1868 // Skip debug instructions.
1869 if (mi->isDebugInstr()) {
1870 mi = nmi;
1871 continue;
1872 }
1873
1874 // Expand REG_SEQUENCE instructions. This will position mi at the first
1875 // expanded instruction.
1876 if (mi->isRegSequence()) {
1877 eliminateRegSequence(mi);
1878 MadeChange = true;
1879 }
1880
1881 DistanceMap.insert(std::make_pair(&*mi, ++Dist));
1882
1883 processCopy(&*mi);
1884
1885 // First scan through all the tied register uses in this instruction
1886 // and record a list of pairs of tied operands for each register.
1887 if (!collectTiedOperands(&*mi, TiedOperands)) {
1888 removeClobberedSrcRegMap(&*mi);
1889 mi = nmi;
1890 continue;
1891 }
1892
1893 ++NumTwoAddressInstrs;
1894 MadeChange = true;
1895 LLVM_DEBUG(dbgs() << '\t' << *mi);
1896
1897 // If the instruction has a single pair of tied operands, try some
1898 // transformations that may either eliminate the tied operands or
1899 // improve the opportunities for coalescing away the register copy.
1900 if (TiedOperands.size() == 1) {
1901 SmallVectorImpl<std::pair<unsigned, unsigned>> &TiedPairs
1902 = TiedOperands.begin()->second;
1903 if (TiedPairs.size() == 1) {
1904 unsigned SrcIdx = TiedPairs[0].first;
1905 unsigned DstIdx = TiedPairs[0].second;
1906 Register SrcReg = mi->getOperand(SrcIdx).getReg();
1907 Register DstReg = mi->getOperand(DstIdx).getReg();
1908 if (SrcReg != DstReg &&
1909 tryInstructionTransform(mi, nmi, SrcIdx, DstIdx, Dist, false)) {
1910 // The tied operands have been eliminated or shifted further down
1911 // the block to ease elimination. Continue processing with 'nmi'.
1912 TiedOperands.clear();
1913 removeClobberedSrcRegMap(&*mi);
1914 mi = nmi;
1915 continue;
1916 }
1917 }
1918 }
1919
1920 if (mi->getOpcode() == TargetOpcode::STATEPOINT &&
1921 processStatepoint(&*mi, TiedOperands)) {
1922 TiedOperands.clear();
1923 LLVM_DEBUG(dbgs() << "\t\trewrite to:\t" << *mi);
1924 mi = nmi;
1925 continue;
1926 }
1927
1928 // Now iterate over the information collected above.
1929 for (auto &TO : TiedOperands) {
1930 processTiedPairs(&*mi, TO.second, Dist);
1931 LLVM_DEBUG(dbgs() << "\t\trewrite to:\t" << *mi);
1932 }
1933
1934 // Rewrite INSERT_SUBREG as COPY now that we no longer need SSA form.
1935 if (mi->isInsertSubreg()) {
1936 // From %reg = INSERT_SUBREG %reg, %subreg, subidx
1937 // To %reg:subidx = COPY %subreg
1938 unsigned SubIdx = mi->getOperand(3).getImm();
1939 mi->removeOperand(3);
1940 assert(mi->getOperand(0).getSubReg() == 0 && "Unexpected subreg idx");
1941 mi->getOperand(0).setSubReg(SubIdx);
1942 mi->getOperand(0).setIsUndef(mi->getOperand(1).isUndef());
1943 mi->removeOperand(1);
1944 mi->setDesc(TII->get(TargetOpcode::COPY));
1945 LLVM_DEBUG(dbgs() << "\t\tconvert to:\t" << *mi);
1946
1947 // Update LiveIntervals.
1948 if (LIS) {
1949 Register Reg = mi->getOperand(0).getReg();
1950 LiveInterval &LI = LIS->getInterval(Reg);
1951 if (LI.hasSubRanges()) {
1952 // The COPY no longer defines subregs of %reg except for
1953 // %reg.subidx.
1954 LaneBitmask LaneMask =
1955 TRI->getSubRegIndexLaneMask(mi->getOperand(0).getSubReg());
1956 SlotIndex Idx = LIS->getInstructionIndex(*mi).getRegSlot();
1957 for (auto &S : LI.subranges()) {
1958 if ((S.LaneMask & LaneMask).none()) {
1959 LiveRange::iterator DefSeg = S.FindSegmentContaining(Idx);
1960 if (mi->getOperand(0).isUndef()) {
1961 S.removeValNo(DefSeg->valno);
1962 } else {
1963 LiveRange::iterator UseSeg = std::prev(DefSeg);
1964 S.MergeValueNumberInto(DefSeg->valno, UseSeg->valno);
1965 }
1966 }
1967 }
1968
1969 // The COPY no longer has a use of %reg.
1970 LIS->shrinkToUses(&LI);
1971 } else {
1972 // The live interval for Reg did not have subranges but now it needs
1973 // them because we have introduced a subreg def. Recompute it.
1974 LIS->removeInterval(Reg);
1976 }
1977 }
1978 }
1979
1980 // Clear TiedOperands here instead of at the top of the loop
1981 // since most instructions do not have tied operands.
1982 TiedOperands.clear();
1983 removeClobberedSrcRegMap(&*mi);
1984 mi = nmi;
1985 }
1986 }
1987
1988 return MadeChange;
1989}
1990
1991/// Eliminate a REG_SEQUENCE instruction as part of the de-ssa process.
1992///
1993/// The instruction is turned into a sequence of sub-register copies:
1994///
1995/// %dst = REG_SEQUENCE %v1, ssub0, %v2, ssub1
1996///
1997/// Becomes:
1998///
1999/// undef %dst:ssub0 = COPY %v1
2000/// %dst:ssub1 = COPY %v2
2001void TwoAddressInstructionImpl::eliminateRegSequence(
2003 MachineInstr &MI = *MBBI;
2004 Register DstReg = MI.getOperand(0).getReg();
2005
2006 SmallVector<Register, 4> OrigRegs;
2007 VNInfo *DefVN = nullptr;
2008 if (LIS) {
2009 OrigRegs.push_back(MI.getOperand(0).getReg());
2010 for (unsigned i = 1, e = MI.getNumOperands(); i < e; i += 2)
2011 OrigRegs.push_back(MI.getOperand(i).getReg());
2012 if (LIS->hasInterval(DstReg)) {
2013 DefVN = LIS->getInterval(DstReg)
2015 .valueOut();
2016 }
2017 }
2018
2019 LaneBitmask UndefLanes = LaneBitmask::getNone();
2020 bool DefEmitted = false;
2021 for (unsigned i = 1, e = MI.getNumOperands(); i < e; i += 2) {
2022 MachineOperand &UseMO = MI.getOperand(i);
2023 Register SrcReg = UseMO.getReg();
2024 unsigned SubIdx = MI.getOperand(i+1).getImm();
2025 // Nothing needs to be inserted for undef operands.
2026 if (UseMO.isUndef()) {
2027 UndefLanes |= TRI->getSubRegIndexLaneMask(SubIdx);
2028 continue;
2029 }
2030
2031 // Defer any kill flag to the last operand using SrcReg. Otherwise, we
2032 // might insert a COPY that uses SrcReg after is was killed.
2033 bool isKill = UseMO.isKill();
2034 if (isKill)
2035 for (unsigned j = i + 2; j < e; j += 2)
2036 if (MI.getOperand(j).getReg() == SrcReg) {
2037 MI.getOperand(j).setIsKill();
2038 UseMO.setIsKill(false);
2039 isKill = false;
2040 break;
2041 }
2042
2043 // Insert the sub-register copy.
2044 MachineInstr *CopyMI = BuildMI(*MI.getParent(), MI, MI.getDebugLoc(),
2045 TII->get(TargetOpcode::COPY))
2046 .addReg(DstReg, RegState::Define, SubIdx)
2047 .add(UseMO);
2048
2049 // The first def needs an undef flag because there is no live register
2050 // before it.
2051 if (!DefEmitted) {
2052 CopyMI->getOperand(0).setIsUndef(true);
2053 // Return an iterator pointing to the first inserted instr.
2054 MBBI = CopyMI;
2055 }
2056 DefEmitted = true;
2057
2058 // Update LiveVariables' kill info.
2059 if (LV && isKill && !SrcReg.isPhysical())
2060 LV->replaceKillInstruction(SrcReg, MI, *CopyMI);
2061
2062 LLVM_DEBUG(dbgs() << "Inserted: " << *CopyMI);
2063 }
2064
2066 std::next(MachineBasicBlock::iterator(MI));
2067
2068 if (!DefEmitted) {
2069 LLVM_DEBUG(dbgs() << "Turned: " << MI << " into an IMPLICIT_DEF");
2070 MI.setDesc(TII->get(TargetOpcode::IMPLICIT_DEF));
2071 for (int j = MI.getNumOperands() - 1, ee = 0; j > ee; --j)
2072 MI.removeOperand(j);
2073 } else {
2074 if (LIS) {
2075 // Force live interval recomputation if we moved to a partial definition
2076 // of the register. Undef flags must be propagate to uses of undefined
2077 // subregister for accurate interval computation.
2078 if (UndefLanes.any() && DefVN && MRI->shouldTrackSubRegLiveness(DstReg)) {
2079 auto &LI = LIS->getInterval(DstReg);
2080 for (MachineOperand &UseOp : MRI->use_operands(DstReg)) {
2081 unsigned SubReg = UseOp.getSubReg();
2082 if (UseOp.isUndef() || !SubReg)
2083 continue;
2084 auto *VN =
2085 LI.getVNInfoAt(LIS->getInstructionIndex(*UseOp.getParent()));
2086 if (DefVN != VN)
2087 continue;
2088 LaneBitmask LaneMask = TRI->getSubRegIndexLaneMask(SubReg);
2089 if ((UndefLanes & LaneMask).any())
2090 UseOp.setIsUndef(true);
2091 }
2092 LIS->removeInterval(DstReg);
2093 }
2095 }
2096
2097 LLVM_DEBUG(dbgs() << "Eliminated: " << MI);
2098 MI.eraseFromParent();
2099 }
2100
2101 // Udpate LiveIntervals.
2102 if (LIS)
2103 LIS->repairIntervalsInRange(MBB, MBBI, EndMBBI, OrigRegs);
2104}
unsigned SubReg
unsigned const MachineRegisterInfo * MRI
MachineInstrBuilder & UseMI
MachineInstrBuilder MachineInstrBuilder & DefMI
assert(UImm &&(UImm !=~static_cast< T >(0)) &&"Invalid immediate!")
MachineBasicBlock & MBB
MachineBasicBlock MachineBasicBlock::iterator MBBI
static GCRegistry::Add< ErlangGC > A("erlang", "erlang-compatible garbage collector")
This file defines the DenseMap class.
#define DEBUG_TYPE
const HexagonInstrInfo * TII
#define _
IRTranslator LLVM IR MI
const size_t AbstractManglingParser< Derived, Alloc >::NumOps
#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)
#define INITIALIZE_PASS(passName, arg, name, cfg, analysis)
Definition PassSupport.h:56
Remove Loads Into Fake Uses
SI Optimize VGPR LiveRange
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:114
static bool isTwoAddrUse(MachineInstr &MI, Register Reg, Register &DstReg)
Return true if the specified MI uses the specified register as a two-address use.
static MCRegister getMappedReg(Register Reg, DenseMap< Register, Register > &RegMap)
Return the physical register the specified virtual register might be mapped to.
static cl::opt< bool > EnableRescheduling("twoaddr-reschedule", cl::desc("Coalesce copies by rescheduling (default=true)"), cl::init(true), cl::Hidden)
static cl::opt< unsigned > MaxDataFlowEdge("dataflow-edge-limit", cl::Hidden, cl::init(3), cl::desc("Maximum number of dataflow edges to traverse when evaluating " "the benefit of commuting operands"))
PassT::Result * getCachedResult(IRUnitT &IR) const
Get the cached result of an analysis pass for a given IR unit.
AnalysisUsage & addPreservedID(const void *ID)
AnalysisUsage & addUsedIfAvailable()
Add the specified Pass class to the set of analyses used by this pass.
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:270
Represents analyses that only rely on functions' control flow.
Definition Analysis.h:73
iterator find(const_arg_type_t< KeyT > Val)
Definition DenseMap.h:178
bool erase(const KeyT &Val)
Definition DenseMap.h:330
iterator end()
Definition DenseMap.h:81
std::pair< iterator, bool > insert(const std::pair< KeyT, ValueT > &KV)
Definition DenseMap.h:241
bool hasOptNone() const
Do not optimize this function (-O0).
Definition Function.h:700
unsigned getInstrLatency(const InstrItineraryData *ItinData, const MachineInstr &MI, unsigned *PredCost=nullptr) const override
Compute the instruction latency of a given instruction.
Itinerary data supplied by a subtarget to be used by a target.
bool hasSubRanges() const
Returns true if subregister liveness information is available.
iterator_range< subrange_iterator > subranges()
LLVM_ABI void repairIntervalsInRange(MachineBasicBlock *MBB, MachineBasicBlock::iterator Begin, MachineBasicBlock::iterator End, ArrayRef< Register > OrigRegs)
Update live intervals for instructions in a range of iterators.
bool hasInterval(Register Reg) const
MachineInstr * getInstructionFromIndex(SlotIndex index) const
Returns the instruction associated with the given index.
SlotIndex InsertMachineInstrInMaps(MachineInstr &MI)
LLVM_ABI void handleMove(MachineInstr &MI, bool UpdateFlags=false)
Call this method to notify LiveIntervals that instruction MI has been moved within a basic block.
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)
void removeInterval(Register Reg)
Interval removal.
bool isNotInMIMap(const MachineInstr &Instr) const
Returns true if the specified machine instr has been removed or was never entered in the map.
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 bool shrinkToUses(LiveInterval *li, SmallVectorImpl< MachineInstr * > *dead=nullptr)
After removing some uses of a register, shrink its live range to just the remaining uses.
LiveInterval & createAndComputeVirtRegInterval(Register Reg)
VNInfo * valueOut() const
Return the value leaving the instruction, if any.
This class represents the liveness of a register, stack slot, etc.
LLVM_ABI iterator addSegment(Segment S)
Add the specified Segment to this range, merging segments as appropriate.
const Segment * getSegmentContaining(SlotIndex Idx) const
Return the segment that contains the specified index, or null if there is none.
VNInfo * createValueCopy(const VNInfo *orig, VNInfo::Allocator &VNInfoAllocator)
Create a copy of the given value.
LiveQueryResult Query(SlotIndex Idx) const
Query Liveness at Idx.
iterator begin()
bool hasAtLeastOneValue() const
VNInfo * getNextValue(SlotIndex Def, VNInfo::Allocator &VNInfoAllocator)
getNextValue - Create a new value number and return it.
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().
LLVM_ABI void replaceKillInstruction(Register Reg, MachineInstr &OldMI, MachineInstr &NewMI)
replaceKillInstruction - Update register kill info by replacing a kill instruction with a new one.
bool removeVirtualRegisterDead(Register Reg, MachineInstr &MI)
removeVirtualRegisterDead - Remove the specified kill of the virtual register from the live variable ...
bool removeVirtualRegisterKilled(Register Reg, MachineInstr &MI)
removeVirtualRegisterKilled - Remove the specified kill of the virtual register from the live variabl...
void addVirtualRegisterDead(Register IncomingReg, MachineInstr &MI, bool AddIfNotFound=false)
addVirtualRegisterDead - Add information about the fact that the specified register is dead after bei...
void addVirtualRegisterKilled(Register IncomingReg, MachineInstr &MI, bool AddIfNotFound=false)
addVirtualRegisterKilled - Add information about the fact that the specified register is killed after...
LLVM_ABI VarInfo & getVarInfo(Register Reg)
getVarInfo - Return the VarInfo structure for the specified VIRTUAL register.
unsigned getNumDefs() const
Return the number of MachineOperands that are register definitions.
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.
LLVM_ABI instr_iterator insert(instr_iterator I, MachineInstr *M)
Insert MI into the instruction list before I, possibly inside a bundle.
LLVM_ABI instr_iterator erase(instr_iterator I)
Remove an instruction from the instruction list and delete it.
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
Analysis pass which computes a MachineDominatorTree.
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.
StringRef getName() const
getName - Return the name of the corresponding LLVM function.
void makeDebugValueSubstitution(DebugInstrOperandPair, DebugInstrOperandPair, unsigned SubReg=0)
Create a substitution between one <instr,operand> value to a different, new value.
Function & getFunction()
Return the LLVM function that this machine code represents.
const MachineFunctionProperties & getProperties() const
Get the function properties.
const MachineInstrBuilder & add(const MachineOperand &MO) const
const MachineInstrBuilder & addReg(Register RegNo, unsigned Flags=0, unsigned SubReg=0) const
Add a new virtual register operand.
Representation of each machine instruction.
mop_range defs()
Returns all explicit operands that are register definitions.
bool isTerminator(QueryType Type=AnyInBundle) const
Returns true if this instruction part of the terminator for a basic block.
bool isCopy() const
bool isCopyLike() const
Return true if the instruction behaves like a copy.
bool isCall(QueryType Type=AnyInBundle) const
LLVM_ABI bool isSafeToMove(bool &SawStore) const
Return true if it is safe to move this instruction.
bool isBranch(QueryType Type=AnyInBundle) const
Returns true if this is a conditional, unconditional, or indirect branch.
mop_range operands()
LLVM_ABI bool hasUnmodeledSideEffects() const
Return true if this instruction has side effects that are not modeled by mayLoad / mayStore,...
LLVM_ABI unsigned getNumExplicitDefs() const
Returns the number of non-implicit definitions.
LLVM_ABI unsigned getDebugInstrNum()
Fetch the instruction number of this MachineInstr.
const MachineOperand & getOperand(unsigned i) const
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 unsigned getOperandNo() const
Returns the index of this operand in the instruction that it belongs to.
bool isReg() const
isReg - Tests if this is a MO_Register operand.
bool isRegMask() const
isRegMask - Tests if this is a MO_RegisterMask operand.
LLVM_ABI void setReg(Register Reg)
Change the register this operand corresponds to.
void setIsKill(bool Val=true)
MachineInstr * getParent()
getParent - Return the instruction that this operand belongs to.
void setIsUndef(bool Val=true)
Register getReg() const
getReg - Returns the register number.
static bool clobbersPhysReg(const uint32_t *RegMask, MCRegister PhysReg)
clobbersPhysReg - Returns true if this RegMask clobbers PhysReg.
MachineRegisterInfo - Keep track of information for virtual and physical registers,...
defusechain_iterator< false, true, false, true, false > def_iterator
def_iterator/def_begin/def_end - Walk all defs of the specified register.
static LLVM_ABI PassRegistry * getPassRegistry()
getPassRegistry - Access the global registry object, which is automatically initialized at applicatio...
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
Wrapper class representing virtual and physical registers.
Definition Register.h:20
constexpr bool isVirtual() const
Return true if the specified register number is in the virtual register namespace.
Definition Register.h:79
constexpr bool isPhysical() const
Return true if the specified register number is in the physical register namespace.
Definition Register.h:83
static bool isSameInstr(SlotIndex A, SlotIndex B)
isSameInstr - Return true if A and B refer to the same instruction.
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.
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 push_back(const T &Elt)
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...
PreservedAnalyses run(MachineFunction &MF, MachineFunctionAnalysisManager &MFAM)
BumpPtrAllocator Allocator
unsigned id
The ID number of this value.
IteratorT begin() const
Changed
This provides a very simple, boring adaptor for a begin and end iterator into a range type.
constexpr bool any(E Val)
@ Define
Register definition.
initializer< Ty > init(const Ty &Val)
PointerTypeMap run(const Module &M)
Compute the PointerTypeMap for the module M.
constexpr double e
NodeAddr< DefNode * > Def
Definition RDFGraph.h:384
NodeAddr< FuncNode * > Func
Definition RDFGraph.h:393
This is an optimization pass for GlobalISel generic memory operations.
Definition Types.h:26
bool all_of(R &&range, UnaryPredicate P)
Provide wrappers to std::all_of which take ranges instead of having to pass begin/end explicitly.
Definition STLExtras.h:1737
MachineInstrBuilder BuildMI(MachineFunction &MF, const MIMetadata &MIMD, const MCInstrDesc &MCID)
Builder interface. Specify how to create the initial instruction itself.
LLVM_ABI char & MachineDominatorsID
MachineDominators - This pass is a machine dominators analysis pass.
iterator_range< T > make_range(T x, T y)
Convenience function for iterating over sub-ranges.
AnalysisManager< MachineFunction > MachineFunctionAnalysisManager
LLVM_ABI PreservedAnalyses getMachineFunctionPassPreservedAnalyses()
Returns the minimum set of Analyses that all machine function passes must preserve.
IterT skipDebugInstructionsForward(IterT It, IterT End, bool SkipPseudoOp=true)
Increment It until it points to a non-debug instruction or to End and return the resulting iterator.
void erase(Container &C, ValueType V)
Wrapper function to remove a value from a container:
Definition STLExtras.h:2190
LLVM_ABI char & MachineLoopInfoID
MachineLoopInfo - This pass is a loop analysis pass.
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:1744
LLVM_ABI raw_ostream & dbgs()
dbgs() - This returns a reference to a raw_ostream for debugging messages.
Definition Debug.cpp:207
CodeGenOptLevel
Code generation optimization level.
Definition CodeGen.h:82
class LLVM_GSL_OWNER SmallVector
Forward declaration of SmallVector so that calculateSmallVectorDefaultInlinedElements can reference s...
@ Other
Any other memory.
Definition ModRef.h:68
iterator_range< MIBundleOperands > mi_bundle_ops(MachineInstr &MI)
LLVM_ABI void initializeTwoAddressInstructionLegacyPassPass(PassRegistry &)
LLVM_ABI char & TwoAddressInstructionPassID
TwoAddressInstruction - This pass reduces two-address instructions to use two operands.
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.
static constexpr LaneBitmask getAll()
Definition LaneBitmask.h:82
constexpr bool none() const
Definition LaneBitmask.h:52
constexpr bool any() const
Definition LaneBitmask.h:53
static constexpr LaneBitmask getNone()
Definition LaneBitmask.h:81
bool removeKill(MachineInstr &MI)
removeKill - Delete a kill corresponding to the specified machine instruction.
std::vector< MachineInstr * > Kills
Kills - List of MachineInstruction's which are the last use of this virtual register (kill it) in the...
SparseBitVector AliveBlocks
AliveBlocks - Set of blocks in which this value is alive completely through.
LLVM_ABI MachineInstr * findKill(const MachineBasicBlock *MBB) const
findKill - Find a kill instruction in MBB. Return NULL if none is found.