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 
560     MachineInstr *DefMI = MRI->getVRegDef(CurReg);
561     encloseInstr(C, DefMI);
562 
563     // Add register used by the defining MI to the worklist.
564     // Do not add registers which are used in address calculation, they will be
565     // added to a different closure.
566     int OpEnd = DefMI->getNumOperands();
567     const MCInstrDesc &Desc = DefMI->getDesc();
568     int MemOp = X86II::getMemoryOperandNo(Desc.TSFlags);
569     if (MemOp != -1)
570       MemOp += X86II::getOperandBias(Desc);
571     for (int OpIdx = 0; OpIdx < OpEnd; ++OpIdx) {
572       if (OpIdx == MemOp) {
573         // skip address calculation.
574         OpIdx += (X86::AddrNumOperands - 1);
575         continue;
576       }
577       auto &Op = DefMI->getOperand(OpIdx);
578       if (!Op.isReg() || !Op.isUse())
579         continue;
580       visitRegister(C, Op.getReg(), Domain, Worklist);
581     }
582 
583     // Expand closure through register uses.
584     for (auto &UseMI : MRI->use_nodbg_instructions(CurReg)) {
585       // We would like to avoid converting closures which calculare addresses,
586       // as this should remain in GPRs.
587       if (usedAsAddr(UseMI, CurReg, TII)) {
588         C.setAllIllegal();
589         continue;
590       }
591       encloseInstr(C, &UseMI);
592 
593       for (auto &DefOp : UseMI.defs()) {
594         if (!DefOp.isReg())
595           continue;
596 
597         unsigned DefReg = DefOp.getReg();
598         if (!TargetRegisterInfo::isVirtualRegister(DefReg)) {
599           C.setAllIllegal();
600           continue;
601         }
602         visitRegister(C, DefReg, Domain, Worklist);
603       }
604     }
605   }
606 }
607 
608 void X86DomainReassignment::initConverters() {
609   Converters[{MaskDomain, TargetOpcode::PHI}] =
610       new InstrIgnore(TargetOpcode::PHI);
611 
612   Converters[{MaskDomain, TargetOpcode::IMPLICIT_DEF}] =
613       new InstrIgnore(TargetOpcode::IMPLICIT_DEF);
614 
615   Converters[{MaskDomain, TargetOpcode::INSERT_SUBREG}] =
616       new InstrReplaceWithCopy(TargetOpcode::INSERT_SUBREG, 2);
617 
618   Converters[{MaskDomain, TargetOpcode::COPY}] =
619       new InstrCOPYReplacer(TargetOpcode::COPY, MaskDomain, TargetOpcode::COPY);
620 
621   auto createReplacerDstCOPY = [&](unsigned From, unsigned To) {
622     Converters[{MaskDomain, From}] = new InstrReplacerDstCOPY(From, To);
623   };
624 
625   createReplacerDstCOPY(X86::MOVZX32rm16, X86::KMOVWkm);
626   createReplacerDstCOPY(X86::MOVZX64rm16, X86::KMOVWkm);
627 
628   createReplacerDstCOPY(X86::MOVZX32rr16, X86::KMOVWkk);
629   createReplacerDstCOPY(X86::MOVZX64rr16, X86::KMOVWkk);
630 
631   if (STI->hasDQI()) {
632     createReplacerDstCOPY(X86::MOVZX16rm8, X86::KMOVBkm);
633     createReplacerDstCOPY(X86::MOVZX32rm8, X86::KMOVBkm);
634     createReplacerDstCOPY(X86::MOVZX64rm8, X86::KMOVBkm);
635 
636     createReplacerDstCOPY(X86::MOVZX16rr8, X86::KMOVBkk);
637     createReplacerDstCOPY(X86::MOVZX32rr8, X86::KMOVBkk);
638     createReplacerDstCOPY(X86::MOVZX64rr8, X86::KMOVBkk);
639   }
640 
641   auto createReplacer = [&](unsigned From, unsigned To) {
642     Converters[{MaskDomain, From}] = new InstrReplacer(From, To);
643   };
644 
645   createReplacer(X86::MOV16rm, X86::KMOVWkm);
646   createReplacer(X86::MOV16mr, X86::KMOVWmk);
647   createReplacer(X86::MOV16rr, X86::KMOVWkk);
648   createReplacer(X86::SHR16ri, X86::KSHIFTRWri);
649   createReplacer(X86::SHL16ri, X86::KSHIFTLWri);
650   createReplacer(X86::NOT16r, X86::KNOTWrr);
651   createReplacer(X86::OR16rr, X86::KORWrr);
652   createReplacer(X86::AND16rr, X86::KANDWrr);
653   createReplacer(X86::XOR16rr, X86::KXORWrr);
654 
655   if (STI->hasBWI()) {
656     createReplacer(X86::MOV32rm, X86::KMOVDkm);
657     createReplacer(X86::MOV64rm, X86::KMOVQkm);
658 
659     createReplacer(X86::MOV32mr, X86::KMOVDmk);
660     createReplacer(X86::MOV64mr, X86::KMOVQmk);
661 
662     createReplacer(X86::MOV32rr, X86::KMOVDkk);
663     createReplacer(X86::MOV64rr, X86::KMOVQkk);
664 
665     createReplacer(X86::SHR32ri, X86::KSHIFTRDri);
666     createReplacer(X86::SHR64ri, X86::KSHIFTRQri);
667 
668     createReplacer(X86::SHL32ri, X86::KSHIFTLDri);
669     createReplacer(X86::SHL64ri, X86::KSHIFTLQri);
670 
671     createReplacer(X86::ADD32rr, X86::KADDDrr);
672     createReplacer(X86::ADD64rr, X86::KADDQrr);
673 
674     createReplacer(X86::NOT32r, X86::KNOTDrr);
675     createReplacer(X86::NOT64r, X86::KNOTQrr);
676 
677     createReplacer(X86::OR32rr, X86::KORDrr);
678     createReplacer(X86::OR64rr, X86::KORQrr);
679 
680     createReplacer(X86::AND32rr, X86::KANDDrr);
681     createReplacer(X86::AND64rr, X86::KANDQrr);
682 
683     createReplacer(X86::ANDN32rr, X86::KANDNDrr);
684     createReplacer(X86::ANDN64rr, X86::KANDNQrr);
685 
686     createReplacer(X86::XOR32rr, X86::KXORDrr);
687     createReplacer(X86::XOR64rr, X86::KXORQrr);
688 
689     // TODO: KTEST is not a replacement for TEST due to flag differences. Need
690     // to prove only Z flag is used.
691     //createReplacer(X86::TEST32rr, X86::KTESTDrr);
692     //createReplacer(X86::TEST64rr, X86::KTESTQrr);
693   }
694 
695   if (STI->hasDQI()) {
696     createReplacer(X86::ADD8rr, X86::KADDBrr);
697     createReplacer(X86::ADD16rr, X86::KADDWrr);
698 
699     createReplacer(X86::AND8rr, X86::KANDBrr);
700 
701     createReplacer(X86::MOV8rm, X86::KMOVBkm);
702     createReplacer(X86::MOV8mr, X86::KMOVBmk);
703     createReplacer(X86::MOV8rr, X86::KMOVBkk);
704 
705     createReplacer(X86::NOT8r, X86::KNOTBrr);
706 
707     createReplacer(X86::OR8rr, X86::KORBrr);
708 
709     createReplacer(X86::SHR8ri, X86::KSHIFTRBri);
710     createReplacer(X86::SHL8ri, X86::KSHIFTLBri);
711 
712     // TODO: KTEST is not a replacement for TEST due to flag differences. Need
713     // to prove only Z flag is used.
714     //createReplacer(X86::TEST8rr, X86::KTESTBrr);
715     //createReplacer(X86::TEST16rr, X86::KTESTWrr);
716 
717     createReplacer(X86::XOR8rr, X86::KXORBrr);
718   }
719 }
720 
721 bool X86DomainReassignment::runOnMachineFunction(MachineFunction &MF) {
722   if (skipFunction(MF.getFunction()))
723     return false;
724   if (DisableX86DomainReassignment)
725     return false;
726 
727   LLVM_DEBUG(
728       dbgs() << "***** Machine Function before Domain Reassignment *****\n");
729   LLVM_DEBUG(MF.print(dbgs()));
730 
731   STI = &MF.getSubtarget<X86Subtarget>();
732   // GPR->K is the only transformation currently supported, bail out early if no
733   // AVX512.
734   // TODO: We're also bailing of AVX512BW isn't supported since we use VK32 and
735   // VK64 for GR32/GR64, but those aren't legal classes on KNL. If the register
736   // coalescer doesn't clean it up and we generate a spill we will crash.
737   if (!STI->hasAVX512() || !STI->hasBWI())
738     return false;
739 
740   MRI = &MF.getRegInfo();
741   assert(MRI->isSSA() && "Expected MIR to be in SSA form");
742 
743   TII = STI->getInstrInfo();
744   initConverters();
745   bool Changed = false;
746 
747   EnclosedEdges.clear();
748   EnclosedInstrs.clear();
749 
750   std::vector<Closure> Closures;
751 
752   // Go over all virtual registers and calculate a closure.
753   unsigned ClosureID = 0;
754   for (unsigned Idx = 0; Idx < MRI->getNumVirtRegs(); ++Idx) {
755     unsigned Reg = TargetRegisterInfo::index2VirtReg(Idx);
756 
757     // GPR only current source domain supported.
758     if (!isGPR(MRI->getRegClass(Reg)))
759       continue;
760 
761     // Register already in closure.
762     if (EnclosedEdges.count(Reg))
763       continue;
764 
765     // Calculate closure starting with Reg.
766     Closure C(ClosureID++, {MaskDomain});
767     buildClosure(C, Reg);
768 
769     // Collect all closures that can potentially be converted.
770     if (!C.empty() && C.isLegal(MaskDomain))
771       Closures.push_back(std::move(C));
772   }
773 
774   for (Closure &C : Closures) {
775     LLVM_DEBUG(C.dump(MRI));
776     if (isReassignmentProfitable(C, MaskDomain)) {
777       reassign(C, MaskDomain);
778       ++NumClosuresConverted;
779       Changed = true;
780     }
781   }
782 
783   DeleteContainerSeconds(Converters);
784 
785   LLVM_DEBUG(
786       dbgs() << "***** Machine Function after Domain Reassignment *****\n");
787   LLVM_DEBUG(MF.print(dbgs()));
788 
789   return Changed;
790 }
791 
792 INITIALIZE_PASS(X86DomainReassignment, "x86-domain-reassignment",
793                 "X86 Domain Reassignment Pass", false, false)
794 
795 /// Returns an instance of the Domain Reassignment pass.
796 FunctionPass *llvm::createX86DomainReassignmentPass() {
797   return new X86DomainReassignment();
798 }
799