1 //===--- X86DomainReassignment.cpp - Selectively switch register classes---===//
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 pass attempts to find instruction chains (closures) in one domain,
10 // and convert them to equivalent instructions in a different domain,
11 // if profitable.
12 //
13 //===----------------------------------------------------------------------===//
14 
15 #include "X86.h"
16 #include "X86InstrInfo.h"
17 #include "X86Subtarget.h"
18 #include "llvm/ADT/DenseMap.h"
19 #include "llvm/ADT/DenseMapInfo.h"
20 #include "llvm/ADT/STLExtras.h"
21 #include "llvm/ADT/SmallVector.h"
22 #include "llvm/ADT/Statistic.h"
23 #include "llvm/CodeGen/MachineFunctionPass.h"
24 #include "llvm/CodeGen/MachineInstrBuilder.h"
25 #include "llvm/CodeGen/MachineRegisterInfo.h"
26 #include "llvm/CodeGen/TargetRegisterInfo.h"
27 #include "llvm/Support/Debug.h"
28 #include "llvm/Support/Printable.h"
29 #include <bitset>
30 
31 using namespace llvm;
32 
33 #define DEBUG_TYPE "x86-domain-reassignment"
34 
35 STATISTIC(NumClosuresConverted, "Number of closures converted by the pass");
36 
37 static cl::opt<bool> DisableX86DomainReassignment(
38     "disable-x86-domain-reassignment", cl::Hidden,
39     cl::desc("X86: Disable Virtual Register Reassignment."), cl::init(false));
40 
41 namespace {
42 enum RegDomain { NoDomain = -1, GPRDomain, MaskDomain, OtherDomain, NumDomains };
43 
44 static bool isGPR(const TargetRegisterClass *RC) {
45   return X86::GR64RegClass.hasSubClassEq(RC) ||
46          X86::GR32RegClass.hasSubClassEq(RC) ||
47          X86::GR16RegClass.hasSubClassEq(RC) ||
48          X86::GR8RegClass.hasSubClassEq(RC);
49 }
50 
51 static bool isMask(const TargetRegisterClass *RC,
52                    const TargetRegisterInfo *TRI) {
53   return X86::VK16RegClass.hasSubClassEq(RC);
54 }
55 
56 static RegDomain getDomain(const TargetRegisterClass *RC,
57                            const TargetRegisterInfo *TRI) {
58   if (isGPR(RC))
59     return GPRDomain;
60   if (isMask(RC, TRI))
61     return MaskDomain;
62   return OtherDomain;
63 }
64 
65 /// Return a register class equivalent to \p SrcRC, in \p Domain.
66 static const TargetRegisterClass *getDstRC(const TargetRegisterClass *SrcRC,
67                                            RegDomain Domain) {
68   assert(Domain == MaskDomain && "add domain");
69   if (X86::GR8RegClass.hasSubClassEq(SrcRC))
70     return &X86::VK8RegClass;
71   if (X86::GR16RegClass.hasSubClassEq(SrcRC))
72     return &X86::VK16RegClass;
73   if (X86::GR32RegClass.hasSubClassEq(SrcRC))
74     return &X86::VK32RegClass;
75   if (X86::GR64RegClass.hasSubClassEq(SrcRC))
76     return &X86::VK64RegClass;
77   llvm_unreachable("add register class");
78   return nullptr;
79 }
80 
81 /// Abstract Instruction Converter class.
82 class InstrConverterBase {
83 protected:
84   unsigned SrcOpcode;
85 
86 public:
87   InstrConverterBase(unsigned SrcOpcode) : SrcOpcode(SrcOpcode) {}
88 
89   virtual ~InstrConverterBase() {}
90 
91   /// \returns true if \p MI is legal to convert.
92   virtual bool isLegal(const MachineInstr *MI,
93                        const TargetInstrInfo *TII) const {
94     assert(MI->getOpcode() == SrcOpcode &&
95            "Wrong instruction passed to converter");
96     return true;
97   }
98 
99   /// Applies conversion to \p MI.
100   ///
101   /// \returns true if \p MI is no longer need, and can be deleted.
102   virtual bool convertInstr(MachineInstr *MI, const TargetInstrInfo *TII,
103                             MachineRegisterInfo *MRI) const = 0;
104 
105   /// \returns the cost increment incurred by converting \p MI.
106   virtual double getExtraCost(const MachineInstr *MI,
107                               MachineRegisterInfo *MRI) const = 0;
108 };
109 
110 /// An Instruction Converter which ignores the given instruction.
111 /// For example, PHI instructions can be safely ignored since only the registers
112 /// need to change.
113 class InstrIgnore : public InstrConverterBase {
114 public:
115   InstrIgnore(unsigned SrcOpcode) : InstrConverterBase(SrcOpcode) {}
116 
117   bool convertInstr(MachineInstr *MI, const TargetInstrInfo *TII,
118                     MachineRegisterInfo *MRI) const override {
119     assert(isLegal(MI, TII) && "Cannot convert instruction");
120     return false;
121   }
122 
123   double getExtraCost(const MachineInstr *MI,
124                       MachineRegisterInfo *MRI) const override {
125     return 0;
126   }
127 };
128 
129 /// An Instruction Converter which replaces an instruction with another.
130 class InstrReplacer : public InstrConverterBase {
131 public:
132   /// Opcode of the destination instruction.
133   unsigned DstOpcode;
134 
135   InstrReplacer(unsigned SrcOpcode, unsigned DstOpcode)
136       : InstrConverterBase(SrcOpcode), DstOpcode(DstOpcode) {}
137 
138   bool isLegal(const MachineInstr *MI,
139                const TargetInstrInfo *TII) const override {
140     if (!InstrConverterBase::isLegal(MI, TII))
141       return false;
142     // It's illegal to replace an instruction that implicitly defines a register
143     // with an instruction that doesn't, unless that register dead.
144     for (auto &MO : MI->implicit_operands())
145       if (MO.isReg() && MO.isDef() && !MO.isDead() &&
146           !TII->get(DstOpcode).hasImplicitDefOfPhysReg(MO.getReg()))
147         return false;
148     return true;
149   }
150 
151   bool convertInstr(MachineInstr *MI, const TargetInstrInfo *TII,
152                     MachineRegisterInfo *MRI) const override {
153     assert(isLegal(MI, TII) && "Cannot convert instruction");
154     MachineInstrBuilder Bld =
155         BuildMI(*MI->getParent(), MI, MI->getDebugLoc(), TII->get(DstOpcode));
156     // Transfer explicit operands from original instruction. Implicit operands
157     // are handled by BuildMI.
158     for (auto &Op : MI->explicit_operands())
159       Bld.add(Op);
160     return true;
161   }
162 
163   double getExtraCost(const MachineInstr *MI,
164                       MachineRegisterInfo *MRI) const override {
165     // Assuming instructions have the same cost.
166     return 0;
167   }
168 };
169 
170 /// An Instruction Converter which replaces an instruction with another, and
171 /// adds a COPY from the new instruction's destination to the old one's.
172 class InstrReplacerDstCOPY : public InstrConverterBase {
173 public:
174   unsigned DstOpcode;
175 
176   InstrReplacerDstCOPY(unsigned SrcOpcode, unsigned DstOpcode)
177       : InstrConverterBase(SrcOpcode), DstOpcode(DstOpcode) {}
178 
179   bool convertInstr(MachineInstr *MI, const TargetInstrInfo *TII,
180                     MachineRegisterInfo *MRI) const override {
181     assert(isLegal(MI, TII) && "Cannot convert instruction");
182     MachineBasicBlock *MBB = MI->getParent();
183     auto &DL = MI->getDebugLoc();
184 
185     unsigned Reg = MRI->createVirtualRegister(
186         TII->getRegClass(TII->get(DstOpcode), 0, MRI->getTargetRegisterInfo(),
187                          *MBB->getParent()));
188     MachineInstrBuilder Bld = BuildMI(*MBB, MI, DL, TII->get(DstOpcode), Reg);
189     for (unsigned Idx = 1, End = MI->getNumOperands(); Idx < End; ++Idx)
190       Bld.add(MI->getOperand(Idx));
191 
192     BuildMI(*MBB, MI, DL, TII->get(TargetOpcode::COPY))
193         .add(MI->getOperand(0))
194         .addReg(Reg);
195 
196     return true;
197   }
198 
199   double getExtraCost(const MachineInstr *MI,
200                       MachineRegisterInfo *MRI) const override {
201     // Assuming instructions have the same cost, and that COPY is in the same
202     // domain so it will be eliminated.
203     return 0;
204   }
205 };
206 
207 /// An Instruction Converter for replacing COPY instructions.
208 class InstrCOPYReplacer : public InstrReplacer {
209 public:
210   RegDomain DstDomain;
211 
212   InstrCOPYReplacer(unsigned SrcOpcode, RegDomain DstDomain, unsigned DstOpcode)
213       : InstrReplacer(SrcOpcode, DstOpcode), DstDomain(DstDomain) {}
214 
215   bool isLegal(const MachineInstr *MI,
216                const TargetInstrInfo *TII) const override {
217     if (!InstrConverterBase::isLegal(MI, TII))
218       return false;
219 
220     // Don't allow copies to/flow GR8/GR16 physical registers.
221     // FIXME: Is there some better way to support this?
222     unsigned DstReg = MI->getOperand(0).getReg();
223     if (TargetRegisterInfo::isPhysicalRegister(DstReg) &&
224         (X86::GR8RegClass.contains(DstReg) ||
225          X86::GR16RegClass.contains(DstReg)))
226       return false;
227     unsigned SrcReg = MI->getOperand(1).getReg();
228     if (TargetRegisterInfo::isPhysicalRegister(SrcReg) &&
229         (X86::GR8RegClass.contains(SrcReg) ||
230          X86::GR16RegClass.contains(SrcReg)))
231       return false;
232 
233     return true;
234   }
235 
236   double getExtraCost(const MachineInstr *MI,
237                       MachineRegisterInfo *MRI) const override {
238     assert(MI->getOpcode() == TargetOpcode::COPY && "Expected a COPY");
239 
240     for (auto &MO : MI->operands()) {
241       // Physical registers will not be converted. Assume that converting the
242       // COPY to the destination domain will eventually result in a actual
243       // instruction.
244       if (TargetRegisterInfo::isPhysicalRegister(MO.getReg()))
245         return 1;
246 
247       RegDomain OpDomain = getDomain(MRI->getRegClass(MO.getReg()),
248                                      MRI->getTargetRegisterInfo());
249       // Converting a cross domain COPY to a same domain COPY should eliminate
250       // an insturction
251       if (OpDomain == DstDomain)
252         return -1;
253     }
254     return 0;
255   }
256 };
257 
258 /// An Instruction Converter which replaces an instruction with a COPY.
259 class InstrReplaceWithCopy : public InstrConverterBase {
260 public:
261   // Source instruction operand Index, to be used as the COPY source.
262   unsigned SrcOpIdx;
263 
264   InstrReplaceWithCopy(unsigned SrcOpcode, unsigned SrcOpIdx)
265       : InstrConverterBase(SrcOpcode), SrcOpIdx(SrcOpIdx) {}
266 
267   bool convertInstr(MachineInstr *MI, const TargetInstrInfo *TII,
268                     MachineRegisterInfo *MRI) const override {
269     assert(isLegal(MI, TII) && "Cannot convert instruction");
270     BuildMI(*MI->getParent(), MI, MI->getDebugLoc(),
271             TII->get(TargetOpcode::COPY))
272         .add({MI->getOperand(0), MI->getOperand(SrcOpIdx)});
273     return true;
274   }
275 
276   double getExtraCost(const MachineInstr *MI,
277                       MachineRegisterInfo *MRI) const override {
278     return 0;
279   }
280 };
281 
282 // Key type to be used by the Instruction Converters map.
283 // A converter is identified by <destination domain, source opcode>
284 typedef std::pair<int, unsigned> InstrConverterBaseKeyTy;
285 
286 typedef DenseMap<InstrConverterBaseKeyTy, InstrConverterBase *>
287     InstrConverterBaseMap;
288 
289 /// A closure is a set of virtual register representing all of the edges in
290 /// the closure, as well as all of the instructions connected by those edges.
291 ///
292 /// A closure may encompass virtual registers in the same register bank that
293 /// have different widths. For example, it may contain 32-bit GPRs as well as
294 /// 64-bit GPRs.
295 ///
296 /// A closure that computes an address (i.e. defines a virtual register that is
297 /// used in a memory operand) excludes the instructions that contain memory
298 /// operands using the address. Such an instruction will be included in a
299 /// different closure that manipulates the loaded or stored value.
300 class Closure {
301 private:
302   /// Virtual registers in the closure.
303   DenseSet<unsigned> Edges;
304 
305   /// Instructions in the closure.
306   SmallVector<MachineInstr *, 8> Instrs;
307 
308   /// Domains which this closure can legally be reassigned to.
309   std::bitset<NumDomains> LegalDstDomains;
310 
311   /// An ID to uniquely identify this closure, even when it gets
312   /// moved around
313   unsigned ID;
314 
315 public:
316   Closure(unsigned ID, std::initializer_list<RegDomain> LegalDstDomainList) : ID(ID) {
317     for (RegDomain D : LegalDstDomainList)
318       LegalDstDomains.set(D);
319   }
320 
321   /// Mark this closure as illegal for reassignment to all domains.
322   void setAllIllegal() { LegalDstDomains.reset(); }
323 
324   /// \returns true if this closure has domains which are legal to reassign to.
325   bool hasLegalDstDomain() const { return LegalDstDomains.any(); }
326 
327   /// \returns true if is legal to reassign this closure to domain \p RD.
328   bool isLegal(RegDomain RD) const { return LegalDstDomains[RD]; }
329 
330   /// Mark this closure as illegal for reassignment to domain \p RD.
331   void setIllegal(RegDomain RD) { LegalDstDomains[RD] = false; }
332 
333   bool empty() const { return Edges.empty(); }
334 
335   bool insertEdge(unsigned Reg) {
336     return Edges.insert(Reg).second;
337   }
338 
339   using const_edge_iterator = DenseSet<unsigned>::const_iterator;
340   iterator_range<const_edge_iterator> edges() const {
341     return iterator_range<const_edge_iterator>(Edges.begin(), Edges.end());
342   }
343 
344   void addInstruction(MachineInstr *I) {
345     Instrs.push_back(I);
346   }
347 
348   ArrayRef<MachineInstr *> instructions() const {
349     return Instrs;
350   }
351 
352   LLVM_DUMP_METHOD void dump(const MachineRegisterInfo *MRI) const {
353     dbgs() << "Registers: ";
354     bool First = true;
355     for (unsigned Reg : Edges) {
356       if (!First)
357         dbgs() << ", ";
358       First = false;
359       dbgs() << printReg(Reg, MRI->getTargetRegisterInfo(), 0, MRI);
360     }
361     dbgs() << "\n" << "Instructions:";
362     for (MachineInstr *MI : Instrs) {
363       dbgs() << "\n  ";
364       MI->print(dbgs());
365     }
366     dbgs() << "\n";
367   }
368 
369   unsigned getID() const {
370     return ID;
371   }
372 
373 };
374 
375 class X86DomainReassignment : public MachineFunctionPass {
376   const X86Subtarget *STI;
377   MachineRegisterInfo *MRI;
378   const X86InstrInfo *TII;
379 
380   /// All edges that are included in some closure
381   DenseSet<unsigned> EnclosedEdges;
382 
383   /// All instructions that are included in some closure.
384   DenseMap<MachineInstr *, unsigned> EnclosedInstrs;
385 
386 public:
387   static char ID;
388 
389   X86DomainReassignment() : MachineFunctionPass(ID) {
390     initializeX86DomainReassignmentPass(*PassRegistry::getPassRegistry());
391   }
392 
393   bool runOnMachineFunction(MachineFunction &MF) override;
394 
395   void getAnalysisUsage(AnalysisUsage &AU) const override {
396     AU.setPreservesCFG();
397     MachineFunctionPass::getAnalysisUsage(AU);
398   }
399 
400   StringRef getPassName() const override {
401     return "X86 Domain Reassignment Pass";
402   }
403 
404 private:
405   /// A map of available Instruction Converters.
406   InstrConverterBaseMap Converters;
407 
408   /// Initialize Converters map.
409   void initConverters();
410 
411   /// Starting from \Reg, expand the closure as much as possible.
412   void buildClosure(Closure &, unsigned Reg);
413 
414   /// Enqueue \p Reg to be considered for addition to the closure.
415   void visitRegister(Closure &, unsigned Reg, RegDomain &Domain,
416                      SmallVectorImpl<unsigned> &Worklist);
417 
418   /// Reassign the closure to \p Domain.
419   void reassign(const Closure &C, RegDomain Domain) const;
420 
421   /// Add \p MI to the closure.
422   void encloseInstr(Closure &C, MachineInstr *MI);
423 
424   /// /returns true if it is profitable to reassign the closure to \p Domain.
425   bool isReassignmentProfitable(const Closure &C, RegDomain Domain) const;
426 
427   /// Calculate the total cost of reassigning the closure to \p Domain.
428   double calculateCost(const Closure &C, RegDomain Domain) const;
429 };
430 
431 char X86DomainReassignment::ID = 0;
432 
433 } // End anonymous namespace.
434 
435 void X86DomainReassignment::visitRegister(Closure &C, unsigned Reg,
436                                           RegDomain &Domain,
437                                           SmallVectorImpl<unsigned> &Worklist) {
438   if (EnclosedEdges.count(Reg))
439     return;
440 
441   if (!TargetRegisterInfo::isVirtualRegister(Reg))
442     return;
443 
444   if (!MRI->hasOneDef(Reg))
445     return;
446 
447   RegDomain RD = getDomain(MRI->getRegClass(Reg), MRI->getTargetRegisterInfo());
448   // First edge in closure sets the domain.
449   if (Domain == NoDomain)
450     Domain = RD;
451 
452   if (Domain != RD)
453     return;
454 
455   Worklist.push_back(Reg);
456 }
457 
458 void X86DomainReassignment::encloseInstr(Closure &C, MachineInstr *MI) {
459   auto I = EnclosedInstrs.find(MI);
460   if (I != EnclosedInstrs.end()) {
461     if (I->second != C.getID())
462       // Instruction already belongs to another closure, avoid conflicts between
463       // closure and mark this closure as illegal.
464       C.setAllIllegal();
465     return;
466   }
467 
468   EnclosedInstrs[MI] = C.getID();
469   C.addInstruction(MI);
470 
471   // Mark closure as illegal for reassignment to domains, if there is no
472   // converter for the instruction or if the converter cannot convert the
473   // instruction.
474   for (int i = 0; i != NumDomains; ++i) {
475     if (C.isLegal((RegDomain)i)) {
476       InstrConverterBase *IC = Converters.lookup({i, MI->getOpcode()});
477       if (!IC || !IC->isLegal(MI, TII))
478         C.setIllegal((RegDomain)i);
479     }
480   }
481 }
482 
483 double X86DomainReassignment::calculateCost(const Closure &C,
484                                             RegDomain DstDomain) const {
485   assert(C.isLegal(DstDomain) && "Cannot calculate cost for illegal closure");
486 
487   double Cost = 0.0;
488   for (auto *MI : C.instructions())
489     Cost +=
490         Converters.lookup({DstDomain, MI->getOpcode()})->getExtraCost(MI, MRI);
491   return Cost;
492 }
493 
494 bool X86DomainReassignment::isReassignmentProfitable(const Closure &C,
495                                                      RegDomain Domain) const {
496   return calculateCost(C, Domain) < 0.0;
497 }
498 
499 void X86DomainReassignment::reassign(const Closure &C, RegDomain Domain) const {
500   assert(C.isLegal(Domain) && "Cannot convert illegal closure");
501 
502   // Iterate all instructions in the closure, convert each one using the
503   // appropriate converter.
504   SmallVector<MachineInstr *, 8> ToErase;
505   for (auto *MI : C.instructions())
506     if (Converters.lookup({Domain, MI->getOpcode()})
507             ->convertInstr(MI, TII, MRI))
508       ToErase.push_back(MI);
509 
510   // Iterate all registers in the closure, replace them with registers in the
511   // destination domain.
512   for (unsigned Reg : C.edges()) {
513     MRI->setRegClass(Reg, getDstRC(MRI->getRegClass(Reg), Domain));
514     for (auto &MO : MRI->use_operands(Reg)) {
515       if (MO.isReg())
516         // Remove all subregister references as they are not valid in the
517         // destination domain.
518         MO.setSubReg(0);
519     }
520   }
521 
522   for (auto MI : ToErase)
523     MI->eraseFromParent();
524 }
525 
526 /// \returns true when \p Reg is used as part of an address calculation in \p
527 /// MI.
528 static bool usedAsAddr(const MachineInstr &MI, unsigned Reg,
529                        const TargetInstrInfo *TII) {
530   if (!MI.mayLoadOrStore())
531     return false;
532 
533   const MCInstrDesc &Desc = TII->get(MI.getOpcode());
534   int MemOpStart = X86II::getMemoryOperandNo(Desc.TSFlags);
535   if (MemOpStart == -1)
536     return false;
537 
538   MemOpStart += X86II::getOperandBias(Desc);
539   for (unsigned MemOpIdx = MemOpStart,
540                 MemOpEnd = MemOpStart + X86::AddrNumOperands;
541        MemOpIdx < MemOpEnd; ++MemOpIdx) {
542     auto &Op = MI.getOperand(MemOpIdx);
543     if (Op.isReg() && Op.getReg() == Reg)
544       return true;
545   }
546   return false;
547 }
548 
549 void X86DomainReassignment::buildClosure(Closure &C, unsigned Reg) {
550   SmallVector<unsigned, 4> Worklist;
551   RegDomain Domain = NoDomain;
552   visitRegister(C, Reg, Domain, Worklist);
553   while (!Worklist.empty()) {
554     unsigned CurReg = Worklist.pop_back_val();
555 
556     // Register already in this closure.
557     if (!C.insertEdge(CurReg))
558       continue;
559     EnclosedEdges.insert(Reg);
560 
561     MachineInstr *DefMI = MRI->getVRegDef(CurReg);
562     encloseInstr(C, DefMI);
563 
564     // Add register used by the defining MI to the worklist.
565     // Do not add registers which are used in address calculation, they will be
566     // added to a different closure.
567     int OpEnd = DefMI->getNumOperands();
568     const MCInstrDesc &Desc = DefMI->getDesc();
569     int MemOp = X86II::getMemoryOperandNo(Desc.TSFlags);
570     if (MemOp != -1)
571       MemOp += X86II::getOperandBias(Desc);
572     for (int OpIdx = 0; OpIdx < OpEnd; ++OpIdx) {
573       if (OpIdx == MemOp) {
574         // skip address calculation.
575         OpIdx += (X86::AddrNumOperands - 1);
576         continue;
577       }
578       auto &Op = DefMI->getOperand(OpIdx);
579       if (!Op.isReg() || !Op.isUse())
580         continue;
581       visitRegister(C, Op.getReg(), Domain, Worklist);
582     }
583 
584     // Expand closure through register uses.
585     for (auto &UseMI : MRI->use_nodbg_instructions(CurReg)) {
586       // We would like to avoid converting closures which calculare addresses,
587       // as this should remain in GPRs.
588       if (usedAsAddr(UseMI, CurReg, TII)) {
589         C.setAllIllegal();
590         continue;
591       }
592       encloseInstr(C, &UseMI);
593 
594       for (auto &DefOp : UseMI.defs()) {
595         if (!DefOp.isReg())
596           continue;
597 
598         unsigned DefReg = DefOp.getReg();
599         if (!TargetRegisterInfo::isVirtualRegister(DefReg)) {
600           C.setAllIllegal();
601           continue;
602         }
603         visitRegister(C, DefReg, Domain, Worklist);
604       }
605     }
606   }
607 }
608 
609 void X86DomainReassignment::initConverters() {
610   Converters[{MaskDomain, TargetOpcode::PHI}] =
611       new InstrIgnore(TargetOpcode::PHI);
612 
613   Converters[{MaskDomain, TargetOpcode::IMPLICIT_DEF}] =
614       new InstrIgnore(TargetOpcode::IMPLICIT_DEF);
615 
616   Converters[{MaskDomain, TargetOpcode::INSERT_SUBREG}] =
617       new InstrReplaceWithCopy(TargetOpcode::INSERT_SUBREG, 2);
618 
619   Converters[{MaskDomain, TargetOpcode::COPY}] =
620       new InstrCOPYReplacer(TargetOpcode::COPY, MaskDomain, TargetOpcode::COPY);
621 
622   auto createReplacerDstCOPY = [&](unsigned From, unsigned To) {
623     Converters[{MaskDomain, From}] = new InstrReplacerDstCOPY(From, To);
624   };
625 
626   createReplacerDstCOPY(X86::MOVZX32rm16, X86::KMOVWkm);
627   createReplacerDstCOPY(X86::MOVZX64rm16, X86::KMOVWkm);
628 
629   createReplacerDstCOPY(X86::MOVZX32rr16, X86::KMOVWkk);
630   createReplacerDstCOPY(X86::MOVZX64rr16, X86::KMOVWkk);
631 
632   if (STI->hasDQI()) {
633     createReplacerDstCOPY(X86::MOVZX16rm8, X86::KMOVBkm);
634     createReplacerDstCOPY(X86::MOVZX32rm8, X86::KMOVBkm);
635     createReplacerDstCOPY(X86::MOVZX64rm8, X86::KMOVBkm);
636 
637     createReplacerDstCOPY(X86::MOVZX16rr8, X86::KMOVBkk);
638     createReplacerDstCOPY(X86::MOVZX32rr8, X86::KMOVBkk);
639     createReplacerDstCOPY(X86::MOVZX64rr8, X86::KMOVBkk);
640   }
641 
642   auto createReplacer = [&](unsigned From, unsigned To) {
643     Converters[{MaskDomain, From}] = new InstrReplacer(From, To);
644   };
645 
646   createReplacer(X86::MOV16rm, X86::KMOVWkm);
647   createReplacer(X86::MOV16mr, X86::KMOVWmk);
648   createReplacer(X86::MOV16rr, X86::KMOVWkk);
649   createReplacer(X86::SHR16ri, X86::KSHIFTRWri);
650   createReplacer(X86::SHL16ri, X86::KSHIFTLWri);
651   createReplacer(X86::NOT16r, X86::KNOTWrr);
652   createReplacer(X86::OR16rr, X86::KORWrr);
653   createReplacer(X86::AND16rr, X86::KANDWrr);
654   createReplacer(X86::XOR16rr, X86::KXORWrr);
655 
656   if (STI->hasBWI()) {
657     createReplacer(X86::MOV32rm, X86::KMOVDkm);
658     createReplacer(X86::MOV64rm, X86::KMOVQkm);
659 
660     createReplacer(X86::MOV32mr, X86::KMOVDmk);
661     createReplacer(X86::MOV64mr, X86::KMOVQmk);
662 
663     createReplacer(X86::MOV32rr, X86::KMOVDkk);
664     createReplacer(X86::MOV64rr, X86::KMOVQkk);
665 
666     createReplacer(X86::SHR32ri, X86::KSHIFTRDri);
667     createReplacer(X86::SHR64ri, X86::KSHIFTRQri);
668 
669     createReplacer(X86::SHL32ri, X86::KSHIFTLDri);
670     createReplacer(X86::SHL64ri, X86::KSHIFTLQri);
671 
672     createReplacer(X86::ADD32rr, X86::KADDDrr);
673     createReplacer(X86::ADD64rr, X86::KADDQrr);
674 
675     createReplacer(X86::NOT32r, X86::KNOTDrr);
676     createReplacer(X86::NOT64r, X86::KNOTQrr);
677 
678     createReplacer(X86::OR32rr, X86::KORDrr);
679     createReplacer(X86::OR64rr, X86::KORQrr);
680 
681     createReplacer(X86::AND32rr, X86::KANDDrr);
682     createReplacer(X86::AND64rr, X86::KANDQrr);
683 
684     createReplacer(X86::ANDN32rr, X86::KANDNDrr);
685     createReplacer(X86::ANDN64rr, X86::KANDNQrr);
686 
687     createReplacer(X86::XOR32rr, X86::KXORDrr);
688     createReplacer(X86::XOR64rr, X86::KXORQrr);
689 
690     // TODO: KTEST is not a replacement for TEST due to flag differences. Need
691     // to prove only Z flag is used.
692     //createReplacer(X86::TEST32rr, X86::KTESTDrr);
693     //createReplacer(X86::TEST64rr, X86::KTESTQrr);
694   }
695 
696   if (STI->hasDQI()) {
697     createReplacer(X86::ADD8rr, X86::KADDBrr);
698     createReplacer(X86::ADD16rr, X86::KADDWrr);
699 
700     createReplacer(X86::AND8rr, X86::KANDBrr);
701 
702     createReplacer(X86::MOV8rm, X86::KMOVBkm);
703     createReplacer(X86::MOV8mr, X86::KMOVBmk);
704     createReplacer(X86::MOV8rr, X86::KMOVBkk);
705 
706     createReplacer(X86::NOT8r, X86::KNOTBrr);
707 
708     createReplacer(X86::OR8rr, X86::KORBrr);
709 
710     createReplacer(X86::SHR8ri, X86::KSHIFTRBri);
711     createReplacer(X86::SHL8ri, X86::KSHIFTLBri);
712 
713     // TODO: KTEST is not a replacement for TEST due to flag differences. Need
714     // to prove only Z flag is used.
715     //createReplacer(X86::TEST8rr, X86::KTESTBrr);
716     //createReplacer(X86::TEST16rr, X86::KTESTWrr);
717 
718     createReplacer(X86::XOR8rr, X86::KXORBrr);
719   }
720 }
721 
722 bool X86DomainReassignment::runOnMachineFunction(MachineFunction &MF) {
723   if (skipFunction(MF.getFunction()))
724     return false;
725   if (DisableX86DomainReassignment)
726     return false;
727 
728   LLVM_DEBUG(
729       dbgs() << "***** Machine Function before Domain Reassignment *****\n");
730   LLVM_DEBUG(MF.print(dbgs()));
731 
732   STI = &MF.getSubtarget<X86Subtarget>();
733   // GPR->K is the only transformation currently supported, bail out early if no
734   // AVX512.
735   // TODO: We're also bailing of AVX512BW isn't supported since we use VK32 and
736   // VK64 for GR32/GR64, but those aren't legal classes on KNL. If the register
737   // coalescer doesn't clean it up and we generate a spill we will crash.
738   if (!STI->hasAVX512() || !STI->hasBWI())
739     return false;
740 
741   MRI = &MF.getRegInfo();
742   assert(MRI->isSSA() && "Expected MIR to be in SSA form");
743 
744   TII = STI->getInstrInfo();
745   initConverters();
746   bool Changed = false;
747 
748   EnclosedEdges.clear();
749   EnclosedInstrs.clear();
750 
751   std::vector<Closure> Closures;
752 
753   // Go over all virtual registers and calculate a closure.
754   unsigned ClosureID = 0;
755   for (unsigned Idx = 0; Idx < MRI->getNumVirtRegs(); ++Idx) {
756     unsigned Reg = TargetRegisterInfo::index2VirtReg(Idx);
757 
758     // GPR only current source domain supported.
759     if (!isGPR(MRI->getRegClass(Reg)))
760       continue;
761 
762     // Register already in closure.
763     if (EnclosedEdges.count(Reg))
764       continue;
765 
766     // Calculate closure starting with Reg.
767     Closure C(ClosureID++, {MaskDomain});
768     buildClosure(C, Reg);
769 
770     // Collect all closures that can potentially be converted.
771     if (!C.empty() && C.isLegal(MaskDomain))
772       Closures.push_back(std::move(C));
773   }
774 
775   for (Closure &C : Closures) {
776     LLVM_DEBUG(C.dump(MRI));
777     if (isReassignmentProfitable(C, MaskDomain)) {
778       reassign(C, MaskDomain);
779       ++NumClosuresConverted;
780       Changed = true;
781     }
782   }
783 
784   DeleteContainerSeconds(Converters);
785 
786   LLVM_DEBUG(
787       dbgs() << "***** Machine Function after Domain Reassignment *****\n");
788   LLVM_DEBUG(MF.print(dbgs()));
789 
790   return Changed;
791 }
792 
793 INITIALIZE_PASS(X86DomainReassignment, "x86-domain-reassignment",
794                 "X86 Domain Reassignment Pass", false, false)
795 
796 /// Returns an instance of the Domain Reassignment pass.
797 FunctionPass *llvm::createX86DomainReassignmentPass() {
798   return new X86DomainReassignment();
799 }
800