Rename SSEDomainFix -> lib/CodeGen/ExecutionDepsFix.
[oota-llvm.git] / lib / CodeGen / ExecutionDepsFix.cpp
1 //===- SSEDomainFix.cpp - Use proper int/float domain for SSE ---*- C++ -*-===//
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 // This file contains the SSEDomainFix pass.
11 //
12 // Some SSE instructions like mov, and, or, xor are available in different
13 // variants for different operand types. These variant instructions are
14 // equivalent, but on Nehalem and newer cpus there is extra latency
15 // transferring data between integer and floating point domains.
16 //
17 // This pass changes the variant instructions to minimize domain crossings.
18 //
19 //===----------------------------------------------------------------------===//
20
21 #define DEBUG_TYPE "execution-fix"
22 #include "llvm/CodeGen/MachineFunctionPass.h"
23 #include "llvm/CodeGen/MachineRegisterInfo.h"
24 #include "llvm/CodeGen/Passes.h"
25 #include "llvm/Target/TargetInstrInfo.h"
26 #include "llvm/Target/TargetMachine.h"
27 #include "llvm/ADT/DepthFirstIterator.h"
28 #include "llvm/Support/Allocator.h"
29 #include "llvm/Support/Debug.h"
30 #include "llvm/Support/raw_ostream.h"
31 using namespace llvm;
32
33 /// A DomainValue is a bit like LiveIntervals' ValNo, but it also keeps track
34 /// of execution domains.
35 ///
36 /// An open DomainValue represents a set of instructions that can still switch
37 /// execution domain. Multiple registers may refer to the same open
38 /// DomainValue - they will eventually be collapsed to the same execution
39 /// domain.
40 ///
41 /// A collapsed DomainValue represents a single register that has been forced
42 /// into one of more execution domains. There is a separate collapsed
43 /// DomainValue for each register, but it may contain multiple execution
44 /// domains. A register value is initially created in a single execution
45 /// domain, but if we were forced to pay the penalty of a domain crossing, we
46 /// keep track of the fact the the register is now available in multiple
47 /// domains.
48 namespace {
49 struct DomainValue {
50   // Basic reference counting.
51   unsigned Refs;
52
53   // Bitmask of available domains. For an open DomainValue, it is the still
54   // possible domains for collapsing. For a collapsed DomainValue it is the
55   // domains where the register is available for free.
56   unsigned AvailableDomains;
57
58   // Position of the last defining instruction.
59   unsigned Dist;
60
61   // Twiddleable instructions using or defining these registers.
62   SmallVector<MachineInstr*, 8> Instrs;
63
64   // A collapsed DomainValue has no instructions to twiddle - it simply keeps
65   // track of the domains where the registers are already available.
66   bool isCollapsed() const { return Instrs.empty(); }
67
68   // Is domain available?
69   bool hasDomain(unsigned domain) const {
70     return AvailableDomains & (1u << domain);
71   }
72
73   // Mark domain as available.
74   void addDomain(unsigned domain) {
75     AvailableDomains |= 1u << domain;
76   }
77
78   // Restrict to a single domain available.
79   void setSingleDomain(unsigned domain) {
80     AvailableDomains = 1u << domain;
81   }
82
83   // Return bitmask of domains that are available and in mask.
84   unsigned getCommonDomains(unsigned mask) const {
85     return AvailableDomains & mask;
86   }
87
88   // First domain available.
89   unsigned getFirstDomain() const {
90     return CountTrailingZeros_32(AvailableDomains);
91   }
92
93   DomainValue() { clear(); }
94
95   void clear() {
96     Refs = AvailableDomains = Dist = 0;
97     Instrs.clear();
98   }
99 };
100 }
101
102 namespace {
103 class SSEDomainFixPass : public MachineFunctionPass {
104   static char ID;
105   SpecificBumpPtrAllocator<DomainValue> Allocator;
106   SmallVector<DomainValue*,16> Avail;
107
108   const TargetRegisterClass *const RC;
109   MachineFunction *MF;
110   const TargetInstrInfo *TII;
111   const TargetRegisterInfo *TRI;
112   MachineBasicBlock *MBB;
113   std::vector<int> AliasMap;
114   const unsigned NumRegs;
115   DomainValue **LiveRegs;
116   typedef DenseMap<MachineBasicBlock*,DomainValue**> LiveOutMap;
117   LiveOutMap LiveOuts;
118   unsigned Distance;
119
120 public:
121   SSEDomainFixPass(const TargetRegisterClass *rc)
122     : MachineFunctionPass(ID), RC(rc), NumRegs(RC->getNumRegs()) {}
123
124   virtual void getAnalysisUsage(AnalysisUsage &AU) const {
125     AU.setPreservesAll();
126     MachineFunctionPass::getAnalysisUsage(AU);
127   }
128
129   virtual bool runOnMachineFunction(MachineFunction &MF);
130
131   virtual const char *getPassName() const {
132     return "SSE execution domain fixup";
133   }
134
135 private:
136   // Register mapping.
137   int RegIndex(unsigned Reg);
138
139   // DomainValue allocation.
140   DomainValue *Alloc(int domain = -1);
141   void Recycle(DomainValue*);
142
143   // LiveRegs manipulations.
144   void SetLiveReg(int rx, DomainValue *DV);
145   void Kill(int rx);
146   void Force(int rx, unsigned domain);
147   void Collapse(DomainValue *dv, unsigned domain);
148   bool Merge(DomainValue *A, DomainValue *B);
149
150   void enterBasicBlock();
151   void visitGenericInstr(MachineInstr*);
152   void visitSoftInstr(MachineInstr*, unsigned mask);
153   void visitHardInstr(MachineInstr*, unsigned domain);
154 };
155 }
156
157 char SSEDomainFixPass::ID = 0;
158
159 /// Translate TRI register number to an index into our smaller tables of
160 /// interesting registers. Return -1 for boring registers.
161 int SSEDomainFixPass::RegIndex(unsigned Reg) {
162   assert(Reg < AliasMap.size() && "Invalid register");
163   return AliasMap[Reg];
164 }
165
166 DomainValue *SSEDomainFixPass::Alloc(int domain) {
167   DomainValue *dv = Avail.empty() ?
168                       new(Allocator.Allocate()) DomainValue :
169                       Avail.pop_back_val();
170   dv->Dist = Distance;
171   if (domain >= 0)
172     dv->addDomain(domain);
173   return dv;
174 }
175
176 void SSEDomainFixPass::Recycle(DomainValue *dv) {
177   assert(dv && "Cannot recycle NULL");
178   dv->clear();
179   Avail.push_back(dv);
180 }
181
182 /// Set LiveRegs[rx] = dv, updating reference counts.
183 void SSEDomainFixPass::SetLiveReg(int rx, DomainValue *dv) {
184   assert(unsigned(rx) < NumRegs && "Invalid index");
185   if (!LiveRegs) {
186     LiveRegs = new DomainValue*[NumRegs];
187     std::fill(LiveRegs, LiveRegs+NumRegs, (DomainValue*)0);
188   }
189
190   if (LiveRegs[rx] == dv)
191     return;
192   if (LiveRegs[rx]) {
193     assert(LiveRegs[rx]->Refs && "Bad refcount");
194     if (--LiveRegs[rx]->Refs == 0) Recycle(LiveRegs[rx]);
195   }
196   LiveRegs[rx] = dv;
197   if (dv) ++dv->Refs;
198 }
199
200 // Kill register rx, recycle or collapse any DomainValue.
201 void SSEDomainFixPass::Kill(int rx) {
202   assert(unsigned(rx) < NumRegs && "Invalid index");
203   if (!LiveRegs || !LiveRegs[rx]) return;
204
205   // Before killing the last reference to an open DomainValue, collapse it to
206   // the first available domain.
207   if (LiveRegs[rx]->Refs == 1 && !LiveRegs[rx]->isCollapsed())
208     Collapse(LiveRegs[rx], LiveRegs[rx]->getFirstDomain());
209   else
210     SetLiveReg(rx, 0);
211 }
212
213 /// Force register rx into domain.
214 void SSEDomainFixPass::Force(int rx, unsigned domain) {
215   assert(unsigned(rx) < NumRegs && "Invalid index");
216   DomainValue *dv;
217   if (LiveRegs && (dv = LiveRegs[rx])) {
218     if (dv->isCollapsed())
219       dv->addDomain(domain);
220     else if (dv->hasDomain(domain))
221       Collapse(dv, domain);
222     else {
223       // This is an incompatible open DomainValue. Collapse it to whatever and force
224       // the new value into domain. This costs a domain crossing.
225       Collapse(dv, dv->getFirstDomain());
226       assert(LiveRegs[rx] && "Not live after collapse?");
227       LiveRegs[rx]->addDomain(domain);
228     }
229   } else {
230     // Set up basic collapsed DomainValue.
231     SetLiveReg(rx, Alloc(domain));
232   }
233 }
234
235 /// Collapse open DomainValue into given domain. If there are multiple
236 /// registers using dv, they each get a unique collapsed DomainValue.
237 void SSEDomainFixPass::Collapse(DomainValue *dv, unsigned domain) {
238   assert(dv->hasDomain(domain) && "Cannot collapse");
239
240   // Collapse all the instructions.
241   while (!dv->Instrs.empty())
242     TII->setExecutionDomain(dv->Instrs.pop_back_val(), domain);
243   dv->setSingleDomain(domain);
244
245   // If there are multiple users, give them new, unique DomainValues.
246   if (LiveRegs && dv->Refs > 1)
247     for (unsigned rx = 0; rx != NumRegs; ++rx)
248       if (LiveRegs[rx] == dv)
249         SetLiveReg(rx, Alloc(domain));
250 }
251
252 /// Merge - All instructions and registers in B are moved to A, and B is
253 /// released.
254 bool SSEDomainFixPass::Merge(DomainValue *A, DomainValue *B) {
255   assert(!A->isCollapsed() && "Cannot merge into collapsed");
256   assert(!B->isCollapsed() && "Cannot merge from collapsed");
257   if (A == B)
258     return true;
259   // Restrict to the domains that A and B have in common.
260   unsigned common = A->getCommonDomains(B->AvailableDomains);
261   if (!common)
262     return false;
263   A->AvailableDomains = common;
264   A->Dist = std::max(A->Dist, B->Dist);
265   A->Instrs.append(B->Instrs.begin(), B->Instrs.end());
266   for (unsigned rx = 0; rx != NumRegs; ++rx)
267     if (LiveRegs[rx] == B)
268       SetLiveReg(rx, A);
269   return true;
270 }
271
272 void SSEDomainFixPass::enterBasicBlock() {
273   // Try to coalesce live-out registers from predecessors.
274   for (MachineBasicBlock::livein_iterator i = MBB->livein_begin(),
275          e = MBB->livein_end(); i != e; ++i) {
276     int rx = RegIndex(*i);
277     if (rx < 0) continue;
278     for (MachineBasicBlock::const_pred_iterator pi = MBB->pred_begin(),
279            pe = MBB->pred_end(); pi != pe; ++pi) {
280       LiveOutMap::const_iterator fi = LiveOuts.find(*pi);
281       if (fi == LiveOuts.end()) continue;
282       DomainValue *pdv = fi->second[rx];
283       if (!pdv) continue;
284       if (!LiveRegs || !LiveRegs[rx]) {
285         SetLiveReg(rx, pdv);
286         continue;
287       }
288
289       // We have a live DomainValue from more than one predecessor.
290       if (LiveRegs[rx]->isCollapsed()) {
291         // We are already collapsed, but predecessor is not. Force him.
292         unsigned domain = LiveRegs[rx]->getFirstDomain();
293         if (!pdv->isCollapsed() && pdv->hasDomain(domain))
294           Collapse(pdv, domain);
295         continue;
296       }
297
298       // Currently open, merge in predecessor.
299       if (!pdv->isCollapsed())
300         Merge(LiveRegs[rx], pdv);
301       else
302         Force(rx, pdv->getFirstDomain());
303     }
304   }
305 }
306
307 // A hard instruction only works in one domain. All input registers will be
308 // forced into that domain.
309 void SSEDomainFixPass::visitHardInstr(MachineInstr *mi, unsigned domain) {
310   // Collapse all uses.
311   for (unsigned i = mi->getDesc().getNumDefs(),
312                 e = mi->getDesc().getNumOperands(); i != e; ++i) {
313     MachineOperand &mo = mi->getOperand(i);
314     if (!mo.isReg()) continue;
315     int rx = RegIndex(mo.getReg());
316     if (rx < 0) continue;
317     Force(rx, domain);
318   }
319
320   // Kill all defs and force them.
321   for (unsigned i = 0, e = mi->getDesc().getNumDefs(); i != e; ++i) {
322     MachineOperand &mo = mi->getOperand(i);
323     if (!mo.isReg()) continue;
324     int rx = RegIndex(mo.getReg());
325     if (rx < 0) continue;
326     Kill(rx);
327     Force(rx, domain);
328   }
329 }
330
331 // A soft instruction can be changed to work in other domains given by mask.
332 void SSEDomainFixPass::visitSoftInstr(MachineInstr *mi, unsigned mask) {
333   // Bitmask of available domains for this instruction after taking collapsed
334   // operands into account.
335   unsigned available = mask;
336
337   // Scan the explicit use operands for incoming domains.
338   SmallVector<int, 4> used;
339   if (LiveRegs)
340     for (unsigned i = mi->getDesc().getNumDefs(),
341                   e = mi->getDesc().getNumOperands(); i != e; ++i) {
342       MachineOperand &mo = mi->getOperand(i);
343       if (!mo.isReg()) continue;
344       int rx = RegIndex(mo.getReg());
345       if (rx < 0) continue;
346       if (DomainValue *dv = LiveRegs[rx]) {
347         // Bitmask of domains that dv and available have in common.
348         unsigned common = dv->getCommonDomains(available);
349         // Is it possible to use this collapsed register for free?
350         if (dv->isCollapsed()) {
351           // Restrict available domains to the ones in common with the operand.
352           // If there are no common domains, we must pay the cross-domain 
353           // penalty for this operand.
354           if (common) available = common;
355         } else if (common)
356           // Open DomainValue is compatible, save it for merging.
357           used.push_back(rx);
358         else
359           // Open DomainValue is not compatible with instruction. It is useless
360           // now.
361           Kill(rx);
362       }
363     }
364
365   // If the collapsed operands force a single domain, propagate the collapse.
366   if (isPowerOf2_32(available)) {
367     unsigned domain = CountTrailingZeros_32(available);
368     TII->setExecutionDomain(mi, domain);
369     visitHardInstr(mi, domain);
370     return;
371   }
372
373   // Kill off any remaining uses that don't match available, and build a list of
374   // incoming DomainValues that we want to merge.
375   SmallVector<DomainValue*,4> doms;
376   for (SmallVector<int, 4>::iterator i=used.begin(), e=used.end(); i!=e; ++i) {
377     int rx = *i;
378     DomainValue *dv = LiveRegs[rx];
379     // This useless DomainValue could have been missed above.
380     if (!dv->getCommonDomains(available)) {
381       Kill(*i);
382       continue;
383     }
384     // sorted, uniqued insert.
385     bool inserted = false;
386     for (SmallVector<DomainValue*,4>::iterator i = doms.begin(), e = doms.end();
387            i != e && !inserted; ++i) {
388       if (dv == *i)
389         inserted = true;
390       else if (dv->Dist < (*i)->Dist) {
391         inserted = true;
392         doms.insert(i, dv);
393       }
394     }
395     if (!inserted)
396       doms.push_back(dv);
397   }
398
399   // doms are now sorted in order of appearance. Try to merge them all, giving
400   // priority to the latest ones.
401   DomainValue *dv = 0;
402   while (!doms.empty()) {
403     if (!dv) {
404       dv = doms.pop_back_val();
405       continue;
406     }
407
408     DomainValue *latest = doms.pop_back_val();
409     if (Merge(dv, latest)) continue;
410
411     // If latest didn't merge, it is useless now. Kill all registers using it.
412     for (SmallVector<int,4>::iterator i=used.begin(), e=used.end(); i != e; ++i)
413       if (LiveRegs[*i] == latest)
414         Kill(*i);
415   }
416
417   // dv is the DomainValue we are going to use for this instruction.
418   if (!dv)
419     dv = Alloc();
420   dv->Dist = Distance;
421   dv->AvailableDomains = available;
422   dv->Instrs.push_back(mi);
423
424   // Finally set all defs and non-collapsed uses to dv.
425   for (unsigned i = 0, e = mi->getDesc().getNumOperands(); i != e; ++i) {
426     MachineOperand &mo = mi->getOperand(i);
427     if (!mo.isReg()) continue;
428     int rx = RegIndex(mo.getReg());
429     if (rx < 0) continue;
430     if (!LiveRegs || !LiveRegs[rx] || (mo.isDef() && LiveRegs[rx]!=dv)) {
431       Kill(rx);
432       SetLiveReg(rx, dv);
433     }
434   }
435 }
436
437 void SSEDomainFixPass::visitGenericInstr(MachineInstr *mi) {
438   // Process explicit defs, kill any XMM registers redefined.
439   for (unsigned i = 0, e = mi->getDesc().getNumDefs(); i != e; ++i) {
440     MachineOperand &mo = mi->getOperand(i);
441     if (!mo.isReg()) continue;
442     int rx = RegIndex(mo.getReg());
443     if (rx < 0) continue;
444     Kill(rx);
445   }
446 }
447
448 bool SSEDomainFixPass::runOnMachineFunction(MachineFunction &mf) {
449   MF = &mf;
450   TII = MF->getTarget().getInstrInfo();
451   TRI = MF->getTarget().getRegisterInfo();
452   MBB = 0;
453   LiveRegs = 0;
454   Distance = 0;
455   assert(NumRegs == RC->getNumRegs() && "Bad regclass");
456
457   // If no XMM registers are used in the function, we can skip it completely.
458   bool anyregs = false;
459   for (TargetRegisterClass::const_iterator I = RC->begin(), E = RC->end();
460        I != E; ++I)
461     if (MF->getRegInfo().isPhysRegUsed(*I)) {
462       anyregs = true;
463       break;
464     }
465   if (!anyregs) return false;
466
467   // Initialize the AliasMap on the first use.
468   if (AliasMap.empty()) {
469     // Given a PhysReg, AliasMap[PhysReg] is either the relevant index into RC,
470     // or -1.
471     AliasMap.resize(TRI->getNumRegs(), -1);
472     for (unsigned i = 0, e = RC->getNumRegs(); i != e; ++i)
473       for (const unsigned *AI = TRI->getOverlaps(RC->getRegister(i)); *AI; ++AI)
474         AliasMap[*AI] = i;
475   }
476
477   MachineBasicBlock *Entry = MF->begin();
478   SmallPtrSet<MachineBasicBlock*, 16> Visited;
479   for (df_ext_iterator<MachineBasicBlock*, SmallPtrSet<MachineBasicBlock*, 16> >
480          DFI = df_ext_begin(Entry, Visited), DFE = df_ext_end(Entry, Visited);
481          DFI != DFE; ++DFI) {
482     MBB = *DFI;
483     enterBasicBlock();
484     for (MachineBasicBlock::iterator I = MBB->begin(), E = MBB->end(); I != E;
485         ++I) {
486       MachineInstr *mi = I;
487       if (mi->isDebugValue()) continue;
488       ++Distance;
489       std::pair<uint16_t, uint16_t> domp = TII->getExecutionDomain(mi);
490       if (domp.first)
491         if (domp.second)
492           visitSoftInstr(mi, domp.second);
493         else
494           visitHardInstr(mi, domp.first);
495       else if (LiveRegs)
496         visitGenericInstr(mi);
497     }
498
499     // Save live registers at end of MBB - used by enterBasicBlock().
500     if (LiveRegs)
501       LiveOuts.insert(std::make_pair(MBB, LiveRegs));
502     LiveRegs = 0;
503   }
504
505   // Clear the LiveOuts vectors. Should we also collapse any remaining
506   // DomainValues?
507   for (LiveOutMap::const_iterator i = LiveOuts.begin(), e = LiveOuts.end();
508          i != e; ++i)
509     delete[] i->second;
510   LiveOuts.clear();
511   Avail.clear();
512   Allocator.DestroyAll();
513
514   return false;
515 }
516
517 FunctionPass *
518 llvm::createExecutionDependencyFixPass(const TargetRegisterClass *RC) {
519   return new SSEDomainFixPass(RC);
520 }