• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1 //=== A15SDOptimizerPass.cpp - Optimize DPR and SPR register accesses on A15==//
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 //
10 // The Cortex-A15 processor employs a tracking scheme in its register renaming
11 // in order to process each instruction's micro-ops speculatively and
12 // out-of-order with appropriate forwarding. The ARM architecture allows VFP
13 // instructions to read and write 32-bit S-registers.  Each S-register
14 // corresponds to one half (upper or lower) of an overlaid 64-bit D-register.
15 //
16 // There are several instruction patterns which can be used to provide this
17 // capability which can provide higher performance than other, potentially more
18 // direct patterns, specifically around when one micro-op reads a D-register
19 // operand that has recently been written as one or more S-register results.
20 //
21 // This file defines a pre-regalloc pass which looks for SPR producers which
22 // are going to be used by a DPR (or QPR) consumers and creates the more
23 // optimized access pattern.
24 //
25 //===----------------------------------------------------------------------===//
26 
27 #include "ARM.h"
28 #include "ARMBaseInstrInfo.h"
29 #include "ARMBaseRegisterInfo.h"
30 #include "ARMSubtarget.h"
31 #include "llvm/ADT/Statistic.h"
32 #include "llvm/CodeGen/MachineFunction.h"
33 #include "llvm/CodeGen/MachineFunctionPass.h"
34 #include "llvm/CodeGen/MachineInstr.h"
35 #include "llvm/CodeGen/MachineInstrBuilder.h"
36 #include "llvm/CodeGen/MachineRegisterInfo.h"
37 #include "llvm/Support/Debug.h"
38 #include "llvm/Support/raw_ostream.h"
39 #include "llvm/Target/TargetRegisterInfo.h"
40 #include "llvm/Target/TargetSubtargetInfo.h"
41 #include <map>
42 #include <set>
43 
44 using namespace llvm;
45 
46 #define DEBUG_TYPE "a15-sd-optimizer"
47 
48 namespace {
49   struct A15SDOptimizer : public MachineFunctionPass {
50     static char ID;
A15SDOptimizer__anon4f8adbd70111::A15SDOptimizer51     A15SDOptimizer() : MachineFunctionPass(ID) {}
52 
53     bool runOnMachineFunction(MachineFunction &Fn) override;
54 
getPassName__anon4f8adbd70111::A15SDOptimizer55     const char *getPassName() const override {
56       return "ARM A15 S->D optimizer";
57     }
58 
59   private:
60     const ARMBaseInstrInfo *TII;
61     const TargetRegisterInfo *TRI;
62     MachineRegisterInfo *MRI;
63 
64     bool runOnInstruction(MachineInstr *MI);
65 
66     //
67     // Instruction builder helpers
68     //
69     unsigned createDupLane(MachineBasicBlock &MBB,
70                            MachineBasicBlock::iterator InsertBefore,
71                            const DebugLoc &DL, unsigned Reg, unsigned Lane,
72                            bool QPR = false);
73 
74     unsigned createExtractSubreg(MachineBasicBlock &MBB,
75                                  MachineBasicBlock::iterator InsertBefore,
76                                  const DebugLoc &DL, unsigned DReg,
77                                  unsigned Lane, const TargetRegisterClass *TRC);
78 
79     unsigned createVExt(MachineBasicBlock &MBB,
80                         MachineBasicBlock::iterator InsertBefore,
81                         const DebugLoc &DL, unsigned Ssub0, unsigned Ssub1);
82 
83     unsigned createRegSequence(MachineBasicBlock &MBB,
84                                MachineBasicBlock::iterator InsertBefore,
85                                const DebugLoc &DL, unsigned Reg1,
86                                unsigned Reg2);
87 
88     unsigned createInsertSubreg(MachineBasicBlock &MBB,
89                                 MachineBasicBlock::iterator InsertBefore,
90                                 const DebugLoc &DL, unsigned DReg,
91                                 unsigned Lane, unsigned ToInsert);
92 
93     unsigned createImplicitDef(MachineBasicBlock &MBB,
94                                MachineBasicBlock::iterator InsertBefore,
95                                const DebugLoc &DL);
96 
97     //
98     // Various property checkers
99     //
100     bool usesRegClass(MachineOperand &MO, const TargetRegisterClass *TRC);
101     bool hasPartialWrite(MachineInstr *MI);
102     SmallVector<unsigned, 8> getReadDPRs(MachineInstr *MI);
103     unsigned getDPRLaneFromSPR(unsigned SReg);
104 
105     //
106     // Methods used for getting the definitions of partial registers
107     //
108 
109     MachineInstr *elideCopies(MachineInstr *MI);
110     void elideCopiesAndPHIs(MachineInstr *MI,
111                             SmallVectorImpl<MachineInstr*> &Outs);
112 
113     //
114     // Pattern optimization methods
115     //
116     unsigned optimizeAllLanesPattern(MachineInstr *MI, unsigned Reg);
117     unsigned optimizeSDPattern(MachineInstr *MI);
118     unsigned getPrefSPRLane(unsigned SReg);
119 
120     //
121     // Sanitizing method - used to make sure if don't leave dead code around.
122     //
123     void eraseInstrWithNoUses(MachineInstr *MI);
124 
125     //
126     // A map used to track the changes done by this pass.
127     //
128     std::map<MachineInstr*, unsigned> Replacements;
129     std::set<MachineInstr *> DeadInstr;
130   };
131   char A15SDOptimizer::ID = 0;
132 } // end anonymous namespace
133 
134 // Returns true if this is a use of a SPR register.
usesRegClass(MachineOperand & MO,const TargetRegisterClass * TRC)135 bool A15SDOptimizer::usesRegClass(MachineOperand &MO,
136                                   const TargetRegisterClass *TRC) {
137   if (!MO.isReg())
138     return false;
139   unsigned Reg = MO.getReg();
140 
141   if (TargetRegisterInfo::isVirtualRegister(Reg))
142     return MRI->getRegClass(Reg)->hasSuperClassEq(TRC);
143   else
144     return TRC->contains(Reg);
145 }
146 
getDPRLaneFromSPR(unsigned SReg)147 unsigned A15SDOptimizer::getDPRLaneFromSPR(unsigned SReg) {
148   unsigned DReg = TRI->getMatchingSuperReg(SReg, ARM::ssub_1,
149                                            &ARM::DPRRegClass);
150   if (DReg != ARM::NoRegister) return ARM::ssub_1;
151   return ARM::ssub_0;
152 }
153 
154 // Get the subreg type that is most likely to be coalesced
155 // for an SPR register that will be used in VDUP32d pseudo.
getPrefSPRLane(unsigned SReg)156 unsigned A15SDOptimizer::getPrefSPRLane(unsigned SReg) {
157   if (!TRI->isVirtualRegister(SReg))
158     return getDPRLaneFromSPR(SReg);
159 
160   MachineInstr *MI = MRI->getVRegDef(SReg);
161   if (!MI) return ARM::ssub_0;
162   MachineOperand *MO = MI->findRegisterDefOperand(SReg);
163 
164   assert(MO->isReg() && "Non-register operand found!");
165   if (!MO) return ARM::ssub_0;
166 
167   if (MI->isCopy() && usesRegClass(MI->getOperand(1),
168                                     &ARM::SPRRegClass)) {
169     SReg = MI->getOperand(1).getReg();
170   }
171 
172   if (TargetRegisterInfo::isVirtualRegister(SReg)) {
173     if (MO->getSubReg() == ARM::ssub_1) return ARM::ssub_1;
174     return ARM::ssub_0;
175   }
176   return getDPRLaneFromSPR(SReg);
177 }
178 
179 // MI is known to be dead. Figure out what instructions
180 // are also made dead by this and mark them for removal.
eraseInstrWithNoUses(MachineInstr * MI)181 void A15SDOptimizer::eraseInstrWithNoUses(MachineInstr *MI) {
182   SmallVector<MachineInstr *, 8> Front;
183   DeadInstr.insert(MI);
184 
185   DEBUG(dbgs() << "Deleting base instruction " << *MI << "\n");
186   Front.push_back(MI);
187 
188   while (Front.size() != 0) {
189     MI = Front.back();
190     Front.pop_back();
191 
192     // MI is already known to be dead. We need to see
193     // if other instructions can also be removed.
194     for (unsigned int i = 0; i < MI->getNumOperands(); ++i) {
195       MachineOperand &MO = MI->getOperand(i);
196       if ((!MO.isReg()) || (!MO.isUse()))
197         continue;
198       unsigned Reg = MO.getReg();
199       if (!TRI->isVirtualRegister(Reg))
200         continue;
201       MachineOperand *Op = MI->findRegisterDefOperand(Reg);
202 
203       if (!Op)
204         continue;
205 
206       MachineInstr *Def = Op->getParent();
207 
208       // We don't need to do anything if we have already marked
209       // this instruction as being dead.
210       if (DeadInstr.find(Def) != DeadInstr.end())
211         continue;
212 
213       // Check if all the uses of this instruction are marked as
214       // dead. If so, we can also mark this instruction as being
215       // dead.
216       bool IsDead = true;
217       for (unsigned int j = 0; j < Def->getNumOperands(); ++j) {
218         MachineOperand &MODef = Def->getOperand(j);
219         if ((!MODef.isReg()) || (!MODef.isDef()))
220           continue;
221         unsigned DefReg = MODef.getReg();
222         if (!TRI->isVirtualRegister(DefReg)) {
223           IsDead = false;
224           break;
225         }
226         for (MachineRegisterInfo::use_instr_iterator
227              II = MRI->use_instr_begin(Reg), EE = MRI->use_instr_end();
228              II != EE; ++II) {
229           // We don't care about self references.
230           if (&*II == Def)
231             continue;
232           if (DeadInstr.find(&*II) == DeadInstr.end()) {
233             IsDead = false;
234             break;
235           }
236         }
237       }
238 
239       if (!IsDead) continue;
240 
241       DEBUG(dbgs() << "Deleting instruction " << *Def << "\n");
242       DeadInstr.insert(Def);
243     }
244   }
245 }
246 
247 // Creates the more optimized patterns and generally does all the code
248 // transformations in this pass.
optimizeSDPattern(MachineInstr * MI)249 unsigned A15SDOptimizer::optimizeSDPattern(MachineInstr *MI) {
250   if (MI->isCopy()) {
251     return optimizeAllLanesPattern(MI, MI->getOperand(1).getReg());
252   }
253 
254   if (MI->isInsertSubreg()) {
255     unsigned DPRReg = MI->getOperand(1).getReg();
256     unsigned SPRReg = MI->getOperand(2).getReg();
257 
258     if (TRI->isVirtualRegister(DPRReg) && TRI->isVirtualRegister(SPRReg)) {
259       MachineInstr *DPRMI = MRI->getVRegDef(MI->getOperand(1).getReg());
260       MachineInstr *SPRMI = MRI->getVRegDef(MI->getOperand(2).getReg());
261 
262       if (DPRMI && SPRMI) {
263         // See if the first operand of this insert_subreg is IMPLICIT_DEF
264         MachineInstr *ECDef = elideCopies(DPRMI);
265         if (ECDef && ECDef->isImplicitDef()) {
266           // Another corner case - if we're inserting something that is purely
267           // a subreg copy of a DPR, just use that DPR.
268 
269           MachineInstr *EC = elideCopies(SPRMI);
270           // Is it a subreg copy of ssub_0?
271           if (EC && EC->isCopy() &&
272               EC->getOperand(1).getSubReg() == ARM::ssub_0) {
273             DEBUG(dbgs() << "Found a subreg copy: " << *SPRMI);
274 
275             // Find the thing we're subreg copying out of - is it of the same
276             // regclass as DPRMI? (i.e. a DPR or QPR).
277             unsigned FullReg = SPRMI->getOperand(1).getReg();
278             const TargetRegisterClass *TRC =
279               MRI->getRegClass(MI->getOperand(1).getReg());
280             if (TRC->hasSuperClassEq(MRI->getRegClass(FullReg))) {
281               DEBUG(dbgs() << "Subreg copy is compatible - returning ");
282               DEBUG(dbgs() << PrintReg(FullReg) << "\n");
283               eraseInstrWithNoUses(MI);
284               return FullReg;
285             }
286           }
287 
288           return optimizeAllLanesPattern(MI, MI->getOperand(2).getReg());
289         }
290       }
291     }
292     return optimizeAllLanesPattern(MI, MI->getOperand(0).getReg());
293   }
294 
295   if (MI->isRegSequence() && usesRegClass(MI->getOperand(1),
296                                           &ARM::SPRRegClass)) {
297     // See if all bar one of the operands are IMPLICIT_DEF and insert the
298     // optimizer pattern accordingly.
299     unsigned NumImplicit = 0, NumTotal = 0;
300     unsigned NonImplicitReg = ~0U;
301 
302     for (unsigned I = 1; I < MI->getNumExplicitOperands(); ++I) {
303       if (!MI->getOperand(I).isReg())
304         continue;
305       ++NumTotal;
306       unsigned OpReg = MI->getOperand(I).getReg();
307 
308       if (!TRI->isVirtualRegister(OpReg))
309         break;
310 
311       MachineInstr *Def = MRI->getVRegDef(OpReg);
312       if (!Def)
313         break;
314       if (Def->isImplicitDef())
315         ++NumImplicit;
316       else
317         NonImplicitReg = MI->getOperand(I).getReg();
318     }
319 
320     if (NumImplicit == NumTotal - 1)
321       return optimizeAllLanesPattern(MI, NonImplicitReg);
322     else
323       return optimizeAllLanesPattern(MI, MI->getOperand(0).getReg());
324   }
325 
326   llvm_unreachable("Unhandled update pattern!");
327 }
328 
329 // Return true if this MachineInstr inserts a scalar (SPR) value into
330 // a D or Q register.
hasPartialWrite(MachineInstr * MI)331 bool A15SDOptimizer::hasPartialWrite(MachineInstr *MI) {
332   // The only way we can do a partial register update is through a COPY,
333   // INSERT_SUBREG or REG_SEQUENCE.
334   if (MI->isCopy() && usesRegClass(MI->getOperand(1), &ARM::SPRRegClass))
335     return true;
336 
337   if (MI->isInsertSubreg() && usesRegClass(MI->getOperand(2),
338                                            &ARM::SPRRegClass))
339     return true;
340 
341   if (MI->isRegSequence() && usesRegClass(MI->getOperand(1), &ARM::SPRRegClass))
342     return true;
343 
344   return false;
345 }
346 
347 // Looks through full copies to get the instruction that defines the input
348 // operand for MI.
elideCopies(MachineInstr * MI)349 MachineInstr *A15SDOptimizer::elideCopies(MachineInstr *MI) {
350   if (!MI->isFullCopy())
351     return MI;
352   if (!TRI->isVirtualRegister(MI->getOperand(1).getReg()))
353     return nullptr;
354   MachineInstr *Def = MRI->getVRegDef(MI->getOperand(1).getReg());
355   if (!Def)
356     return nullptr;
357   return elideCopies(Def);
358 }
359 
360 // Look through full copies and PHIs to get the set of non-copy MachineInstrs
361 // that can produce MI.
elideCopiesAndPHIs(MachineInstr * MI,SmallVectorImpl<MachineInstr * > & Outs)362 void A15SDOptimizer::elideCopiesAndPHIs(MachineInstr *MI,
363                                         SmallVectorImpl<MachineInstr*> &Outs) {
364    // Looking through PHIs may create loops so we need to track what
365    // instructions we have visited before.
366    std::set<MachineInstr *> Reached;
367    SmallVector<MachineInstr *, 8> Front;
368    Front.push_back(MI);
369    while (Front.size() != 0) {
370      MI = Front.back();
371      Front.pop_back();
372 
373      // If we have already explored this MachineInstr, ignore it.
374      if (Reached.find(MI) != Reached.end())
375        continue;
376      Reached.insert(MI);
377      if (MI->isPHI()) {
378        for (unsigned I = 1, E = MI->getNumOperands(); I != E; I += 2) {
379          unsigned Reg = MI->getOperand(I).getReg();
380          if (!TRI->isVirtualRegister(Reg)) {
381            continue;
382          }
383          MachineInstr *NewMI = MRI->getVRegDef(Reg);
384          if (!NewMI)
385            continue;
386          Front.push_back(NewMI);
387        }
388      } else if (MI->isFullCopy()) {
389        if (!TRI->isVirtualRegister(MI->getOperand(1).getReg()))
390          continue;
391        MachineInstr *NewMI = MRI->getVRegDef(MI->getOperand(1).getReg());
392        if (!NewMI)
393          continue;
394        Front.push_back(NewMI);
395      } else {
396        DEBUG(dbgs() << "Found partial copy" << *MI <<"\n");
397        Outs.push_back(MI);
398      }
399    }
400 }
401 
402 // Return the DPR virtual registers that are read by this machine instruction
403 // (if any).
getReadDPRs(MachineInstr * MI)404 SmallVector<unsigned, 8> A15SDOptimizer::getReadDPRs(MachineInstr *MI) {
405   if (MI->isCopyLike() || MI->isInsertSubreg() || MI->isRegSequence() ||
406       MI->isKill())
407     return SmallVector<unsigned, 8>();
408 
409   SmallVector<unsigned, 8> Defs;
410   for (unsigned i = 0; i < MI->getNumOperands(); ++i) {
411     MachineOperand &MO = MI->getOperand(i);
412 
413     if (!MO.isReg() || !MO.isUse())
414       continue;
415     if (!usesRegClass(MO, &ARM::DPRRegClass) &&
416         !usesRegClass(MO, &ARM::QPRRegClass) &&
417         !usesRegClass(MO, &ARM::DPairRegClass)) // Treat DPair as QPR
418       continue;
419 
420     Defs.push_back(MO.getReg());
421   }
422   return Defs;
423 }
424 
425 // Creates a DPR register from an SPR one by using a VDUP.
createDupLane(MachineBasicBlock & MBB,MachineBasicBlock::iterator InsertBefore,const DebugLoc & DL,unsigned Reg,unsigned Lane,bool QPR)426 unsigned A15SDOptimizer::createDupLane(MachineBasicBlock &MBB,
427                                        MachineBasicBlock::iterator InsertBefore,
428                                        const DebugLoc &DL, unsigned Reg,
429                                        unsigned Lane, bool QPR) {
430   unsigned Out = MRI->createVirtualRegister(QPR ? &ARM::QPRRegClass :
431                                                   &ARM::DPRRegClass);
432   AddDefaultPred(BuildMI(MBB,
433                          InsertBefore,
434                          DL,
435                          TII->get(QPR ? ARM::VDUPLN32q : ARM::VDUPLN32d),
436                          Out)
437                    .addReg(Reg)
438                    .addImm(Lane));
439 
440   return Out;
441 }
442 
443 // Creates a SPR register from a DPR by copying the value in lane 0.
createExtractSubreg(MachineBasicBlock & MBB,MachineBasicBlock::iterator InsertBefore,const DebugLoc & DL,unsigned DReg,unsigned Lane,const TargetRegisterClass * TRC)444 unsigned A15SDOptimizer::createExtractSubreg(
445     MachineBasicBlock &MBB, MachineBasicBlock::iterator InsertBefore,
446     const DebugLoc &DL, unsigned DReg, unsigned Lane,
447     const TargetRegisterClass *TRC) {
448   unsigned Out = MRI->createVirtualRegister(TRC);
449   BuildMI(MBB,
450           InsertBefore,
451           DL,
452           TII->get(TargetOpcode::COPY), Out)
453     .addReg(DReg, 0, Lane);
454 
455   return Out;
456 }
457 
458 // Takes two SPR registers and creates a DPR by using a REG_SEQUENCE.
createRegSequence(MachineBasicBlock & MBB,MachineBasicBlock::iterator InsertBefore,const DebugLoc & DL,unsigned Reg1,unsigned Reg2)459 unsigned A15SDOptimizer::createRegSequence(
460     MachineBasicBlock &MBB, MachineBasicBlock::iterator InsertBefore,
461     const DebugLoc &DL, unsigned Reg1, unsigned Reg2) {
462   unsigned Out = MRI->createVirtualRegister(&ARM::QPRRegClass);
463   BuildMI(MBB,
464           InsertBefore,
465           DL,
466           TII->get(TargetOpcode::REG_SEQUENCE), Out)
467     .addReg(Reg1)
468     .addImm(ARM::dsub_0)
469     .addReg(Reg2)
470     .addImm(ARM::dsub_1);
471   return Out;
472 }
473 
474 // Takes two DPR registers that have previously been VDUPed (Ssub0 and Ssub1)
475 // and merges them into one DPR register.
createVExt(MachineBasicBlock & MBB,MachineBasicBlock::iterator InsertBefore,const DebugLoc & DL,unsigned Ssub0,unsigned Ssub1)476 unsigned A15SDOptimizer::createVExt(MachineBasicBlock &MBB,
477                                     MachineBasicBlock::iterator InsertBefore,
478                                     const DebugLoc &DL, unsigned Ssub0,
479                                     unsigned Ssub1) {
480   unsigned Out = MRI->createVirtualRegister(&ARM::DPRRegClass);
481   AddDefaultPred(BuildMI(MBB,
482                          InsertBefore,
483                          DL,
484                          TII->get(ARM::VEXTd32), Out)
485                    .addReg(Ssub0)
486                    .addReg(Ssub1)
487                    .addImm(1));
488   return Out;
489 }
490 
createInsertSubreg(MachineBasicBlock & MBB,MachineBasicBlock::iterator InsertBefore,const DebugLoc & DL,unsigned DReg,unsigned Lane,unsigned ToInsert)491 unsigned A15SDOptimizer::createInsertSubreg(
492     MachineBasicBlock &MBB, MachineBasicBlock::iterator InsertBefore,
493     const DebugLoc &DL, unsigned DReg, unsigned Lane, unsigned ToInsert) {
494   unsigned Out = MRI->createVirtualRegister(&ARM::DPR_VFP2RegClass);
495   BuildMI(MBB,
496           InsertBefore,
497           DL,
498           TII->get(TargetOpcode::INSERT_SUBREG), Out)
499     .addReg(DReg)
500     .addReg(ToInsert)
501     .addImm(Lane);
502 
503   return Out;
504 }
505 
506 unsigned
createImplicitDef(MachineBasicBlock & MBB,MachineBasicBlock::iterator InsertBefore,const DebugLoc & DL)507 A15SDOptimizer::createImplicitDef(MachineBasicBlock &MBB,
508                                   MachineBasicBlock::iterator InsertBefore,
509                                   const DebugLoc &DL) {
510   unsigned Out = MRI->createVirtualRegister(&ARM::DPRRegClass);
511   BuildMI(MBB,
512           InsertBefore,
513           DL,
514           TII->get(TargetOpcode::IMPLICIT_DEF), Out);
515   return Out;
516 }
517 
518 // This function inserts instructions in order to optimize interactions between
519 // SPR registers and DPR/QPR registers. It does so by performing VDUPs on all
520 // lanes, and the using VEXT instructions to recompose the result.
521 unsigned
optimizeAllLanesPattern(MachineInstr * MI,unsigned Reg)522 A15SDOptimizer::optimizeAllLanesPattern(MachineInstr *MI, unsigned Reg) {
523   MachineBasicBlock::iterator InsertPt(MI);
524   DebugLoc DL = MI->getDebugLoc();
525   MachineBasicBlock &MBB = *MI->getParent();
526   InsertPt++;
527   unsigned Out;
528 
529   // DPair has the same length as QPR and also has two DPRs as subreg.
530   // Treat DPair as QPR.
531   if (MRI->getRegClass(Reg)->hasSuperClassEq(&ARM::QPRRegClass) ||
532       MRI->getRegClass(Reg)->hasSuperClassEq(&ARM::DPairRegClass)) {
533     unsigned DSub0 = createExtractSubreg(MBB, InsertPt, DL, Reg,
534                                          ARM::dsub_0, &ARM::DPRRegClass);
535     unsigned DSub1 = createExtractSubreg(MBB, InsertPt, DL, Reg,
536                                          ARM::dsub_1, &ARM::DPRRegClass);
537 
538     unsigned Out1 = createDupLane(MBB, InsertPt, DL, DSub0, 0);
539     unsigned Out2 = createDupLane(MBB, InsertPt, DL, DSub0, 1);
540     Out = createVExt(MBB, InsertPt, DL, Out1, Out2);
541 
542     unsigned Out3 = createDupLane(MBB, InsertPt, DL, DSub1, 0);
543     unsigned Out4 = createDupLane(MBB, InsertPt, DL, DSub1, 1);
544     Out2 = createVExt(MBB, InsertPt, DL, Out3, Out4);
545 
546     Out = createRegSequence(MBB, InsertPt, DL, Out, Out2);
547 
548   } else if (MRI->getRegClass(Reg)->hasSuperClassEq(&ARM::DPRRegClass)) {
549     unsigned Out1 = createDupLane(MBB, InsertPt, DL, Reg, 0);
550     unsigned Out2 = createDupLane(MBB, InsertPt, DL, Reg, 1);
551     Out = createVExt(MBB, InsertPt, DL, Out1, Out2);
552 
553   } else {
554     assert(MRI->getRegClass(Reg)->hasSuperClassEq(&ARM::SPRRegClass) &&
555            "Found unexpected regclass!");
556 
557     unsigned PrefLane = getPrefSPRLane(Reg);
558     unsigned Lane;
559     switch (PrefLane) {
560       case ARM::ssub_0: Lane = 0; break;
561       case ARM::ssub_1: Lane = 1; break;
562       default: llvm_unreachable("Unknown preferred lane!");
563     }
564 
565     // Treat DPair as QPR
566     bool UsesQPR = usesRegClass(MI->getOperand(0), &ARM::QPRRegClass) ||
567                    usesRegClass(MI->getOperand(0), &ARM::DPairRegClass);
568 
569     Out = createImplicitDef(MBB, InsertPt, DL);
570     Out = createInsertSubreg(MBB, InsertPt, DL, Out, PrefLane, Reg);
571     Out = createDupLane(MBB, InsertPt, DL, Out, Lane, UsesQPR);
572     eraseInstrWithNoUses(MI);
573   }
574   return Out;
575 }
576 
runOnInstruction(MachineInstr * MI)577 bool A15SDOptimizer::runOnInstruction(MachineInstr *MI) {
578   // We look for instructions that write S registers that are then read as
579   // D/Q registers. These can only be caused by COPY, INSERT_SUBREG and
580   // REG_SEQUENCE pseudos that insert an SPR value into a DPR register or
581   // merge two SPR values to form a DPR register.  In order avoid false
582   // positives we make sure that there is an SPR producer so we look past
583   // COPY and PHI nodes to find it.
584   //
585   // The best code pattern for when an SPR producer is going to be used by a
586   // DPR or QPR consumer depends on whether the other lanes of the
587   // corresponding DPR/QPR are currently defined.
588   //
589   // We can handle these efficiently, depending on the type of
590   // pseudo-instruction that is producing the pattern
591   //
592   //   * COPY:          * VDUP all lanes and merge the results together
593   //                      using VEXTs.
594   //
595   //   * INSERT_SUBREG: * If the SPR value was originally in another DPR/QPR
596   //                      lane, and the other lane(s) of the DPR/QPR register
597   //                      that we are inserting in are undefined, use the
598   //                      original DPR/QPR value.
599   //                    * Otherwise, fall back on the same stategy as COPY.
600   //
601   //   * REG_SEQUENCE:  * If all except one of the input operands are
602   //                      IMPLICIT_DEFs, insert the VDUP pattern for just the
603   //                      defined input operand
604   //                    * Otherwise, fall back on the same stategy as COPY.
605   //
606 
607   // First, get all the reads of D-registers done by this instruction.
608   SmallVector<unsigned, 8> Defs = getReadDPRs(MI);
609   bool Modified = false;
610 
611   for (SmallVectorImpl<unsigned>::iterator I = Defs.begin(), E = Defs.end();
612      I != E; ++I) {
613     // Follow the def-use chain for this DPR through COPYs, and also through
614     // PHIs (which are essentially multi-way COPYs). It is because of PHIs that
615     // we can end up with multiple defs of this DPR.
616 
617     SmallVector<MachineInstr *, 8> DefSrcs;
618     if (!TRI->isVirtualRegister(*I))
619       continue;
620     MachineInstr *Def = MRI->getVRegDef(*I);
621     if (!Def)
622       continue;
623 
624     elideCopiesAndPHIs(Def, DefSrcs);
625 
626     for (SmallVectorImpl<MachineInstr *>::iterator II = DefSrcs.begin(),
627       EE = DefSrcs.end(); II != EE; ++II) {
628       MachineInstr *MI = *II;
629 
630       // If we've already analyzed and replaced this operand, don't do
631       // anything.
632       if (Replacements.find(MI) != Replacements.end())
633         continue;
634 
635       // Now, work out if the instruction causes a SPR->DPR dependency.
636       if (!hasPartialWrite(MI))
637         continue;
638 
639       // Collect all the uses of this MI's DPR def for updating later.
640       SmallVector<MachineOperand*, 8> Uses;
641       unsigned DPRDefReg = MI->getOperand(0).getReg();
642       for (MachineRegisterInfo::use_iterator I = MRI->use_begin(DPRDefReg),
643              E = MRI->use_end(); I != E; ++I)
644         Uses.push_back(&*I);
645 
646       // We can optimize this.
647       unsigned NewReg = optimizeSDPattern(MI);
648 
649       if (NewReg != 0) {
650         Modified = true;
651         for (SmallVectorImpl<MachineOperand *>::const_iterator I = Uses.begin(),
652                E = Uses.end(); I != E; ++I) {
653           // Make sure to constrain the register class of the new register to
654           // match what we're replacing. Otherwise we can optimize a DPR_VFP2
655           // reference into a plain DPR, and that will end poorly. NewReg is
656           // always virtual here, so there will always be a matching subclass
657           // to find.
658           MRI->constrainRegClass(NewReg, MRI->getRegClass((*I)->getReg()));
659 
660           DEBUG(dbgs() << "Replacing operand "
661                        << **I << " with "
662                        << PrintReg(NewReg) << "\n");
663           (*I)->substVirtReg(NewReg, 0, *TRI);
664         }
665       }
666       Replacements[MI] = NewReg;
667     }
668   }
669   return Modified;
670 }
671 
runOnMachineFunction(MachineFunction & Fn)672 bool A15SDOptimizer::runOnMachineFunction(MachineFunction &Fn) {
673   if (skipFunction(*Fn.getFunction()))
674     return false;
675 
676   const ARMSubtarget &STI = Fn.getSubtarget<ARMSubtarget>();
677   // Since the A15SDOptimizer pass can insert VDUP instructions, it can only be
678   // enabled when NEON is available.
679   if (!(STI.isCortexA15() && STI.hasNEON()))
680     return false;
681   TII = STI.getInstrInfo();
682   TRI = STI.getRegisterInfo();
683   MRI = &Fn.getRegInfo();
684   bool Modified = false;
685 
686   DEBUG(dbgs() << "Running on function " << Fn.getName()<< "\n");
687 
688   DeadInstr.clear();
689   Replacements.clear();
690 
691   for (MachineFunction::iterator MFI = Fn.begin(), E = Fn.end(); MFI != E;
692        ++MFI) {
693 
694     for (MachineBasicBlock::iterator MI = MFI->begin(), ME = MFI->end();
695       MI != ME;) {
696       Modified |= runOnInstruction(&*MI++);
697     }
698 
699   }
700 
701   for (std::set<MachineInstr *>::iterator I = DeadInstr.begin(),
702                                             E = DeadInstr.end();
703                                             I != E; ++I) {
704     (*I)->eraseFromParent();
705   }
706 
707   return Modified;
708 }
709 
createA15SDOptimizerPass()710 FunctionPass *llvm::createA15SDOptimizerPass() {
711   return new A15SDOptimizer();
712 }
713