1 //===- SSEDomainFix.cpp - Use proper int/float domain for SSE ---*- 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 SSEDomainFix pass.
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.
17 // This pass changes the variant instructions to minimize domain crossings.
19 //===----------------------------------------------------------------------===//
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"
33 /// A DomainValue is a bit like LiveIntervals' ValNo, but it also keeps track
34 /// of execution domains.
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
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
50 // Basic reference counting.
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;
58 // Position of the last defining instruction.
61 // Twiddleable instructions using or defining these registers.
62 SmallVector<MachineInstr*, 8> Instrs;
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(); }
68 // Is domain available?
69 bool hasDomain(unsigned domain) const {
70 return AvailableDomains & (1u << domain);
73 // Mark domain as available.
74 void addDomain(unsigned domain) {
75 AvailableDomains |= 1u << domain;
78 // Restrict to a single domain available.
79 void setSingleDomain(unsigned domain) {
80 AvailableDomains = 1u << domain;
83 // Return bitmask of domains that are available and in mask.
84 unsigned getCommonDomains(unsigned mask) const {
85 return AvailableDomains & mask;
88 // First domain available.
89 unsigned getFirstDomain() const {
90 return CountTrailingZeros_32(AvailableDomains);
93 DomainValue() { clear(); }
96 Refs = AvailableDomains = Dist = 0;
103 class SSEDomainFixPass : public MachineFunctionPass {
105 SpecificBumpPtrAllocator<DomainValue> Allocator;
106 SmallVector<DomainValue*,16> Avail;
108 const TargetRegisterClass *const RC;
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;
121 SSEDomainFixPass(const TargetRegisterClass *rc)
122 : MachineFunctionPass(ID), RC(rc), NumRegs(RC->getNumRegs()) {}
124 virtual void getAnalysisUsage(AnalysisUsage &AU) const {
125 AU.setPreservesAll();
126 MachineFunctionPass::getAnalysisUsage(AU);
129 virtual bool runOnMachineFunction(MachineFunction &MF);
131 virtual const char *getPassName() const {
132 return "SSE execution domain fixup";
137 int RegIndex(unsigned Reg);
139 // DomainValue allocation.
140 DomainValue *Alloc(int domain = -1);
141 void Recycle(DomainValue*);
143 // LiveRegs manipulations.
144 void SetLiveReg(int rx, DomainValue *DV);
146 void Force(int rx, unsigned domain);
147 void Collapse(DomainValue *dv, unsigned domain);
148 bool Merge(DomainValue *A, DomainValue *B);
150 void enterBasicBlock();
151 void visitGenericInstr(MachineInstr*);
152 void visitSoftInstr(MachineInstr*, unsigned mask);
153 void visitHardInstr(MachineInstr*, unsigned domain);
157 char SSEDomainFixPass::ID = 0;
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];
166 DomainValue *SSEDomainFixPass::Alloc(int domain) {
167 DomainValue *dv = Avail.empty() ?
168 new(Allocator.Allocate()) DomainValue :
169 Avail.pop_back_val();
172 dv->addDomain(domain);
176 void SSEDomainFixPass::Recycle(DomainValue *dv) {
177 assert(dv && "Cannot recycle NULL");
182 /// Set LiveRegs[rx] = dv, updating reference counts.
183 void SSEDomainFixPass::SetLiveReg(int rx, DomainValue *dv) {
184 assert(unsigned(rx) < NumRegs && "Invalid index");
186 LiveRegs = new DomainValue*[NumRegs];
187 std::fill(LiveRegs, LiveRegs+NumRegs, (DomainValue*)0);
190 if (LiveRegs[rx] == dv)
193 assert(LiveRegs[rx]->Refs && "Bad refcount");
194 if (--LiveRegs[rx]->Refs == 0) Recycle(LiveRegs[rx]);
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;
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());
213 /// Force register rx into domain.
214 void SSEDomainFixPass::Force(int rx, unsigned domain) {
215 assert(unsigned(rx) < NumRegs && "Invalid index");
217 if (LiveRegs && (dv = LiveRegs[rx])) {
218 if (dv->isCollapsed())
219 dv->addDomain(domain);
220 else if (dv->hasDomain(domain))
221 Collapse(dv, domain);
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);
230 // Set up basic collapsed DomainValue.
231 SetLiveReg(rx, Alloc(domain));
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");
240 // Collapse all the instructions.
241 while (!dv->Instrs.empty())
242 TII->setExecutionDomain(dv->Instrs.pop_back_val(), domain);
243 dv->setSingleDomain(domain);
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));
252 /// Merge - All instructions and registers in B are moved to A, and B is
254 bool SSEDomainFixPass::Merge(DomainValue *A, DomainValue *B) {
255 assert(!A->isCollapsed() && "Cannot merge into collapsed");
256 assert(!B->isCollapsed() && "Cannot merge from collapsed");
259 // Restrict to the domains that A and B have in common.
260 unsigned common = A->getCommonDomains(B->AvailableDomains);
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)
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];
284 if (!LiveRegs || !LiveRegs[rx]) {
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);
298 // Currently open, merge in predecessor.
299 if (!pdv->isCollapsed())
300 Merge(LiveRegs[rx], pdv);
302 Force(rx, pdv->getFirstDomain());
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;
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;
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;
337 // Scan the explicit use operands for incoming domains.
338 SmallVector<int, 4> used;
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;
356 // Open DomainValue is compatible, save it for merging.
359 // Open DomainValue is not compatible with instruction. It is useless
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);
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) {
378 DomainValue *dv = LiveRegs[rx];
379 // This useless DomainValue could have been missed above.
380 if (!dv->getCommonDomains(available)) {
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) {
390 else if (dv->Dist < (*i)->Dist) {
399 // doms are now sorted in order of appearance. Try to merge them all, giving
400 // priority to the latest ones.
402 while (!doms.empty()) {
404 dv = doms.pop_back_val();
408 DomainValue *latest = doms.pop_back_val();
409 if (Merge(dv, latest)) continue;
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)
417 // dv is the DomainValue we are going to use for this instruction.
421 dv->AvailableDomains = available;
422 dv->Instrs.push_back(mi);
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)) {
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;
448 bool SSEDomainFixPass::runOnMachineFunction(MachineFunction &mf) {
450 TII = MF->getTarget().getInstrInfo();
451 TRI = MF->getTarget().getRegisterInfo();
455 assert(NumRegs == RC->getNumRegs() && "Bad regclass");
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();
461 if (MF->getRegInfo().isPhysRegUsed(*I)) {
465 if (!anyregs) return false;
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,
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)
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);
484 for (MachineBasicBlock::iterator I = MBB->begin(), E = MBB->end(); I != E;
486 MachineInstr *mi = I;
487 if (mi->isDebugValue()) continue;
489 std::pair<uint16_t, uint16_t> domp = TII->getExecutionDomain(mi);
492 visitSoftInstr(mi, domp.second);
494 visitHardInstr(mi, domp.first);
496 visitGenericInstr(mi);
499 // Save live registers at end of MBB - used by enterBasicBlock().
501 LiveOuts.insert(std::make_pair(MBB, LiveRegs));
505 // Clear the LiveOuts vectors. Should we also collapse any remaining
507 for (LiveOutMap::const_iterator i = LiveOuts.begin(), e = LiveOuts.end();
512 Allocator.DestroyAll();
518 llvm::createExecutionDependencyFixPass(const TargetRegisterClass *RC) {
519 return new SSEDomainFixPass(RC);