1f6909028eab862ee569d49dc52f60f6a99f603c
[oota-llvm.git] / lib / CodeGen / CalcSpillWeights.cpp
1 //===------------------------ CalcSpillWeights.cpp ------------------------===//
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 #include "llvm/CodeGen/CalcSpillWeights.h"
11 #include "llvm/CodeGen/LiveIntervalAnalysis.h"
12 #include "llvm/CodeGen/MachineBlockFrequencyInfo.h"
13 #include "llvm/CodeGen/MachineFunction.h"
14 #include "llvm/CodeGen/MachineLoopInfo.h"
15 #include "llvm/CodeGen/MachineRegisterInfo.h"
16 #include "llvm/Support/Debug.h"
17 #include "llvm/Support/raw_ostream.h"
18 #include "llvm/Target/TargetInstrInfo.h"
19 #include "llvm/Target/TargetMachine.h"
20 #include "llvm/Target/TargetRegisterInfo.h"
21 #include "llvm/Target/TargetSubtargetInfo.h"
22 using namespace llvm;
23
24 #define DEBUG_TYPE "calcspillweights"
25
26 void llvm::calculateSpillWeightsAndHints(LiveIntervals &LIS,
27                            MachineFunction &MF,
28                            const MachineLoopInfo &MLI,
29                            const MachineBlockFrequencyInfo &MBFI,
30                            VirtRegAuxInfo::NormalizingFn norm) {
31   DEBUG(dbgs() << "********** Compute Spill Weights **********\n"
32                << "********** Function: " << MF.getName() << '\n');
33
34   MachineRegisterInfo &MRI = MF.getRegInfo();
35   VirtRegAuxInfo VRAI(MF, LIS, MLI, MBFI, norm);
36   for (unsigned i = 0, e = MRI.getNumVirtRegs(); i != e; ++i) {
37     unsigned Reg = TargetRegisterInfo::index2VirtReg(i);
38     if (MRI.reg_nodbg_empty(Reg))
39       continue;
40     VRAI.calculateSpillWeightAndHint(LIS.getInterval(Reg));
41   }
42 }
43
44 // Return the preferred allocation register for reg, given a COPY instruction.
45 static unsigned copyHint(const MachineInstr *mi, unsigned reg,
46                          const TargetRegisterInfo &tri,
47                          const MachineRegisterInfo &mri) {
48   unsigned sub, hreg, hsub;
49   if (mi->getOperand(0).getReg() == reg) {
50     sub = mi->getOperand(0).getSubReg();
51     hreg = mi->getOperand(1).getReg();
52     hsub = mi->getOperand(1).getSubReg();
53   } else {
54     sub = mi->getOperand(1).getSubReg();
55     hreg = mi->getOperand(0).getReg();
56     hsub = mi->getOperand(0).getSubReg();
57   }
58
59   if (!hreg)
60     return 0;
61
62   if (TargetRegisterInfo::isVirtualRegister(hreg))
63     return sub == hsub ? hreg : 0;
64
65   const TargetRegisterClass *rc = mri.getRegClass(reg);
66
67   // Only allow physreg hints in rc.
68   if (sub == 0)
69     return rc->contains(hreg) ? hreg : 0;
70
71   // reg:sub should match the physreg hreg.
72   return tri.getMatchingSuperReg(hreg, sub, rc);
73 }
74
75 // Check if all values in LI are rematerializable
76 static bool isRematerializable(const LiveInterval &LI,
77                                const LiveIntervals &LIS,
78                                const TargetInstrInfo &TII) {
79   for (LiveInterval::const_vni_iterator I = LI.vni_begin(), E = LI.vni_end();
80        I != E; ++I) {
81     const VNInfo *VNI = *I;
82     if (VNI->isUnused())
83       continue;
84     if (VNI->isPHIDef())
85       return false;
86
87     MachineInstr *MI = LIS.getInstructionFromIndex(VNI->def);
88     assert(MI && "Dead valno in interval");
89
90     if (!TII.isTriviallyReMaterializable(MI, LIS.getAliasAnalysis()))
91       return false;
92   }
93   return true;
94 }
95
96 void
97 VirtRegAuxInfo::calculateSpillWeightAndHint(LiveInterval &li) {
98   MachineRegisterInfo &mri = MF.getRegInfo();
99   const TargetRegisterInfo &tri = *MF.getSubtarget().getRegisterInfo();
100   MachineBasicBlock *mbb = nullptr;
101   MachineLoop *loop = nullptr;
102   bool isExiting = false;
103   float totalWeight = 0;
104   SmallPtrSet<MachineInstr*, 8> visited;
105
106   // Find the best physreg hint and the best virtreg hint.
107   float bestPhys = 0, bestVirt = 0;
108   unsigned hintPhys = 0, hintVirt = 0;
109
110   // Don't recompute a target specific hint.
111   bool noHint = mri.getRegAllocationHint(li.reg).first != 0;
112
113   // Don't recompute spill weight for an unspillable register.
114   bool Spillable = li.isSpillable();
115
116   for (MachineRegisterInfo::reg_instr_iterator
117        I = mri.reg_instr_begin(li.reg), E = mri.reg_instr_end();
118        I != E; ) {
119     MachineInstr *mi = &*(I++);
120     if (mi->isIdentityCopy() || mi->isImplicitDef() || mi->isDebugValue())
121       continue;
122     if (!visited.insert(mi))
123       continue;
124
125     float weight = 1.0f;
126     if (Spillable) {
127       // Get loop info for mi.
128       if (mi->getParent() != mbb) {
129         mbb = mi->getParent();
130         loop = Loops.getLoopFor(mbb);
131         isExiting = loop ? loop->isLoopExiting(mbb) : false;
132       }
133
134       // Calculate instr weight.
135       bool reads, writes;
136       std::tie(reads, writes) = mi->readsWritesVirtualRegister(li.reg);
137       weight = LiveIntervals::getSpillWeight(
138         writes, reads, &MBFI, mi);
139
140       // Give extra weight to what looks like a loop induction variable update.
141       if (writes && isExiting && LIS.isLiveOutOfMBB(li, mbb))
142         weight *= 3;
143
144       totalWeight += weight;
145     }
146
147     // Get allocation hints from copies.
148     if (noHint || !mi->isCopy())
149       continue;
150     unsigned hint = copyHint(mi, li.reg, tri, mri);
151     if (!hint)
152       continue;
153     // Force hweight onto the stack so that x86 doesn't add hidden precision,
154     // making the comparison incorrectly pass (i.e., 1 > 1 == true??).
155     //
156     // FIXME: we probably shouldn't use floats at all.
157     volatile float hweight = Hint[hint] += weight;
158     if (TargetRegisterInfo::isPhysicalRegister(hint)) {
159       if (hweight > bestPhys && mri.isAllocatable(hint))
160         bestPhys = hweight, hintPhys = hint;
161     } else {
162       if (hweight > bestVirt)
163         bestVirt = hweight, hintVirt = hint;
164     }
165   }
166
167   Hint.clear();
168
169   // Always prefer the physreg hint.
170   if (unsigned hint = hintPhys ? hintPhys : hintVirt) {
171     mri.setRegAllocationHint(li.reg, 0, hint);
172     // Weakly boost the spill weight of hinted registers.
173     totalWeight *= 1.01F;
174   }
175
176   // If the live interval was already unspillable, leave it that way.
177   if (!Spillable)
178     return;
179
180   // Mark li as unspillable if all live ranges are tiny.
181   if (li.isZeroLength(LIS.getSlotIndexes())) {
182     li.markNotSpillable();
183     return;
184   }
185
186   // If all of the definitions of the interval are re-materializable,
187   // it is a preferred candidate for spilling.
188   // FIXME: this gets much more complicated once we support non-trivial
189   // re-materialization.
190   if (isRematerializable(li, LIS, *MF.getSubtarget().getInstrInfo()))
191     totalWeight *= 0.5F;
192
193   li.weight = normalize(totalWeight, li.getSize());
194 }