the various ConstantExpr::get*Ty methods existed to work with issues around
[llvm/stm8.git] / lib / CodeGen / LiveRangeEdit.cpp
blobb385fb36bbf1a7836e3516d7e39942ca11aaf178
1 //===--- LiveRangeEdit.cpp - Basic tools for editing a register live range --===//
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 // The LiveRangeEdit class represents changes done to a virtual register when it
11 // is spilled or split.
12 //===----------------------------------------------------------------------===//
14 #define DEBUG_TYPE "regalloc"
15 #include "LiveRangeEdit.h"
16 #include "VirtRegMap.h"
17 #include "llvm/ADT/SetVector.h"
18 #include "llvm/ADT/Statistic.h"
19 #include "llvm/CodeGen/CalcSpillWeights.h"
20 #include "llvm/CodeGen/LiveIntervalAnalysis.h"
21 #include "llvm/CodeGen/MachineRegisterInfo.h"
22 #include "llvm/Target/TargetInstrInfo.h"
23 #include "llvm/Support/Debug.h"
24 #include "llvm/Support/raw_ostream.h"
26 using namespace llvm;
28 STATISTIC(NumDCEDeleted, "Number of instructions deleted by DCE");
29 STATISTIC(NumDCEFoldedLoads, "Number of single use loads folded after DCE");
30 STATISTIC(NumFracRanges, "Number of live ranges fractured by DCE");
32 LiveInterval &LiveRangeEdit::createFrom(unsigned OldReg,
33 LiveIntervals &LIS,
34 VirtRegMap &VRM) {
35 MachineRegisterInfo &MRI = VRM.getRegInfo();
36 unsigned VReg = MRI.createVirtualRegister(MRI.getRegClass(OldReg));
37 VRM.grow();
38 VRM.setIsSplitFromReg(VReg, VRM.getOriginal(OldReg));
39 LiveInterval &LI = LIS.getOrCreateInterval(VReg);
40 newRegs_.push_back(&LI);
41 return LI;
44 bool LiveRangeEdit::checkRematerializable(VNInfo *VNI,
45 const MachineInstr *DefMI,
46 const TargetInstrInfo &tii,
47 AliasAnalysis *aa) {
48 assert(DefMI && "Missing instruction");
49 scannedRemattable_ = true;
50 if (!tii.isTriviallyReMaterializable(DefMI, aa))
51 return false;
52 remattable_.insert(VNI);
53 return true;
56 void LiveRangeEdit::scanRemattable(LiveIntervals &lis,
57 const TargetInstrInfo &tii,
58 AliasAnalysis *aa) {
59 for (LiveInterval::vni_iterator I = parent_.vni_begin(),
60 E = parent_.vni_end(); I != E; ++I) {
61 VNInfo *VNI = *I;
62 if (VNI->isUnused())
63 continue;
64 MachineInstr *DefMI = lis.getInstructionFromIndex(VNI->def);
65 if (!DefMI)
66 continue;
67 checkRematerializable(VNI, DefMI, tii, aa);
69 scannedRemattable_ = true;
72 bool LiveRangeEdit::anyRematerializable(LiveIntervals &lis,
73 const TargetInstrInfo &tii,
74 AliasAnalysis *aa) {
75 if (!scannedRemattable_)
76 scanRemattable(lis, tii, aa);
77 return !remattable_.empty();
80 /// allUsesAvailableAt - Return true if all registers used by OrigMI at
81 /// OrigIdx are also available with the same value at UseIdx.
82 bool LiveRangeEdit::allUsesAvailableAt(const MachineInstr *OrigMI,
83 SlotIndex OrigIdx,
84 SlotIndex UseIdx,
85 LiveIntervals &lis) {
86 OrigIdx = OrigIdx.getUseIndex();
87 UseIdx = UseIdx.getUseIndex();
88 for (unsigned i = 0, e = OrigMI->getNumOperands(); i != e; ++i) {
89 const MachineOperand &MO = OrigMI->getOperand(i);
90 if (!MO.isReg() || !MO.getReg() || MO.isDef())
91 continue;
92 // Reserved registers are OK.
93 if (MO.isUndef() || !lis.hasInterval(MO.getReg()))
94 continue;
95 // We cannot depend on virtual registers in uselessRegs_.
96 if (uselessRegs_)
97 for (unsigned ui = 0, ue = uselessRegs_->size(); ui != ue; ++ui)
98 if ((*uselessRegs_)[ui]->reg == MO.getReg())
99 return false;
101 LiveInterval &li = lis.getInterval(MO.getReg());
102 const VNInfo *OVNI = li.getVNInfoAt(OrigIdx);
103 if (!OVNI)
104 continue;
105 if (OVNI != li.getVNInfoAt(UseIdx))
106 return false;
108 return true;
111 bool LiveRangeEdit::canRematerializeAt(Remat &RM,
112 SlotIndex UseIdx,
113 bool cheapAsAMove,
114 LiveIntervals &lis) {
115 assert(scannedRemattable_ && "Call anyRematerializable first");
117 // Use scanRemattable info.
118 if (!remattable_.count(RM.ParentVNI))
119 return false;
121 // No defining instruction provided.
122 SlotIndex DefIdx;
123 if (RM.OrigMI)
124 DefIdx = lis.getInstructionIndex(RM.OrigMI);
125 else {
126 DefIdx = RM.ParentVNI->def;
127 RM.OrigMI = lis.getInstructionFromIndex(DefIdx);
128 assert(RM.OrigMI && "No defining instruction for remattable value");
131 // If only cheap remats were requested, bail out early.
132 if (cheapAsAMove && !RM.OrigMI->getDesc().isAsCheapAsAMove())
133 return false;
135 // Verify that all used registers are available with the same values.
136 if (!allUsesAvailableAt(RM.OrigMI, DefIdx, UseIdx, lis))
137 return false;
139 return true;
142 SlotIndex LiveRangeEdit::rematerializeAt(MachineBasicBlock &MBB,
143 MachineBasicBlock::iterator MI,
144 unsigned DestReg,
145 const Remat &RM,
146 LiveIntervals &lis,
147 const TargetInstrInfo &tii,
148 const TargetRegisterInfo &tri,
149 bool Late) {
150 assert(RM.OrigMI && "Invalid remat");
151 tii.reMaterialize(MBB, MI, DestReg, 0, RM.OrigMI, tri);
152 rematted_.insert(RM.ParentVNI);
153 return lis.getSlotIndexes()->insertMachineInstrInMaps(--MI, Late)
154 .getDefIndex();
157 void LiveRangeEdit::eraseVirtReg(unsigned Reg, LiveIntervals &LIS) {
158 if (delegate_ && delegate_->LRE_CanEraseVirtReg(Reg))
159 LIS.removeInterval(Reg);
162 bool LiveRangeEdit::foldAsLoad(LiveInterval *LI,
163 SmallVectorImpl<MachineInstr*> &Dead,
164 MachineRegisterInfo &MRI,
165 LiveIntervals &LIS,
166 const TargetInstrInfo &TII) {
167 MachineInstr *DefMI = 0, *UseMI = 0;
169 // Check that there is a single def and a single use.
170 for (MachineRegisterInfo::reg_nodbg_iterator I = MRI.reg_nodbg_begin(LI->reg),
171 E = MRI.reg_nodbg_end(); I != E; ++I) {
172 MachineOperand &MO = I.getOperand();
173 MachineInstr *MI = MO.getParent();
174 if (MO.isDef()) {
175 if (DefMI && DefMI != MI)
176 return false;
177 if (!MI->getDesc().canFoldAsLoad())
178 return false;
179 DefMI = MI;
180 } else if (!MO.isUndef()) {
181 if (UseMI && UseMI != MI)
182 return false;
183 // FIXME: Targets don't know how to fold subreg uses.
184 if (MO.getSubReg())
185 return false;
186 UseMI = MI;
189 if (!DefMI || !UseMI)
190 return false;
192 DEBUG(dbgs() << "Try to fold single def: " << *DefMI
193 << " into single use: " << *UseMI);
195 SmallVector<unsigned, 8> Ops;
196 if (UseMI->readsWritesVirtualRegister(LI->reg, &Ops).second)
197 return false;
199 MachineInstr *FoldMI = TII.foldMemoryOperand(UseMI, Ops, DefMI);
200 if (!FoldMI)
201 return false;
202 DEBUG(dbgs() << " folded: " << *FoldMI);
203 LIS.ReplaceMachineInstrInMaps(UseMI, FoldMI);
204 UseMI->eraseFromParent();
205 DefMI->addRegisterDead(LI->reg, 0);
206 Dead.push_back(DefMI);
207 ++NumDCEFoldedLoads;
208 return true;
211 void LiveRangeEdit::eliminateDeadDefs(SmallVectorImpl<MachineInstr*> &Dead,
212 LiveIntervals &LIS, VirtRegMap &VRM,
213 const TargetInstrInfo &TII) {
214 SetVector<LiveInterval*,
215 SmallVector<LiveInterval*, 8>,
216 SmallPtrSet<LiveInterval*, 8> > ToShrink;
217 MachineRegisterInfo &MRI = VRM.getRegInfo();
219 for (;;) {
220 // Erase all dead defs.
221 while (!Dead.empty()) {
222 MachineInstr *MI = Dead.pop_back_val();
223 assert(MI->allDefsAreDead() && "Def isn't really dead");
224 SlotIndex Idx = LIS.getInstructionIndex(MI).getDefIndex();
226 // Never delete inline asm.
227 if (MI->isInlineAsm()) {
228 DEBUG(dbgs() << "Won't delete: " << Idx << '\t' << *MI);
229 continue;
232 // Use the same criteria as DeadMachineInstructionElim.
233 bool SawStore = false;
234 if (!MI->isSafeToMove(&TII, 0, SawStore)) {
235 DEBUG(dbgs() << "Can't delete: " << Idx << '\t' << *MI);
236 continue;
239 DEBUG(dbgs() << "Deleting dead def " << Idx << '\t' << *MI);
241 // Check for live intervals that may shrink
242 for (MachineInstr::mop_iterator MOI = MI->operands_begin(),
243 MOE = MI->operands_end(); MOI != MOE; ++MOI) {
244 if (!MOI->isReg())
245 continue;
246 unsigned Reg = MOI->getReg();
247 if (!TargetRegisterInfo::isVirtualRegister(Reg))
248 continue;
249 LiveInterval &LI = LIS.getInterval(Reg);
251 // Shrink read registers, unless it is likely to be expensive and
252 // unlikely to change anything. We typically don't want to shrink the
253 // PIC base register that has lots of uses everywhere.
254 // Always shrink COPY uses that probably come from live range splitting.
255 if (MI->readsVirtualRegister(Reg) &&
256 (MI->isCopy() || MOI->isDef() || MRI.hasOneNonDBGUse(Reg) ||
257 LI.killedAt(Idx)))
258 ToShrink.insert(&LI);
260 // Remove defined value.
261 if (MOI->isDef()) {
262 if (VNInfo *VNI = LI.getVNInfoAt(Idx)) {
263 if (delegate_)
264 delegate_->LRE_WillShrinkVirtReg(LI.reg);
265 LI.removeValNo(VNI);
266 if (LI.empty()) {
267 ToShrink.remove(&LI);
268 eraseVirtReg(Reg, LIS);
274 if (delegate_)
275 delegate_->LRE_WillEraseInstruction(MI);
276 LIS.RemoveMachineInstrFromMaps(MI);
277 MI->eraseFromParent();
278 ++NumDCEDeleted;
281 if (ToShrink.empty())
282 break;
284 // Shrink just one live interval. Then delete new dead defs.
285 LiveInterval *LI = ToShrink.back();
286 ToShrink.pop_back();
287 if (foldAsLoad(LI, Dead, MRI, LIS, TII))
288 continue;
289 if (delegate_)
290 delegate_->LRE_WillShrinkVirtReg(LI->reg);
291 if (!LIS.shrinkToUses(LI, &Dead))
292 continue;
294 // LI may have been separated, create new intervals.
295 LI->RenumberValues(LIS);
296 ConnectedVNInfoEqClasses ConEQ(LIS);
297 unsigned NumComp = ConEQ.Classify(LI);
298 if (NumComp <= 1)
299 continue;
300 ++NumFracRanges;
301 bool IsOriginal = VRM.getOriginal(LI->reg) == LI->reg;
302 DEBUG(dbgs() << NumComp << " components: " << *LI << '\n');
303 SmallVector<LiveInterval*, 8> Dups(1, LI);
304 for (unsigned i = 1; i != NumComp; ++i) {
305 Dups.push_back(&createFrom(LI->reg, LIS, VRM));
306 // If LI is an original interval that hasn't been split yet, make the new
307 // intervals their own originals instead of referring to LI. The original
308 // interval must contain all the split products, and LI doesn't.
309 if (IsOriginal)
310 VRM.setIsSplitFromReg(Dups.back()->reg, 0);
311 if (delegate_)
312 delegate_->LRE_DidCloneVirtReg(Dups.back()->reg, LI->reg);
314 ConEQ.Distribute(&Dups[0], MRI);
318 void LiveRangeEdit::calculateRegClassAndHint(MachineFunction &MF,
319 LiveIntervals &LIS,
320 const MachineLoopInfo &Loops) {
321 VirtRegAuxInfo VRAI(MF, LIS, Loops);
322 for (iterator I = begin(), E = end(); I != E; ++I) {
323 LiveInterval &LI = **I;
324 VRAI.CalculateRegClass(LI.reg);
325 VRAI.CalculateWeightAndHint(LI);