1 //===------- HexagonCopyToCombine.cpp - Hexagon Copy-To-Combine Pass ------===//
2 //
3 //                     The LLVM Compiler Infrastructure
4 //
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
7 //
8 //===----------------------------------------------------------------------===//
9 // This pass replaces transfer instructions by combine instructions.
10 // We walk along a basic block and look for two combinable instructions and try
11 // to move them together. If we can move them next to each other we do so and
12 // replace them with a combine instruction.
13 //===----------------------------------------------------------------------===//
14 #include "HexagonInstrInfo.h"
15 #include "HexagonSubtarget.h"
16 #include "llvm/PassSupport.h"
17 #include "llvm/ADT/DenseMap.h"
18 #include "llvm/ADT/DenseSet.h"
19 #include "llvm/CodeGen/MachineBasicBlock.h"
20 #include "llvm/CodeGen/MachineFunction.h"
21 #include "llvm/CodeGen/MachineFunctionPass.h"
22 #include "llvm/CodeGen/MachineInstr.h"
23 #include "llvm/CodeGen/MachineInstrBuilder.h"
24 #include "llvm/CodeGen/Passes.h"
25 #include "llvm/Support/CodeGen.h"
26 #include "llvm/Support/CommandLine.h"
27 #include "llvm/Support/Debug.h"
28 #include "llvm/Support/raw_ostream.h"
29 #include "llvm/Target/TargetRegisterInfo.h"
30 
31 using namespace llvm;
32 
33 #define DEBUG_TYPE "hexagon-copy-combine"
34 
35 static
36 cl::opt<bool> IsCombinesDisabled("disable-merge-into-combines",
37                                  cl::Hidden, cl::ZeroOrMore,
38                                  cl::init(false),
39                                  cl::desc("Disable merging into combines"));
40 static
41 cl::opt<bool> IsConst64Disabled("disable-const64",
42                                  cl::Hidden, cl::ZeroOrMore,
43                                  cl::init(false),
44                                  cl::desc("Disable generation of const64"));
45 static
46 cl::opt<unsigned>
47 MaxNumOfInstsBetweenNewValueStoreAndTFR("max-num-inst-between-tfr-and-nv-store",
48                    cl::Hidden, cl::init(4),
49                    cl::desc("Maximum distance between a tfr feeding a store we "
50                             "consider the store still to be newifiable"));
51 
52 namespace llvm {
53   FunctionPass *createHexagonCopyToCombine();
54   void initializeHexagonCopyToCombinePass(PassRegistry&);
55 }
56 
57 
58 namespace {
59 
60 class HexagonCopyToCombine : public MachineFunctionPass  {
61   const HexagonInstrInfo *TII;
62   const TargetRegisterInfo *TRI;
63   const HexagonSubtarget *ST;
64   bool ShouldCombineAggressively;
65 
66   DenseSet<MachineInstr *> PotentiallyNewifiableTFR;
67   SmallVector<MachineInstr *, 8> DbgMItoMove;
68 
69 public:
70   static char ID;
71 
72   HexagonCopyToCombine() : MachineFunctionPass(ID) {
73     initializeHexagonCopyToCombinePass(*PassRegistry::getPassRegistry());
74   }
75 
76   void getAnalysisUsage(AnalysisUsage &AU) const override {
77     MachineFunctionPass::getAnalysisUsage(AU);
78   }
79 
80   StringRef getPassName() const override {
81     return "Hexagon Copy-To-Combine Pass";
82   }
83 
84   bool runOnMachineFunction(MachineFunction &Fn) override;
85 
86   MachineFunctionProperties getRequiredProperties() const override {
87     return MachineFunctionProperties().set(
88         MachineFunctionProperties::Property::NoVRegs);
89   }
90 
91 private:
92   MachineInstr *findPairable(MachineInstr &I1, bool &DoInsertAtI1,
93                              bool AllowC64);
94 
95   void findPotentialNewifiableTFRs(MachineBasicBlock &);
96 
97   void combine(MachineInstr &I1, MachineInstr &I2,
98                MachineBasicBlock::iterator &MI, bool DoInsertAtI1,
99                bool OptForSize);
100 
101   bool isSafeToMoveTogether(MachineInstr &I1, MachineInstr &I2,
102                             unsigned I1DestReg, unsigned I2DestReg,
103                             bool &DoInsertAtI1);
104 
105   void emitCombineRR(MachineBasicBlock::iterator &Before, unsigned DestReg,
106                      MachineOperand &HiOperand, MachineOperand &LoOperand);
107 
108   void emitCombineRI(MachineBasicBlock::iterator &Before, unsigned DestReg,
109                      MachineOperand &HiOperand, MachineOperand &LoOperand);
110 
111   void emitCombineIR(MachineBasicBlock::iterator &Before, unsigned DestReg,
112                      MachineOperand &HiOperand, MachineOperand &LoOperand);
113 
114   void emitCombineII(MachineBasicBlock::iterator &Before, unsigned DestReg,
115                      MachineOperand &HiOperand, MachineOperand &LoOperand);
116 
117   void emitConst64(MachineBasicBlock::iterator &Before, unsigned DestReg,
118                    MachineOperand &HiOperand, MachineOperand &LoOperand);
119 };
120 
121 } // End anonymous namespace.
122 
123 char HexagonCopyToCombine::ID = 0;
124 
125 INITIALIZE_PASS(HexagonCopyToCombine, "hexagon-copy-combine",
126                 "Hexagon Copy-To-Combine Pass", false, false)
127 
128 static bool isCombinableInstType(MachineInstr &MI, const HexagonInstrInfo *TII,
129                                  bool ShouldCombineAggressively) {
130   switch (MI.getOpcode()) {
131   case Hexagon::A2_tfr: {
132     // A COPY instruction can be combined if its arguments are IntRegs (32bit).
133     const MachineOperand &Op0 = MI.getOperand(0);
134     const MachineOperand &Op1 = MI.getOperand(1);
135     assert(Op0.isReg() && Op1.isReg());
136 
137     unsigned DestReg = Op0.getReg();
138     unsigned SrcReg = Op1.getReg();
139     return Hexagon::IntRegsRegClass.contains(DestReg) &&
140            Hexagon::IntRegsRegClass.contains(SrcReg);
141   }
142 
143   case Hexagon::A2_tfrsi: {
144     // A transfer-immediate can be combined if its argument is a signed 8bit
145     // value.
146     const MachineOperand &Op0 = MI.getOperand(0);
147     const MachineOperand &Op1 = MI.getOperand(1);
148     assert(Op0.isReg());
149 
150     unsigned DestReg = Op0.getReg();
151     // Ensure that TargetFlags are MO_NO_FLAG for a global. This is a
152     // workaround for an ABI bug that prevents GOT relocations on combine
153     // instructions
154     if (!Op1.isImm() && Op1.getTargetFlags() != HexagonII::MO_NO_FLAG)
155       return false;
156 
157     // Only combine constant extended A2_tfrsi if we are in aggressive mode.
158     bool NotExt = Op1.isImm() && isInt<8>(Op1.getImm());
159     return Hexagon::IntRegsRegClass.contains(DestReg) &&
160            (ShouldCombineAggressively || NotExt);
161   }
162 
163   case Hexagon::V6_vassign:
164   case Hexagon::V6_vassign_128B:
165     return true;
166 
167   default:
168     break;
169   }
170 
171   return false;
172 }
173 
174 template <unsigned N> static bool isGreaterThanNBitTFRI(const MachineInstr &I) {
175   if (I.getOpcode() == Hexagon::TFRI64_V4 ||
176       I.getOpcode() == Hexagon::A2_tfrsi) {
177     const MachineOperand &Op = I.getOperand(1);
178     return !Op.isImm() || !isInt<N>(Op.getImm());
179   }
180   return false;
181 }
182 
183 /// areCombinableOperations - Returns true if the two instruction can be merge
184 /// into a combine (ignoring register constraints).
185 static bool areCombinableOperations(const TargetRegisterInfo *TRI,
186                                     MachineInstr &HighRegInst,
187                                     MachineInstr &LowRegInst, bool AllowC64) {
188   unsigned HiOpc = HighRegInst.getOpcode();
189   unsigned LoOpc = LowRegInst.getOpcode();
190 
191   auto verifyOpc = [](unsigned Opc) -> void {
192     switch (Opc) {
193       case Hexagon::A2_tfr:
194       case Hexagon::A2_tfrsi:
195       case Hexagon::V6_vassign:
196         break;
197       default:
198         llvm_unreachable("Unexpected opcode");
199     }
200   };
201   verifyOpc(HiOpc);
202   verifyOpc(LoOpc);
203 
204   if (HiOpc == Hexagon::V6_vassign || LoOpc == Hexagon::V6_vassign)
205     return HiOpc == LoOpc;
206 
207   if (!AllowC64) {
208     // There is no combine of two constant extended values.
209     if (isGreaterThanNBitTFRI<8>(HighRegInst) &&
210         isGreaterThanNBitTFRI<6>(LowRegInst))
211       return false;
212   }
213 
214   // There is a combine of two constant extended values into CONST64,
215   // provided both constants are true immediates.
216   if (isGreaterThanNBitTFRI<16>(HighRegInst) &&
217       isGreaterThanNBitTFRI<16>(LowRegInst))
218     return (HighRegInst.getOperand(1).isImm() &&
219             LowRegInst.getOperand(1).isImm());
220 
221   // There is no combine of two constant extended values, unless handled above
222   // Make both 8-bit size checks to allow both combine (#,##) and combine(##,#)
223   if (isGreaterThanNBitTFRI<8>(HighRegInst) &&
224       isGreaterThanNBitTFRI<8>(LowRegInst))
225     return false;
226 
227   return true;
228 }
229 
230 static bool isEvenReg(unsigned Reg) {
231   assert(TargetRegisterInfo::isPhysicalRegister(Reg));
232   if (Hexagon::IntRegsRegClass.contains(Reg))
233     return (Reg - Hexagon::R0) % 2 == 0;
234   if (Hexagon::VectorRegsRegClass.contains(Reg) ||
235       Hexagon::VectorRegs128BRegClass.contains(Reg))
236     return (Reg - Hexagon::V0) % 2 == 0;
237   llvm_unreachable("Invalid register");
238 }
239 
240 static void removeKillInfo(MachineInstr &MI, unsigned RegNotKilled) {
241   for (unsigned I = 0, E = MI.getNumOperands(); I != E; ++I) {
242     MachineOperand &Op = MI.getOperand(I);
243     if (!Op.isReg() || Op.getReg() != RegNotKilled || !Op.isKill())
244       continue;
245     Op.setIsKill(false);
246   }
247 }
248 
249 /// Returns true if it is unsafe to move a copy instruction from \p UseReg to
250 /// \p DestReg over the instruction \p MI.
251 static bool isUnsafeToMoveAcross(MachineInstr &MI, unsigned UseReg,
252                                  unsigned DestReg,
253                                  const TargetRegisterInfo *TRI) {
254   return (UseReg && (MI.modifiesRegister(UseReg, TRI))) ||
255          MI.modifiesRegister(DestReg, TRI) || MI.readsRegister(DestReg, TRI) ||
256          MI.hasUnmodeledSideEffects() || MI.isInlineAsm() || MI.isDebugValue();
257 }
258 
259 static unsigned UseReg(const MachineOperand& MO) {
260   return MO.isReg() ? MO.getReg() : 0;
261 }
262 
263 /// isSafeToMoveTogether - Returns true if it is safe to move I1 next to I2 such
264 /// that the two instructions can be paired in a combine.
265 bool HexagonCopyToCombine::isSafeToMoveTogether(MachineInstr &I1,
266                                                 MachineInstr &I2,
267                                                 unsigned I1DestReg,
268                                                 unsigned I2DestReg,
269                                                 bool &DoInsertAtI1) {
270   unsigned I2UseReg = UseReg(I2.getOperand(1));
271 
272   // It is not safe to move I1 and I2 into one combine if I2 has a true
273   // dependence on I1.
274   if (I2UseReg && I1.modifiesRegister(I2UseReg, TRI))
275     return false;
276 
277   bool isSafe = true;
278 
279   // First try to move I2 towards I1.
280   {
281     // A reverse_iterator instantiated like below starts before I2, and I1
282     // respectively.
283     // Look at instructions I in between I2 and (excluding) I1.
284     MachineBasicBlock::reverse_iterator I(I2),
285       End = --(MachineBasicBlock::reverse_iterator(I1));
286     // At 03 we got better results (dhrystone!) by being more conservative.
287     if (!ShouldCombineAggressively)
288       End = MachineBasicBlock::reverse_iterator(I1);
289     // If I2 kills its operand and we move I2 over an instruction that also
290     // uses I2's use reg we need to modify that (first) instruction to now kill
291     // this reg.
292     unsigned KilledOperand = 0;
293     if (I2.killsRegister(I2UseReg))
294       KilledOperand = I2UseReg;
295     MachineInstr *KillingInstr = nullptr;
296 
297     for (; I != End; ++I) {
298       // If the intervening instruction I:
299       //   * modifies I2's use reg
300       //   * modifies I2's def reg
301       //   * reads I2's def reg
302       //   * or has unmodelled side effects
303       // we can't move I2 across it.
304       if (I->isDebugValue())
305         continue;
306 
307       if (isUnsafeToMoveAcross(*I, I2UseReg, I2DestReg, TRI)) {
308         isSafe = false;
309         break;
310       }
311 
312       // Update first use of the killed operand.
313       if (!KillingInstr && KilledOperand &&
314           I->readsRegister(KilledOperand, TRI))
315         KillingInstr = &*I;
316     }
317     if (isSafe) {
318       // Update the intermediate instruction to with the kill flag.
319       if (KillingInstr) {
320         bool Added = KillingInstr->addRegisterKilled(KilledOperand, TRI, true);
321         (void)Added; // suppress compiler warning
322         assert(Added && "Must successfully update kill flag");
323         removeKillInfo(I2, KilledOperand);
324       }
325       DoInsertAtI1 = true;
326       return true;
327     }
328   }
329 
330   // Try to move I1 towards I2.
331   {
332     // Look at instructions I in between I1 and (excluding) I2.
333     MachineBasicBlock::iterator I(I1), End(I2);
334     // At O3 we got better results (dhrystone) by being more conservative here.
335     if (!ShouldCombineAggressively)
336       End = std::next(MachineBasicBlock::iterator(I2));
337     unsigned I1UseReg = UseReg(I1.getOperand(1));
338     // Track killed operands. If we move across an instruction that kills our
339     // operand, we need to update the kill information on the moved I1. It kills
340     // the operand now.
341     MachineInstr *KillingInstr = nullptr;
342     unsigned KilledOperand = 0;
343 
344     while(++I != End) {
345       MachineInstr &MI = *I;
346       // If the intervening instruction MI:
347       //   * modifies I1's use reg
348       //   * modifies I1's def reg
349       //   * reads I1's def reg
350       //   * or has unmodelled side effects
351       //   We introduce this special case because llvm has no api to remove a
352       //   kill flag for a register (a removeRegisterKilled() analogous to
353       //   addRegisterKilled) that handles aliased register correctly.
354       //   * or has a killed aliased register use of I1's use reg
355       //           %D4<def> = A2_tfrpi 16
356       //           %R6<def> = A2_tfr %R9
357       //           %R8<def> = KILL %R8, %D4<imp-use,kill>
358       //      If we want to move R6 = across the KILL instruction we would have
359       //      to remove the %D4<imp-use,kill> operand. For now, we are
360       //      conservative and disallow the move.
361       // we can't move I1 across it.
362       if (MI.isDebugValue()) {
363         if (MI.readsRegister(I1DestReg, TRI)) // Move this instruction after I2.
364           DbgMItoMove.push_back(&MI);
365         continue;
366       }
367 
368       if (isUnsafeToMoveAcross(MI, I1UseReg, I1DestReg, TRI) ||
369           // Check for an aliased register kill. Bail out if we see one.
370           (!MI.killsRegister(I1UseReg) && MI.killsRegister(I1UseReg, TRI)))
371         return false;
372 
373       // Check for an exact kill (registers match).
374       if (I1UseReg && MI.killsRegister(I1UseReg)) {
375         assert(!KillingInstr && "Should only see one killing instruction");
376         KilledOperand = I1UseReg;
377         KillingInstr = &MI;
378       }
379     }
380     if (KillingInstr) {
381       removeKillInfo(*KillingInstr, KilledOperand);
382       // Update I1 to set the kill flag. This flag will later be picked up by
383       // the new COMBINE instruction.
384       bool Added = I1.addRegisterKilled(KilledOperand, TRI);
385       (void)Added; // suppress compiler warning
386       assert(Added && "Must successfully update kill flag");
387     }
388     DoInsertAtI1 = false;
389   }
390 
391   return true;
392 }
393 
394 /// findPotentialNewifiableTFRs - Finds tranfers that feed stores that could be
395 /// newified. (A use of a 64 bit register define can not be newified)
396 void
397 HexagonCopyToCombine::findPotentialNewifiableTFRs(MachineBasicBlock &BB) {
398   DenseMap<unsigned, MachineInstr *> LastDef;
399   for (MachineInstr &MI : BB) {
400     if (MI.isDebugValue())
401       continue;
402 
403     // Mark TFRs that feed a potential new value store as such.
404     if (TII->mayBeNewStore(MI)) {
405       // Look for uses of TFR instructions.
406       for (unsigned OpdIdx = 0, OpdE = MI.getNumOperands(); OpdIdx != OpdE;
407            ++OpdIdx) {
408         MachineOperand &Op = MI.getOperand(OpdIdx);
409 
410         // Skip over anything except register uses.
411         if (!Op.isReg() || !Op.isUse() || !Op.getReg())
412           continue;
413 
414         // Look for the defining instruction.
415         unsigned Reg = Op.getReg();
416         MachineInstr *DefInst = LastDef[Reg];
417         if (!DefInst)
418           continue;
419         if (!isCombinableInstType(*DefInst, TII, ShouldCombineAggressively))
420           continue;
421 
422         // Only close newifiable stores should influence the decision.
423         // Ignore the debug instructions in between.
424         MachineBasicBlock::iterator It(DefInst);
425         unsigned NumInstsToDef = 0;
426         while (&*It != &MI) {
427           if (!It->isDebugValue())
428             ++NumInstsToDef;
429           ++It;
430         }
431 
432         if (NumInstsToDef > MaxNumOfInstsBetweenNewValueStoreAndTFR)
433           continue;
434 
435         PotentiallyNewifiableTFR.insert(DefInst);
436       }
437       // Skip to next instruction.
438       continue;
439     }
440 
441     // Put instructions that last defined integer or double registers into the
442     // map.
443     for (MachineOperand &Op : MI.operands()) {
444       if (Op.isReg()) {
445         if (!Op.isDef() || !Op.getReg())
446           continue;
447         unsigned Reg = Op.getReg();
448         if (Hexagon::DoubleRegsRegClass.contains(Reg)) {
449           for (MCSubRegIterator SubRegs(Reg, TRI); SubRegs.isValid(); ++SubRegs)
450             LastDef[*SubRegs] = &MI;
451         } else if (Hexagon::IntRegsRegClass.contains(Reg))
452           LastDef[Reg] = &MI;
453       } else if (Op.isRegMask()) {
454         for (unsigned Reg : Hexagon::IntRegsRegClass)
455           if (Op.clobbersPhysReg(Reg))
456             LastDef[Reg] = &MI;
457       }
458     }
459   }
460 }
461 
462 bool HexagonCopyToCombine::runOnMachineFunction(MachineFunction &MF) {
463 
464   if (IsCombinesDisabled) return false;
465 
466   bool HasChanged = false;
467 
468   // Get target info.
469   ST = &MF.getSubtarget<HexagonSubtarget>();
470   TRI = ST->getRegisterInfo();
471   TII = ST->getInstrInfo();
472 
473   const Function *F = MF.getFunction();
474   bool OptForSize = F->hasFnAttribute(Attribute::OptimizeForSize);
475 
476   // Combine aggressively (for code size)
477   ShouldCombineAggressively =
478     MF.getTarget().getOptLevel() <= CodeGenOpt::Default;
479 
480   // Traverse basic blocks.
481   for (MachineFunction::iterator BI = MF.begin(), BE = MF.end(); BI != BE;
482        ++BI) {
483     PotentiallyNewifiableTFR.clear();
484     findPotentialNewifiableTFRs(*BI);
485 
486     // Traverse instructions in basic block.
487     for(MachineBasicBlock::iterator MI = BI->begin(), End = BI->end();
488         MI != End;) {
489       MachineInstr &I1 = *MI++;
490 
491       if (I1.isDebugValue())
492         continue;
493 
494       // Don't combine a TFR whose user could be newified (instructions that
495       // define double registers can not be newified - Programmer's Ref Manual
496       // 5.4.2 New-value stores).
497       if (ShouldCombineAggressively && PotentiallyNewifiableTFR.count(&I1))
498         continue;
499 
500       // Ignore instructions that are not combinable.
501       if (!isCombinableInstType(I1, TII, ShouldCombineAggressively))
502         continue;
503 
504       // Find a second instruction that can be merged into a combine
505       // instruction. In addition, also find all the debug instructions that
506       // need to be moved along with it.
507       bool DoInsertAtI1 = false;
508       DbgMItoMove.clear();
509       MachineInstr *I2 = findPairable(I1, DoInsertAtI1, OptForSize);
510       if (I2) {
511         HasChanged = true;
512         combine(I1, *I2, MI, DoInsertAtI1, OptForSize);
513       }
514     }
515   }
516 
517   return HasChanged;
518 }
519 
520 /// findPairable - Returns an instruction that can be merged with \p I1 into a
521 /// COMBINE instruction or 0 if no such instruction can be found. Returns true
522 /// in \p DoInsertAtI1 if the combine must be inserted at instruction \p I1
523 /// false if the combine must be inserted at the returned instruction.
524 MachineInstr *HexagonCopyToCombine::findPairable(MachineInstr &I1,
525                                                  bool &DoInsertAtI1,
526                                                  bool AllowC64) {
527   MachineBasicBlock::iterator I2 = std::next(MachineBasicBlock::iterator(I1));
528   while (I2 != I1.getParent()->end() && I2->isDebugValue())
529     ++I2;
530 
531   unsigned I1DestReg = I1.getOperand(0).getReg();
532 
533   for (MachineBasicBlock::iterator End = I1.getParent()->end(); I2 != End;
534        ++I2) {
535     // Bail out early if we see a second definition of I1DestReg.
536     if (I2->modifiesRegister(I1DestReg, TRI))
537       break;
538 
539     // Ignore non-combinable instructions.
540     if (!isCombinableInstType(*I2, TII, ShouldCombineAggressively))
541       continue;
542 
543     // Don't combine a TFR whose user could be newified.
544     if (ShouldCombineAggressively && PotentiallyNewifiableTFR.count(&*I2))
545       continue;
546 
547     unsigned I2DestReg = I2->getOperand(0).getReg();
548 
549     // Check that registers are adjacent and that the first destination register
550     // is even.
551     bool IsI1LowReg = (I2DestReg - I1DestReg) == 1;
552     bool IsI2LowReg = (I1DestReg - I2DestReg) == 1;
553     unsigned FirstRegIndex = IsI1LowReg ? I1DestReg : I2DestReg;
554     if ((!IsI1LowReg && !IsI2LowReg) || !isEvenReg(FirstRegIndex))
555       continue;
556 
557     // Check that the two instructions are combinable. V4 allows more
558     // instructions to be merged into a combine.
559     // The order matters because in a A2_tfrsi we might can encode a int8 as
560     // the hi reg operand but only a uint6 as the low reg operand.
561     if ((IsI2LowReg && !areCombinableOperations(TRI, I1, *I2, AllowC64)) ||
562         (IsI1LowReg && !areCombinableOperations(TRI, *I2, I1, AllowC64)))
563       break;
564 
565     if (isSafeToMoveTogether(I1, *I2, I1DestReg, I2DestReg, DoInsertAtI1))
566       return &*I2;
567 
568     // Not safe. Stop searching.
569     break;
570   }
571   return nullptr;
572 }
573 
574 void HexagonCopyToCombine::combine(MachineInstr &I1, MachineInstr &I2,
575                                    MachineBasicBlock::iterator &MI,
576                                    bool DoInsertAtI1, bool OptForSize) {
577   // We are going to delete I2. If MI points to I2 advance it to the next
578   // instruction.
579   if (MI == I2.getIterator())
580     ++MI;
581 
582   // Figure out whether I1 or I2 goes into the lowreg part.
583   unsigned I1DestReg = I1.getOperand(0).getReg();
584   unsigned I2DestReg = I2.getOperand(0).getReg();
585   bool IsI1Loreg = (I2DestReg - I1DestReg) == 1;
586   unsigned LoRegDef = IsI1Loreg ? I1DestReg : I2DestReg;
587   unsigned SubLo;
588 
589   const TargetRegisterClass *SuperRC = nullptr;
590   if (Hexagon::IntRegsRegClass.contains(LoRegDef)) {
591     SuperRC = &Hexagon::DoubleRegsRegClass;
592     SubLo = Hexagon::isub_lo;
593   } else if (Hexagon::VectorRegsRegClass.contains(LoRegDef)) {
594     assert(ST->useHVXOps());
595     if (ST->useHVXSglOps())
596       SuperRC = &Hexagon::VecDblRegsRegClass;
597     else
598       SuperRC = &Hexagon::VecDblRegs128BRegClass;
599     SubLo = Hexagon::vsub_lo;
600   } else
601     llvm_unreachable("Unexpected register class");
602 
603   // Get the double word register.
604   unsigned DoubleRegDest = TRI->getMatchingSuperReg(LoRegDef, SubLo, SuperRC);
605   assert(DoubleRegDest != 0 && "Expect a valid register");
606 
607   // Setup source operands.
608   MachineOperand &LoOperand = IsI1Loreg ? I1.getOperand(1) : I2.getOperand(1);
609   MachineOperand &HiOperand = IsI1Loreg ? I2.getOperand(1) : I1.getOperand(1);
610 
611   // Figure out which source is a register and which a constant.
612   bool IsHiReg = HiOperand.isReg();
613   bool IsLoReg = LoOperand.isReg();
614 
615   // There is a combine of two constant extended values into CONST64.
616   bool IsC64 = OptForSize && LoOperand.isImm() && HiOperand.isImm() &&
617                isGreaterThanNBitTFRI<16>(I1) && isGreaterThanNBitTFRI<16>(I2);
618 
619   MachineBasicBlock::iterator InsertPt(DoInsertAtI1 ? I1 : I2);
620   // Emit combine.
621   if (IsHiReg && IsLoReg)
622     emitCombineRR(InsertPt, DoubleRegDest, HiOperand, LoOperand);
623   else if (IsHiReg)
624     emitCombineRI(InsertPt, DoubleRegDest, HiOperand, LoOperand);
625   else if (IsLoReg)
626     emitCombineIR(InsertPt, DoubleRegDest, HiOperand, LoOperand);
627   else if (IsC64 && !IsConst64Disabled)
628     emitConst64(InsertPt, DoubleRegDest, HiOperand, LoOperand);
629   else
630     emitCombineII(InsertPt, DoubleRegDest, HiOperand, LoOperand);
631 
632   // Move debug instructions along with I1 if it's being
633   // moved towards I2.
634   if (!DoInsertAtI1 && DbgMItoMove.size() != 0) {
635     // Insert debug instructions at the new location before I2.
636     MachineBasicBlock *BB = InsertPt->getParent();
637     for (auto NewMI : DbgMItoMove) {
638       // If iterator MI is pointing to DEBUG_VAL, make sure
639       // MI now points to next relevant instruction.
640       if (NewMI == MI)
641         ++MI;
642       BB->splice(InsertPt, BB, NewMI);
643     }
644   }
645 
646   I1.eraseFromParent();
647   I2.eraseFromParent();
648 }
649 
650 void HexagonCopyToCombine::emitConst64(MachineBasicBlock::iterator &InsertPt,
651                                        unsigned DoubleDestReg,
652                                        MachineOperand &HiOperand,
653                                        MachineOperand &LoOperand) {
654   DEBUG(dbgs() << "Found a CONST64\n");
655 
656   DebugLoc DL = InsertPt->getDebugLoc();
657   MachineBasicBlock *BB = InsertPt->getParent();
658   assert(LoOperand.isImm() && HiOperand.isImm() &&
659          "Both operands must be immediate");
660 
661   int64_t V = HiOperand.getImm();
662   V = (V << 32) | (0x0ffffffffLL & LoOperand.getImm());
663   BuildMI(*BB, InsertPt, DL, TII->get(Hexagon::CONST64), DoubleDestReg)
664     .addImm(V);
665 }
666 
667 void HexagonCopyToCombine::emitCombineII(MachineBasicBlock::iterator &InsertPt,
668                                          unsigned DoubleDestReg,
669                                          MachineOperand &HiOperand,
670                                          MachineOperand &LoOperand) {
671   DebugLoc DL = InsertPt->getDebugLoc();
672   MachineBasicBlock *BB = InsertPt->getParent();
673 
674   // Handle globals.
675   if (HiOperand.isGlobal()) {
676     BuildMI(*BB, InsertPt, DL, TII->get(Hexagon::A2_combineii), DoubleDestReg)
677       .addGlobalAddress(HiOperand.getGlobal(), HiOperand.getOffset(),
678                         HiOperand.getTargetFlags())
679       .addImm(LoOperand.getImm());
680     return;
681   }
682   if (LoOperand.isGlobal()) {
683     BuildMI(*BB, InsertPt, DL, TII->get(Hexagon::A4_combineii), DoubleDestReg)
684       .addImm(HiOperand.getImm())
685       .addGlobalAddress(LoOperand.getGlobal(), LoOperand.getOffset(),
686                         LoOperand.getTargetFlags());
687     return;
688   }
689 
690   // Handle block addresses.
691   if (HiOperand.isBlockAddress()) {
692     BuildMI(*BB, InsertPt, DL, TII->get(Hexagon::A2_combineii), DoubleDestReg)
693       .addBlockAddress(HiOperand.getBlockAddress(), HiOperand.getOffset(),
694                        HiOperand.getTargetFlags())
695       .addImm(LoOperand.getImm());
696     return;
697   }
698   if (LoOperand.isBlockAddress()) {
699     BuildMI(*BB, InsertPt, DL, TII->get(Hexagon::A4_combineii), DoubleDestReg)
700       .addImm(HiOperand.getImm())
701       .addBlockAddress(LoOperand.getBlockAddress(), LoOperand.getOffset(),
702                        LoOperand.getTargetFlags());
703     return;
704   }
705 
706   // Handle jump tables.
707   if (HiOperand.isJTI()) {
708     BuildMI(*BB, InsertPt, DL, TII->get(Hexagon::A2_combineii), DoubleDestReg)
709       .addJumpTableIndex(HiOperand.getIndex(), HiOperand.getTargetFlags())
710       .addImm(LoOperand.getImm());
711     return;
712   }
713   if (LoOperand.isJTI()) {
714     BuildMI(*BB, InsertPt, DL, TII->get(Hexagon::A4_combineii), DoubleDestReg)
715       .addImm(HiOperand.getImm())
716       .addJumpTableIndex(LoOperand.getIndex(), LoOperand.getTargetFlags());
717     return;
718   }
719 
720   // Handle constant pools.
721   if (HiOperand.isCPI()) {
722     BuildMI(*BB, InsertPt, DL, TII->get(Hexagon::A2_combineii), DoubleDestReg)
723       .addConstantPoolIndex(HiOperand.getIndex(), HiOperand.getOffset(),
724                             HiOperand.getTargetFlags())
725       .addImm(LoOperand.getImm());
726     return;
727   }
728   if (LoOperand.isCPI()) {
729     BuildMI(*BB, InsertPt, DL, TII->get(Hexagon::A4_combineii), DoubleDestReg)
730       .addImm(HiOperand.getImm())
731       .addConstantPoolIndex(LoOperand.getIndex(), LoOperand.getOffset(),
732                             LoOperand.getTargetFlags());
733     return;
734   }
735 
736   // First preference should be given to Hexagon::A2_combineii instruction
737   // as it can include U6 (in Hexagon::A4_combineii) as well.
738   // In this instruction, HiOperand is const extended, if required.
739   if (isInt<8>(LoOperand.getImm())) {
740     BuildMI(*BB, InsertPt, DL, TII->get(Hexagon::A2_combineii), DoubleDestReg)
741       .addImm(HiOperand.getImm())
742       .addImm(LoOperand.getImm());
743       return;
744   }
745 
746   // In this instruction, LoOperand is const extended, if required.
747   if (isInt<8>(HiOperand.getImm())) {
748     BuildMI(*BB, InsertPt, DL, TII->get(Hexagon::A4_combineii), DoubleDestReg)
749       .addImm(HiOperand.getImm())
750       .addImm(LoOperand.getImm());
751     return;
752   }
753 
754   // Insert new combine instruction.
755   //  DoubleRegDest = combine #HiImm, #LoImm
756   BuildMI(*BB, InsertPt, DL, TII->get(Hexagon::A2_combineii), DoubleDestReg)
757     .addImm(HiOperand.getImm())
758     .addImm(LoOperand.getImm());
759 }
760 
761 void HexagonCopyToCombine::emitCombineIR(MachineBasicBlock::iterator &InsertPt,
762                                          unsigned DoubleDestReg,
763                                          MachineOperand &HiOperand,
764                                          MachineOperand &LoOperand) {
765   unsigned LoReg = LoOperand.getReg();
766   unsigned LoRegKillFlag = getKillRegState(LoOperand.isKill());
767 
768   DebugLoc DL = InsertPt->getDebugLoc();
769   MachineBasicBlock *BB = InsertPt->getParent();
770 
771   // Handle globals.
772   if (HiOperand.isGlobal()) {
773     BuildMI(*BB, InsertPt, DL, TII->get(Hexagon::A4_combineir), DoubleDestReg)
774       .addGlobalAddress(HiOperand.getGlobal(), HiOperand.getOffset(),
775                         HiOperand.getTargetFlags())
776       .addReg(LoReg, LoRegKillFlag);
777     return;
778   }
779   // Handle block addresses.
780   if (HiOperand.isBlockAddress()) {
781     BuildMI(*BB, InsertPt, DL, TII->get(Hexagon::A4_combineir), DoubleDestReg)
782       .addBlockAddress(HiOperand.getBlockAddress(), HiOperand.getOffset(),
783                        HiOperand.getTargetFlags())
784       .addReg(LoReg, LoRegKillFlag);
785     return;
786   }
787   // Handle jump tables.
788   if (HiOperand.isJTI()) {
789     BuildMI(*BB, InsertPt, DL, TII->get(Hexagon::A4_combineir), DoubleDestReg)
790       .addJumpTableIndex(HiOperand.getIndex(), HiOperand.getTargetFlags())
791       .addReg(LoReg, LoRegKillFlag);
792     return;
793   }
794   // Handle constant pools.
795   if (HiOperand.isCPI()) {
796     BuildMI(*BB, InsertPt, DL, TII->get(Hexagon::A4_combineir), DoubleDestReg)
797       .addConstantPoolIndex(HiOperand.getIndex(), HiOperand.getOffset(),
798                             HiOperand.getTargetFlags())
799       .addReg(LoReg, LoRegKillFlag);
800     return;
801   }
802   // Insert new combine instruction.
803   //  DoubleRegDest = combine #HiImm, LoReg
804   BuildMI(*BB, InsertPt, DL, TII->get(Hexagon::A4_combineir), DoubleDestReg)
805     .addImm(HiOperand.getImm())
806     .addReg(LoReg, LoRegKillFlag);
807 }
808 
809 void HexagonCopyToCombine::emitCombineRI(MachineBasicBlock::iterator &InsertPt,
810                                          unsigned DoubleDestReg,
811                                          MachineOperand &HiOperand,
812                                          MachineOperand &LoOperand) {
813   unsigned HiRegKillFlag = getKillRegState(HiOperand.isKill());
814   unsigned HiReg = HiOperand.getReg();
815 
816   DebugLoc DL = InsertPt->getDebugLoc();
817   MachineBasicBlock *BB = InsertPt->getParent();
818 
819   // Handle global.
820   if (LoOperand.isGlobal()) {
821     BuildMI(*BB, InsertPt, DL, TII->get(Hexagon::A4_combineri), DoubleDestReg)
822       .addReg(HiReg, HiRegKillFlag)
823       .addGlobalAddress(LoOperand.getGlobal(), LoOperand.getOffset(),
824                         LoOperand.getTargetFlags());
825     return;
826   }
827   // Handle block addresses.
828   if (LoOperand.isBlockAddress()) {
829     BuildMI(*BB, InsertPt, DL, TII->get(Hexagon::A4_combineri), DoubleDestReg)
830       .addReg(HiReg, HiRegKillFlag)
831       .addBlockAddress(LoOperand.getBlockAddress(), LoOperand.getOffset(),
832                        LoOperand.getTargetFlags());
833     return;
834   }
835   // Handle jump tables.
836   if (LoOperand.isJTI()) {
837     BuildMI(*BB, InsertPt, DL, TII->get(Hexagon::A4_combineri), DoubleDestReg)
838       .addReg(HiOperand.getReg(), HiRegKillFlag)
839       .addJumpTableIndex(LoOperand.getIndex(), LoOperand.getTargetFlags());
840     return;
841   }
842   // Handle constant pools.
843   if (LoOperand.isCPI()) {
844     BuildMI(*BB, InsertPt, DL, TII->get(Hexagon::A4_combineri), DoubleDestReg)
845       .addReg(HiOperand.getReg(), HiRegKillFlag)
846       .addConstantPoolIndex(LoOperand.getIndex(), LoOperand.getOffset(),
847                             LoOperand.getTargetFlags());
848     return;
849   }
850 
851   // Insert new combine instruction.
852   //  DoubleRegDest = combine HiReg, #LoImm
853   BuildMI(*BB, InsertPt, DL, TII->get(Hexagon::A4_combineri), DoubleDestReg)
854     .addReg(HiReg, HiRegKillFlag)
855     .addImm(LoOperand.getImm());
856 }
857 
858 void HexagonCopyToCombine::emitCombineRR(MachineBasicBlock::iterator &InsertPt,
859                                          unsigned DoubleDestReg,
860                                          MachineOperand &HiOperand,
861                                          MachineOperand &LoOperand) {
862   unsigned LoRegKillFlag = getKillRegState(LoOperand.isKill());
863   unsigned HiRegKillFlag = getKillRegState(HiOperand.isKill());
864   unsigned LoReg = LoOperand.getReg();
865   unsigned HiReg = HiOperand.getReg();
866 
867   DebugLoc DL = InsertPt->getDebugLoc();
868   MachineBasicBlock *BB = InsertPt->getParent();
869 
870   // Insert new combine instruction.
871   //  DoubleRegDest = combine HiReg, LoReg
872   unsigned NewOpc;
873   if (Hexagon::DoubleRegsRegClass.contains(DoubleDestReg)) {
874     NewOpc = Hexagon::A2_combinew;
875   } else if (Hexagon::VecDblRegsRegClass.contains(DoubleDestReg)) {
876     assert(ST->useHVXOps());
877     if (ST->useHVXSglOps())
878       NewOpc = Hexagon::V6_vcombine;
879     else
880       NewOpc = Hexagon::V6_vcombine_128B;
881   } else
882     llvm_unreachable("Unexpected register");
883 
884   BuildMI(*BB, InsertPt, DL, TII->get(NewOpc), DoubleDestReg)
885     .addReg(HiReg, HiRegKillFlag)
886     .addReg(LoReg, LoRegKillFlag);
887 }
888 
889 FunctionPass *llvm::createHexagonCopyToCombine() {
890   return new HexagonCopyToCombine();
891 }
892