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