VirtRegMap.cpp revision ce665bd2e2b581ab0858d1afe359192bac96b868
1//===-- llvm/CodeGen/VirtRegMap.cpp - Virtual Register Map ----------------===//
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// This file implements the VirtRegMap class.
11//
12// It also contains implementations of the Spiller interface, which, given a
13// virtual register map and a machine function, eliminates all virtual
14// references by replacing them with physical register references - adding spill
15// code as necessary.
16//
17//===----------------------------------------------------------------------===//
18
19#define DEBUG_TYPE "virtregmap"
20#include "VirtRegMap.h"
21#include "llvm/Function.h"
22#include "llvm/CodeGen/LiveIntervalAnalysis.h"
23#include "llvm/CodeGen/MachineFrameInfo.h"
24#include "llvm/CodeGen/MachineFunction.h"
25#include "llvm/CodeGen/MachineInstrBuilder.h"
26#include "llvm/CodeGen/MachineRegisterInfo.h"
27#include "llvm/Target/TargetMachine.h"
28#include "llvm/Target/TargetInstrInfo.h"
29#include "llvm/Target/TargetRegisterInfo.h"
30#include "llvm/Support/CommandLine.h"
31#include "llvm/Support/Compiler.h"
32#include "llvm/Support/Debug.h"
33#include "llvm/Support/raw_ostream.h"
34#include "llvm/ADT/BitVector.h"
35#include "llvm/ADT/DenseMap.h"
36#include "llvm/ADT/DepthFirstIterator.h"
37#include "llvm/ADT/Statistic.h"
38#include "llvm/ADT/STLExtras.h"
39#include "llvm/ADT/SmallSet.h"
40#include <algorithm>
41using namespace llvm;
42
43STATISTIC(NumSpills  , "Number of register spills");
44
45//===----------------------------------------------------------------------===//
46//  VirtRegMap implementation
47//===----------------------------------------------------------------------===//
48
49char VirtRegMap::ID = 0;
50
51INITIALIZE_PASS(VirtRegMap, "virtregmap", "Virtual Register Map", false, false)
52
53bool VirtRegMap::runOnMachineFunction(MachineFunction &mf) {
54  MRI = &mf.getRegInfo();
55  TII = mf.getTarget().getInstrInfo();
56  TRI = mf.getTarget().getRegisterInfo();
57  MF = &mf;
58
59  ReMatId = MAX_STACK_SLOT+1;
60  LowSpillSlot = HighSpillSlot = NO_STACK_SLOT;
61
62  Virt2PhysMap.clear();
63  Virt2StackSlotMap.clear();
64  Virt2ReMatIdMap.clear();
65  Virt2SplitMap.clear();
66  Virt2SplitKillMap.clear();
67  ReMatMap.clear();
68  ImplicitDefed.clear();
69  SpillSlotToUsesMap.clear();
70  MI2VirtMap.clear();
71  SpillPt2VirtMap.clear();
72  RestorePt2VirtMap.clear();
73  EmergencySpillMap.clear();
74  EmergencySpillSlots.clear();
75
76  SpillSlotToUsesMap.resize(8);
77  ImplicitDefed.resize(MF->getRegInfo().getLastVirtReg()+1-
78                       TargetRegisterInfo::FirstVirtualRegister);
79
80  allocatableRCRegs.clear();
81  for (TargetRegisterInfo::regclass_iterator I = TRI->regclass_begin(),
82         E = TRI->regclass_end(); I != E; ++I)
83    allocatableRCRegs.insert(std::make_pair(*I,
84                                            TRI->getAllocatableSet(mf, *I)));
85
86  grow();
87
88  return false;
89}
90
91void VirtRegMap::grow() {
92  unsigned LastVirtReg = MF->getRegInfo().getLastVirtReg();
93  Virt2PhysMap.grow(LastVirtReg);
94  Virt2StackSlotMap.grow(LastVirtReg);
95  Virt2ReMatIdMap.grow(LastVirtReg);
96  Virt2SplitMap.grow(LastVirtReg);
97  Virt2SplitKillMap.grow(LastVirtReg);
98  ReMatMap.grow(LastVirtReg);
99  ImplicitDefed.resize(LastVirtReg-TargetRegisterInfo::FirstVirtualRegister+1);
100}
101
102unsigned VirtRegMap::getRegAllocPref(unsigned virtReg) {
103  std::pair<unsigned, unsigned> Hint = MRI->getRegAllocationHint(virtReg);
104  unsigned physReg = Hint.second;
105  if (physReg &&
106      TargetRegisterInfo::isVirtualRegister(physReg) && hasPhys(physReg))
107    physReg = getPhys(physReg);
108  if (Hint.first == 0)
109    return (physReg && TargetRegisterInfo::isPhysicalRegister(physReg))
110      ? physReg : 0;
111  return TRI->ResolveRegAllocHint(Hint.first, physReg, *MF);
112}
113
114int VirtRegMap::assignVirt2StackSlot(unsigned virtReg) {
115  assert(TargetRegisterInfo::isVirtualRegister(virtReg));
116  assert(Virt2StackSlotMap[virtReg] == NO_STACK_SLOT &&
117         "attempt to assign stack slot to already spilled register");
118  const TargetRegisterClass* RC = MF->getRegInfo().getRegClass(virtReg);
119  int SS = MF->getFrameInfo()->CreateSpillStackObject(RC->getSize(),
120                                                 RC->getAlignment());
121  if (LowSpillSlot == NO_STACK_SLOT)
122    LowSpillSlot = SS;
123  if (HighSpillSlot == NO_STACK_SLOT || SS > HighSpillSlot)
124    HighSpillSlot = SS;
125  unsigned Idx = SS-LowSpillSlot;
126  while (Idx >= SpillSlotToUsesMap.size())
127    SpillSlotToUsesMap.resize(SpillSlotToUsesMap.size()*2);
128  Virt2StackSlotMap[virtReg] = SS;
129  ++NumSpills;
130  return SS;
131}
132
133void VirtRegMap::assignVirt2StackSlot(unsigned virtReg, int SS) {
134  assert(TargetRegisterInfo::isVirtualRegister(virtReg));
135  assert(Virt2StackSlotMap[virtReg] == NO_STACK_SLOT &&
136         "attempt to assign stack slot to already spilled register");
137  assert((SS >= 0 ||
138          (SS >= MF->getFrameInfo()->getObjectIndexBegin())) &&
139         "illegal fixed frame index");
140  Virt2StackSlotMap[virtReg] = SS;
141}
142
143int VirtRegMap::assignVirtReMatId(unsigned virtReg) {
144  assert(TargetRegisterInfo::isVirtualRegister(virtReg));
145  assert(Virt2ReMatIdMap[virtReg] == NO_STACK_SLOT &&
146         "attempt to assign re-mat id to already spilled register");
147  Virt2ReMatIdMap[virtReg] = ReMatId;
148  return ReMatId++;
149}
150
151void VirtRegMap::assignVirtReMatId(unsigned virtReg, int id) {
152  assert(TargetRegisterInfo::isVirtualRegister(virtReg));
153  assert(Virt2ReMatIdMap[virtReg] == NO_STACK_SLOT &&
154         "attempt to assign re-mat id to already spilled register");
155  Virt2ReMatIdMap[virtReg] = id;
156}
157
158int VirtRegMap::getEmergencySpillSlot(const TargetRegisterClass *RC) {
159  std::map<const TargetRegisterClass*, int>::iterator I =
160    EmergencySpillSlots.find(RC);
161  if (I != EmergencySpillSlots.end())
162    return I->second;
163  int SS = MF->getFrameInfo()->CreateSpillStackObject(RC->getSize(),
164                                                 RC->getAlignment());
165  if (LowSpillSlot == NO_STACK_SLOT)
166    LowSpillSlot = SS;
167  if (HighSpillSlot == NO_STACK_SLOT || SS > HighSpillSlot)
168    HighSpillSlot = SS;
169  EmergencySpillSlots[RC] = SS;
170  return SS;
171}
172
173void VirtRegMap::addSpillSlotUse(int FI, MachineInstr *MI) {
174  if (!MF->getFrameInfo()->isFixedObjectIndex(FI)) {
175    // If FI < LowSpillSlot, this stack reference was produced by
176    // instruction selection and is not a spill
177    if (FI >= LowSpillSlot) {
178      assert(FI >= 0 && "Spill slot index should not be negative!");
179      assert((unsigned)FI-LowSpillSlot < SpillSlotToUsesMap.size()
180             && "Invalid spill slot");
181      SpillSlotToUsesMap[FI-LowSpillSlot].insert(MI);
182    }
183  }
184}
185
186void VirtRegMap::virtFolded(unsigned VirtReg, MachineInstr *OldMI,
187                            MachineInstr *NewMI, ModRef MRInfo) {
188  // Move previous memory references folded to new instruction.
189  MI2VirtMapTy::iterator IP = MI2VirtMap.lower_bound(NewMI);
190  for (MI2VirtMapTy::iterator I = MI2VirtMap.lower_bound(OldMI),
191         E = MI2VirtMap.end(); I != E && I->first == OldMI; ) {
192    MI2VirtMap.insert(IP, std::make_pair(NewMI, I->second));
193    MI2VirtMap.erase(I++);
194  }
195
196  // add new memory reference
197  MI2VirtMap.insert(IP, std::make_pair(NewMI, std::make_pair(VirtReg, MRInfo)));
198}
199
200void VirtRegMap::virtFolded(unsigned VirtReg, MachineInstr *MI, ModRef MRInfo) {
201  MI2VirtMapTy::iterator IP = MI2VirtMap.lower_bound(MI);
202  MI2VirtMap.insert(IP, std::make_pair(MI, std::make_pair(VirtReg, MRInfo)));
203}
204
205void VirtRegMap::RemoveMachineInstrFromMaps(MachineInstr *MI) {
206  for (unsigned i = 0, e = MI->getNumOperands(); i != e; ++i) {
207    MachineOperand &MO = MI->getOperand(i);
208    if (!MO.isFI())
209      continue;
210    int FI = MO.getIndex();
211    if (MF->getFrameInfo()->isFixedObjectIndex(FI))
212      continue;
213    // This stack reference was produced by instruction selection and
214    // is not a spill
215    if (FI < LowSpillSlot)
216      continue;
217    assert((unsigned)FI-LowSpillSlot < SpillSlotToUsesMap.size()
218           && "Invalid spill slot");
219    SpillSlotToUsesMap[FI-LowSpillSlot].erase(MI);
220  }
221  MI2VirtMap.erase(MI);
222  SpillPt2VirtMap.erase(MI);
223  RestorePt2VirtMap.erase(MI);
224  EmergencySpillMap.erase(MI);
225}
226
227/// FindUnusedRegisters - Gather a list of allocatable registers that
228/// have not been allocated to any virtual register.
229bool VirtRegMap::FindUnusedRegisters(LiveIntervals* LIs) {
230  unsigned NumRegs = TRI->getNumRegs();
231  UnusedRegs.reset();
232  UnusedRegs.resize(NumRegs);
233
234  BitVector Used(NumRegs);
235  for (unsigned i = TargetRegisterInfo::FirstVirtualRegister,
236         e = MF->getRegInfo().getLastVirtReg(); i <= e; ++i)
237    if (Virt2PhysMap[i] != (unsigned)VirtRegMap::NO_PHYS_REG)
238      Used.set(Virt2PhysMap[i]);
239
240  BitVector Allocatable = TRI->getAllocatableSet(*MF);
241  bool AnyUnused = false;
242  for (unsigned Reg = 1; Reg < NumRegs; ++Reg) {
243    if (Allocatable[Reg] && !Used[Reg] && !LIs->hasInterval(Reg)) {
244      bool ReallyUnused = true;
245      for (const unsigned *AS = TRI->getAliasSet(Reg); *AS; ++AS) {
246        if (Used[*AS] || LIs->hasInterval(*AS)) {
247          ReallyUnused = false;
248          break;
249        }
250      }
251      if (ReallyUnused) {
252        AnyUnused = true;
253        UnusedRegs.set(Reg);
254      }
255    }
256  }
257
258  return AnyUnused;
259}
260
261void VirtRegMap::print(raw_ostream &OS, const Module* M) const {
262  const TargetRegisterInfo* TRI = MF->getTarget().getRegisterInfo();
263  const MachineRegisterInfo &MRI = MF->getRegInfo();
264
265  OS << "********** REGISTER MAP **********\n";
266  for (unsigned i = TargetRegisterInfo::FirstVirtualRegister,
267         e = MF->getRegInfo().getLastVirtReg(); i <= e; ++i) {
268    if (Virt2PhysMap[i] != (unsigned)VirtRegMap::NO_PHYS_REG)
269      OS << "[reg" << i << " -> " << TRI->getName(Virt2PhysMap[i])
270         << "] " << MRI.getRegClass(i)->getName() << "\n";
271  }
272
273  for (unsigned i = TargetRegisterInfo::FirstVirtualRegister,
274         e = MF->getRegInfo().getLastVirtReg(); i <= e; ++i)
275    if (Virt2StackSlotMap[i] != VirtRegMap::NO_STACK_SLOT)
276      OS << "[reg" << i << " -> fi#" << Virt2StackSlotMap[i]
277         << "] " << MRI.getRegClass(i)->getName() << "\n";
278  OS << '\n';
279}
280
281void VirtRegMap::dump() const {
282  print(dbgs());
283}
284