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 "sse-domain-fix"
22 #include "X86InstrInfo.h"
23 #include "llvm/CodeGen/MachineFunctionPass.h"
24 #include "llvm/CodeGen/MachineRegisterInfo.h"
25 #include "llvm/ADT/DepthFirstIterator.h"
26 #include "llvm/Support/Allocator.h"
27 #include "llvm/Support/Debug.h"
28 #include "llvm/Support/raw_ostream.h"
31 /// A DomainValue is a bit like LiveIntervals' ValNo, but it also keeps track
32 /// of execution domains.
34 /// An open DomainValue represents a set of instructions that can still switch
35 /// execution domain. Multiple registers may refer to the same open
36 /// DomainValue - they will eventually be collapsed to the same execution
39 /// A collapsed DomainValue represents a single register that has been forced
40 /// into one of more execution domains. There is a separate collapsed
41 /// DomainValue for each register, but it may contain multiple execution
42 /// domains. A register value is initially created in a single execution
43 /// domain, but if we were forced to pay the penalty of a domain crossing, we
44 /// keep track of the fact the the register is now available in multiple
48 // Basic reference counting.
51 // Available domains. For an open DomainValue, it is the still possible
52 // domains for collapsing. For a collapsed DomainValue it is the domains where
53 // the register is available for free.
56 // Position of the last defining instruction.
59 // Twiddleable instructions using or defining these registers.
60 SmallVector<MachineInstr*, 8> Instrs;
62 // Collapsed DomainValue have no instructions to twiddle - it simply keeps
63 // track of the domains where the registers are already available.
64 bool collapsed() const { return Instrs.empty(); }
66 // Is any domain in mask available?
67 bool compat(unsigned mask) const {
71 // Mark domain as available.
72 void add(unsigned domain) {
76 // First domain available in mask.
77 unsigned firstDomain() const {
78 return CountTrailingZeros_32(Mask);
81 DomainValue() { clear(); }
84 Refs = Mask = Dist = 0;
90 static const unsigned NumRegs = 16;
93 class SSEDomainFixPass : public MachineFunctionPass {
95 SpecificBumpPtrAllocator<DomainValue> Allocator;
96 SmallVector<DomainValue*,16> Avail;
99 const X86InstrInfo *TII;
100 const TargetRegisterInfo *TRI;
101 MachineBasicBlock *MBB;
102 DomainValue **LiveRegs;
103 typedef DenseMap<MachineBasicBlock*,DomainValue**> LiveOutMap;
108 SSEDomainFixPass() : MachineFunctionPass(&ID) {}
110 virtual void getAnalysisUsage(AnalysisUsage &AU) const {
111 AU.setPreservesAll();
112 MachineFunctionPass::getAnalysisUsage(AU);
115 virtual bool runOnMachineFunction(MachineFunction &MF);
117 virtual const char *getPassName() const {
118 return "SSE execution domain fixup";
123 int RegIndex(unsigned Reg);
125 // DomainValue allocation.
126 DomainValue *Alloc(int domain = -1);
127 void Recycle(DomainValue*);
129 // LiveRegs manipulations.
130 void SetLiveReg(int rx, DomainValue *DV);
132 void Force(int rx, unsigned domain);
133 void Collapse(DomainValue *dv, unsigned domain);
134 bool Merge(DomainValue *A, DomainValue *B);
136 void enterBasicBlock();
137 void visitGenericInstr(MachineInstr*);
138 void visitSoftInstr(MachineInstr*, unsigned mask);
139 void visitHardInstr(MachineInstr*, unsigned domain);
143 char SSEDomainFixPass::ID = 0;
145 /// Translate TRI register number to an index into our smaller tables of
146 /// interesting registers. Return -1 for boring registers.
147 int SSEDomainFixPass::RegIndex(unsigned reg) {
148 // Registers are sorted lexicographically.
149 // We just need them to be consecutive, ordering doesn't matter.
150 assert(X86::XMM9 == X86::XMM0+NumRegs-1 && "Unexpected sort");
152 return reg < NumRegs ? reg : -1;
155 DomainValue *SSEDomainFixPass::Alloc(int domain) {
156 DomainValue *dv = Avail.empty() ?
157 new(Allocator.Allocate()) DomainValue :
158 Avail.pop_back_val();
161 dv->Mask = 1u << domain;
165 void SSEDomainFixPass::Recycle(DomainValue *dv) {
166 assert(dv && "Cannot recycle NULL");
171 /// Set LiveRegs[rx] = dv, updating reference counts.
172 void SSEDomainFixPass::SetLiveReg(int rx, DomainValue *dv) {
173 assert(unsigned(rx) < NumRegs && "Invalid index");
175 LiveRegs = (DomainValue**)calloc(sizeof(DomainValue*), NumRegs);
177 if (LiveRegs[rx] == dv)
180 assert(LiveRegs[rx]->Refs && "Bad refcount");
181 if (--LiveRegs[rx]->Refs == 0) Recycle(LiveRegs[rx]);
187 // Kill register rx, recycle or collapse any DomainValue.
188 void SSEDomainFixPass::Kill(int rx) {
189 assert(unsigned(rx) < NumRegs && "Invalid index");
190 if (!LiveRegs || !LiveRegs[rx]) return;
192 // Before killing the last reference to an open DomainValue, collapse it to
193 // the first available domain.
194 if (LiveRegs[rx]->Refs == 1 && !LiveRegs[rx]->collapsed())
195 Collapse(LiveRegs[rx], LiveRegs[rx]->firstDomain());
200 /// Force register rx into domain.
201 void SSEDomainFixPass::Force(int rx, unsigned domain) {
202 assert(unsigned(rx) < NumRegs && "Invalid index");
204 if (LiveRegs && (dv = LiveRegs[rx])) {
208 Collapse(dv, domain);
210 // Set up basic collapsed DomainValue.
211 SetLiveReg(rx, Alloc(domain));
215 /// Collapse open DomainValue into given domain. If there are multiple
216 /// registers using dv, they each get a unique collapsed DomainValue.
217 void SSEDomainFixPass::Collapse(DomainValue *dv, unsigned domain) {
218 assert(dv->compat(1u << domain) && "Cannot collapse");
220 // Collapse all the instructions.
221 while (!dv->Instrs.empty()) {
222 MachineInstr *mi = dv->Instrs.back();
223 TII->SetSSEDomain(mi, domain);
224 dv->Instrs.pop_back();
226 dv->Mask = 1u << domain;
228 // If there are multiple users, give them new, unique DomainValues.
229 if (LiveRegs && dv->Refs > 1)
230 for (unsigned rx = 0; rx != NumRegs; ++rx)
231 if (LiveRegs[rx] == dv)
232 SetLiveReg(rx, Alloc(domain));
235 /// Merge - All instructions and registers in B are moved to A, and B is
237 bool SSEDomainFixPass::Merge(DomainValue *A, DomainValue *B) {
238 assert(!A->collapsed() && "Cannot merge into collapsed");
239 assert(!B->collapsed() && "Cannot merge from collapsed");
242 if (!A->compat(B->Mask))
245 A->Dist = std::max(A->Dist, B->Dist);
246 A->Instrs.append(B->Instrs.begin(), B->Instrs.end());
247 for (unsigned rx = 0; rx != NumRegs; ++rx)
248 if (LiveRegs[rx] == B)
253 void SSEDomainFixPass::enterBasicBlock() {
254 // Try to coalesce live-out registers from predecessors.
255 for (MachineBasicBlock::const_livein_iterator i = MBB->livein_begin(),
256 e = MBB->livein_end(); i != e; ++i) {
257 int rx = RegIndex(*i);
258 if (rx < 0) continue;
259 for (MachineBasicBlock::const_pred_iterator pi = MBB->pred_begin(),
260 pe = MBB->pred_end(); pi != pe; ++pi) {
261 LiveOutMap::const_iterator fi = LiveOuts.find(*pi);
262 if (fi == LiveOuts.end()) continue;
263 DomainValue *pdv = fi->second[rx];
265 if (!LiveRegs || !LiveRegs[rx]) {
270 // We have a live DomainValue from more than one predecessor.
271 if (LiveRegs[rx]->collapsed()) {
272 // We are already collapsed, but predecessor is not. Force him.
273 if (!pdv->collapsed())
274 Collapse(pdv, LiveRegs[rx]->firstDomain());
278 // Currently open, merge in predecessor.
279 if (!pdv->collapsed())
280 Merge(LiveRegs[rx], pdv);
282 Collapse(LiveRegs[rx], pdv->firstDomain());
287 // A hard instruction only works in one domain. All input registers will be
288 // forced into that domain.
289 void SSEDomainFixPass::visitHardInstr(MachineInstr *mi, unsigned domain) {
290 // Collapse all uses.
291 for (unsigned i = mi->getDesc().getNumDefs(),
292 e = mi->getDesc().getNumOperands(); i != e; ++i) {
293 MachineOperand &mo = mi->getOperand(i);
294 if (!mo.isReg()) continue;
295 int rx = RegIndex(mo.getReg());
296 if (rx < 0) continue;
300 // Kill all defs and force them.
301 for (unsigned i = 0, e = mi->getDesc().getNumDefs(); i != e; ++i) {
302 MachineOperand &mo = mi->getOperand(i);
303 if (!mo.isReg()) continue;
304 int rx = RegIndex(mo.getReg());
305 if (rx < 0) continue;
311 // A soft instruction can be changed to work in other domains given by mask.
312 void SSEDomainFixPass::visitSoftInstr(MachineInstr *mi, unsigned mask) {
313 // Scan the explicit use operands for incoming domains.
314 unsigned collmask = mask;
315 SmallVector<int, 4> used;
317 for (unsigned i = mi->getDesc().getNumDefs(),
318 e = mi->getDesc().getNumOperands(); i != e; ++i) {
319 MachineOperand &mo = mi->getOperand(i);
320 if (!mo.isReg()) continue;
321 int rx = RegIndex(mo.getReg());
322 if (rx < 0) continue;
323 if (DomainValue *dv = LiveRegs[rx]) {
324 // Is it possible to use this collapsed register for free?
325 if (dv->collapsed()) {
326 if (unsigned m = collmask & dv->Mask)
328 } else if (dv->compat(collmask))
335 // If the collapsed operands force a single domain, propagate the collapse.
336 if (isPowerOf2_32(collmask)) {
337 unsigned domain = CountTrailingZeros_32(collmask);
338 TII->SetSSEDomain(mi, domain);
339 visitHardInstr(mi, domain);
343 // Kill off any remaining uses that don't match collmask, and build a list of
344 // incoming DomainValue that we want to merge.
345 SmallVector<DomainValue*,4> doms;
346 for (SmallVector<int, 4>::iterator i=used.begin(), e=used.end(); i!=e; ++i) {
348 DomainValue *dv = LiveRegs[rx];
349 // This useless DomainValue could have been missed above.
350 if (!dv->compat(collmask)) {
354 // sorted, uniqued insert.
355 bool inserted = false;
356 for (SmallVector<DomainValue*,4>::iterator i = doms.begin(), e = doms.end();
357 i != e && !inserted; ++i) {
360 else if (dv->Dist < (*i)->Dist) {
369 // doms are now sorted in order of appearance. Try to merge them all, giving
370 // priority to the latest ones.
372 while (!doms.empty()) {
374 dv = doms.pop_back_val();
378 DomainValue *ThisDV = doms.pop_back_val();
379 if (Merge(dv, ThisDV)) continue;
381 for (SmallVector<int,4>::iterator i=used.begin(), e=used.end(); i != e; ++i)
382 if (LiveRegs[*i] == ThisDV)
386 // dv is the DomainValue we are going to use for this instruction.
391 dv->Instrs.push_back(mi);
393 // Finally set all defs and non-collapsed uses to dv.
394 for (unsigned i = 0, e = mi->getDesc().getNumOperands(); i != e; ++i) {
395 MachineOperand &mo = mi->getOperand(i);
396 if (!mo.isReg()) continue;
397 int rx = RegIndex(mo.getReg());
398 if (rx < 0) continue;
399 if (!LiveRegs || !LiveRegs[rx] || (mo.isDef() && LiveRegs[rx]!=dv)) {
406 void SSEDomainFixPass::visitGenericInstr(MachineInstr *mi) {
407 // Process explicit defs, kill any XMM registers redefined.
408 for (unsigned i = 0, e = mi->getDesc().getNumDefs(); i != e; ++i) {
409 MachineOperand &mo = mi->getOperand(i);
410 if (!mo.isReg()) continue;
411 int rx = RegIndex(mo.getReg());
412 if (rx < 0) continue;
417 bool SSEDomainFixPass::runOnMachineFunction(MachineFunction &mf) {
419 TII = static_cast<const X86InstrInfo*>(MF->getTarget().getInstrInfo());
420 TRI = MF->getTarget().getRegisterInfo();
424 assert(NumRegs == X86::VR128RegClass.getNumRegs() && "Bad regclass");
426 // If no XMM registers are used in the function, we can skip it completely.
427 bool anyregs = false;
428 for (TargetRegisterClass::const_iterator I = X86::VR128RegClass.begin(),
429 E = X86::VR128RegClass.end(); I != E; ++I)
430 if (MF->getRegInfo().isPhysRegUsed(*I)) {
434 if (!anyregs) return false;
436 MachineBasicBlock *Entry = MF->begin();
437 SmallPtrSet<MachineBasicBlock*, 16> Visited;
438 for (df_ext_iterator<MachineBasicBlock*, SmallPtrSet<MachineBasicBlock*, 16> >
439 DFI = df_ext_begin(Entry, Visited), DFE = df_ext_end(Entry, Visited);
443 for (MachineBasicBlock::iterator I = MBB->begin(), E = MBB->end(); I != E;
445 MachineInstr *mi = I;
446 if (mi->isDebugValue()) continue;
448 std::pair<uint16_t, uint16_t> domp = TII->GetSSEDomain(mi);
451 visitSoftInstr(mi, domp.second);
453 visitHardInstr(mi, domp.first);
455 visitGenericInstr(mi);
458 // Save live registers at end of MBB - used by enterBasicBlock().
460 LiveOuts.insert(std::make_pair(MBB, LiveRegs));
464 // Clear the LiveOuts vectors. Should we also collapse any remaining
466 for (LiveOutMap::const_iterator i = LiveOuts.begin(), e = LiveOuts.end();
471 Allocator.DestroyAll();
476 FunctionPass *llvm::createSSEDomainFixPass() {
477 return new SSEDomainFixPass();