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