1 //===- ExecutionDepsFix.cpp - Fix execution dependecy issues ----*- C++ -*-===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
10 // This file contains the execution dependency fix pass.
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
19 // This pass changes the variant instructions to minimize domain crossings.
21 //===----------------------------------------------------------------------===//
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"
35 /// A DomainValue is a bit like LiveIntervals' ValNo, but it also keeps track
36 /// of execution domains.
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
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
52 // Basic reference counting.
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;
60 // Position of the last defining instruction.
63 // Twiddleable instructions using or defining these registers.
64 SmallVector<MachineInstr*, 8> Instrs;
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(); }
70 // Is domain available?
71 bool hasDomain(unsigned domain) const {
72 return AvailableDomains & (1u << domain);
75 // Mark domain as available.
76 void addDomain(unsigned domain) {
77 AvailableDomains |= 1u << domain;
80 // Restrict to a single domain available.
81 void setSingleDomain(unsigned domain) {
82 AvailableDomains = 1u << domain;
85 // Return bitmask of domains that are available and in mask.
86 unsigned getCommonDomains(unsigned mask) const {
87 return AvailableDomains & mask;
90 // First domain available.
91 unsigned getFirstDomain() const {
92 return CountTrailingZeros_32(AvailableDomains);
95 DomainValue() { clear(); }
98 Refs = AvailableDomains = Dist = 0;
105 class ExeDepsFix : public MachineFunctionPass {
107 SpecificBumpPtrAllocator<DomainValue> Allocator;
108 SmallVector<DomainValue*,16> Avail;
110 const TargetRegisterClass *const RC;
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;
122 ExeDepsFix(const TargetRegisterClass *rc)
123 : MachineFunctionPass(ID), RC(rc), NumRegs(RC->getNumRegs()) {}
125 virtual void getAnalysisUsage(AnalysisUsage &AU) const {
126 AU.setPreservesAll();
127 MachineFunctionPass::getAnalysisUsage(AU);
130 virtual bool runOnMachineFunction(MachineFunction &MF);
132 virtual const char *getPassName() const {
133 return "Execution dependency fix";
138 int RegIndex(unsigned Reg);
140 // DomainValue allocation.
141 DomainValue *Alloc(int domain = -1);
142 void Recycle(DomainValue*);
144 // LiveRegs manipulations.
145 void SetLiveReg(int rx, DomainValue *DV);
147 void Force(int rx, unsigned domain);
148 void Collapse(DomainValue *dv, unsigned domain);
149 bool Merge(DomainValue *A, DomainValue *B);
151 void enterBasicBlock(MachineBasicBlock*);
152 void visitGenericInstr(MachineInstr*);
153 void visitSoftInstr(MachineInstr*, unsigned mask);
154 void visitHardInstr(MachineInstr*, unsigned domain);
158 char ExeDepsFix::ID = 0;
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];
167 DomainValue *ExeDepsFix::Alloc(int domain) {
168 DomainValue *dv = Avail.empty() ?
169 new(Allocator.Allocate()) DomainValue :
170 Avail.pop_back_val();
173 dv->addDomain(domain);
177 void ExeDepsFix::Recycle(DomainValue *dv) {
178 assert(dv && "Cannot recycle NULL");
183 /// Set LiveRegs[rx] = dv, updating reference counts.
184 void ExeDepsFix::SetLiveReg(int rx, DomainValue *dv) {
185 assert(unsigned(rx) < NumRegs && "Invalid index");
187 LiveRegs = new DomainValue*[NumRegs];
188 std::fill(LiveRegs, LiveRegs+NumRegs, (DomainValue*)0);
191 if (LiveRegs[rx] == dv)
194 assert(LiveRegs[rx]->Refs && "Bad refcount");
195 if (--LiveRegs[rx]->Refs == 0) Recycle(LiveRegs[rx]);
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;
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());
214 /// Force register rx into domain.
215 void ExeDepsFix::Force(int rx, unsigned domain) {
216 assert(unsigned(rx) < NumRegs && "Invalid index");
218 if (LiveRegs && (dv = LiveRegs[rx])) {
219 if (dv->isCollapsed())
220 dv->addDomain(domain);
221 else if (dv->hasDomain(domain))
222 Collapse(dv, domain);
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);
231 // Set up basic collapsed DomainValue.
232 SetLiveReg(rx, Alloc(domain));
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");
241 // Collapse all the instructions.
242 while (!dv->Instrs.empty())
243 TII->setExecutionDomain(dv->Instrs.pop_back_val(), domain);
244 dv->setSingleDomain(domain);
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));
253 /// Merge - All instructions and registers in B are moved to A, and B is
255 bool ExeDepsFix::Merge(DomainValue *A, DomainValue *B) {
256 assert(!A->isCollapsed() && "Cannot merge into collapsed");
257 assert(!B->isCollapsed() && "Cannot merge from collapsed");
260 // Restrict to the domains that A and B have in common.
261 unsigned common = A->getCommonDomains(B->AvailableDomains);
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)
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];
285 if (!LiveRegs || !LiveRegs[rx]) {
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);
299 // Currently open, merge in predecessor.
300 if (!pdv->isCollapsed())
301 Merge(LiveRegs[rx], pdv);
303 Force(rx, pdv->getFirstDomain());
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;
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;
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;
338 // Scan the explicit use operands for incoming domains.
339 SmallVector<int, 4> used;
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;
357 // Open DomainValue is compatible, save it for merging.
360 // Open DomainValue is not compatible with instruction. It is useless
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);
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) {
379 DomainValue *dv = LiveRegs[rx];
380 // This useless DomainValue could have been missed above.
381 if (!dv->getCommonDomains(available)) {
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) {
391 else if (dv->Dist < (*i)->Dist) {
400 // doms are now sorted in order of appearance. Try to merge them all, giving
401 // priority to the latest ones.
403 while (!doms.empty()) {
405 dv = doms.pop_back_val();
409 DomainValue *latest = doms.pop_back_val();
410 if (Merge(dv, latest)) continue;
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)
418 // dv is the DomainValue we are going to use for this instruction.
422 dv->AvailableDomains = available;
423 dv->Instrs.push_back(mi);
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)) {
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;
449 bool ExeDepsFix::runOnMachineFunction(MachineFunction &mf) {
451 TII = MF->getTarget().getInstrInfo();
452 TRI = MF->getTarget().getRegisterInfo();
455 assert(NumRegs == RC->getNumRegs() && "Bad regclass");
457 // If no relevant registers are used in the function, we can skip it
459 bool anyregs = false;
460 for (TargetRegisterClass::const_iterator I = RC->begin(), E = RC->end();
462 if (MF->getRegInfo().isPhysRegUsed(*I)) {
466 if (!anyregs) return false;
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,
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)
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);
483 MachineBasicBlock *MBB = *DFI;
484 enterBasicBlock(MBB);
485 for (MachineBasicBlock::iterator I = MBB->begin(), E = MBB->end(); I != E;
487 MachineInstr *mi = I;
488 if (mi->isDebugValue()) continue;
490 std::pair<uint16_t, uint16_t> domp = TII->getExecutionDomain(mi);
493 visitSoftInstr(mi, domp.second);
495 visitHardInstr(mi, domp.first);
497 visitGenericInstr(mi);
500 // Save live registers at end of MBB - used by enterBasicBlock().
502 LiveOuts.insert(std::make_pair(MBB, LiveRegs));
506 // Clear the LiveOuts vectors. Should we also collapse any remaining
508 for (LiveOutMap::const_iterator i = LiveOuts.begin(), e = LiveOuts.end();
513 Allocator.DestroyAll();
519 llvm::createExecutionDependencyFixPass(const TargetRegisterClass *RC) {
520 return new ExeDepsFix(RC);