1 //===-- RegAllocLinearScan.cpp - Linear Scan register allocator -----------===//
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 implements a linear scan register allocator.
12 //===----------------------------------------------------------------------===//
14 #define DEBUG_TYPE "regalloc"
15 #include "VirtRegMap.h"
16 #include "VirtRegRewriter.h"
17 #include "llvm/Function.h"
18 #include "llvm/CodeGen/LiveIntervalAnalysis.h"
19 #include "llvm/CodeGen/LiveStackAnalysis.h"
20 #include "llvm/CodeGen/MachineFunctionPass.h"
21 #include "llvm/CodeGen/MachineInstr.h"
22 #include "llvm/CodeGen/MachineLoopInfo.h"
23 #include "llvm/CodeGen/MachineRegisterInfo.h"
24 #include "llvm/CodeGen/Passes.h"
25 #include "llvm/CodeGen/RegAllocRegistry.h"
26 #include "llvm/CodeGen/RegisterCoalescer.h"
27 #include "llvm/Target/TargetRegisterInfo.h"
28 #include "llvm/Target/TargetMachine.h"
29 #include "llvm/Target/TargetOptions.h"
30 #include "llvm/Target/TargetInstrInfo.h"
31 #include "llvm/ADT/EquivalenceClasses.h"
32 #include "llvm/ADT/SmallSet.h"
33 #include "llvm/ADT/Statistic.h"
34 #include "llvm/ADT/STLExtras.h"
35 #include "llvm/Support/Debug.h"
36 #include "llvm/Support/Compiler.h"
44 STATISTIC(NumIters
, "Number of iterations performed");
45 STATISTIC(NumBacktracks
, "Number of times we had to backtrack");
46 STATISTIC(NumCoalesce
, "Number of copies coalesced");
47 STATISTIC(NumDowngrade
, "Number of registers downgraded");
50 NewHeuristic("new-spilling-heuristic",
51 cl::desc("Use new spilling heuristic"),
52 cl::init(false), cl::Hidden
);
55 PreSplitIntervals("pre-alloc-split",
56 cl::desc("Pre-register allocation live interval splitting"),
57 cl::init(false), cl::Hidden
);
59 static RegisterRegAlloc
60 linearscanRegAlloc("linearscan", "linear scan register allocator",
61 createLinearScanRegisterAllocator
);
64 struct VISIBILITY_HIDDEN RALinScan
: public MachineFunctionPass
{
66 RALinScan() : MachineFunctionPass(&ID
) {}
68 typedef std::pair
<LiveInterval
*, LiveInterval::iterator
> IntervalPtr
;
69 typedef SmallVector
<IntervalPtr
, 32> IntervalPtrs
;
71 /// RelatedRegClasses - This structure is built the first time a function is
72 /// compiled, and keeps track of which register classes have registers that
73 /// belong to multiple classes or have aliases that are in other classes.
74 EquivalenceClasses
<const TargetRegisterClass
*> RelatedRegClasses
;
75 DenseMap
<unsigned, const TargetRegisterClass
*> OneClassForEachPhysReg
;
77 // NextReloadMap - For each register in the map, it maps to the another
78 // register which is defined by a reload from the same stack slot and
79 // both reloads are in the same basic block.
80 DenseMap
<unsigned, unsigned> NextReloadMap
;
82 // DowngradedRegs - A set of registers which are being "downgraded", i.e.
83 // un-favored for allocation.
84 SmallSet
<unsigned, 8> DowngradedRegs
;
86 // DowngradeMap - A map from virtual registers to physical registers being
87 // downgraded for the virtual registers.
88 DenseMap
<unsigned, unsigned> DowngradeMap
;
91 MachineRegisterInfo
* mri_
;
92 const TargetMachine
* tm_
;
93 const TargetRegisterInfo
* tri_
;
94 const TargetInstrInfo
* tii_
;
95 BitVector allocatableRegs_
;
98 const MachineLoopInfo
*loopInfo
;
100 /// handled_ - Intervals are added to the handled_ set in the order of their
101 /// start value. This is uses for backtracking.
102 std::vector
<LiveInterval
*> handled_
;
104 /// fixed_ - Intervals that correspond to machine registers.
108 /// active_ - Intervals that are currently being processed, and which have a
109 /// live range active for the current point.
110 IntervalPtrs active_
;
112 /// inactive_ - Intervals that are currently being processed, but which have
113 /// a hold at the current point.
114 IntervalPtrs inactive_
;
116 typedef std::priority_queue
<LiveInterval
*,
117 SmallVector
<LiveInterval
*, 64>,
118 greater_ptr
<LiveInterval
> > IntervalHeap
;
119 IntervalHeap unhandled_
;
121 /// regUse_ - Tracks register usage.
122 SmallVector
<unsigned, 32> regUse_
;
123 SmallVector
<unsigned, 32> regUseBackUp_
;
125 /// vrm_ - Tracks register assignments.
128 std::auto_ptr
<VirtRegRewriter
> rewriter_
;
131 virtual const char* getPassName() const {
132 return "Linear Scan Register Allocator";
135 virtual void getAnalysisUsage(AnalysisUsage
&AU
) const {
136 AU
.addRequired
<LiveIntervals
>();
138 AU
.addRequiredID(StrongPHIEliminationID
);
139 // Make sure PassManager knows which analyses to make available
140 // to coalescing and which analyses coalescing invalidates.
141 AU
.addRequiredTransitive
<RegisterCoalescer
>();
142 if (PreSplitIntervals
)
143 AU
.addRequiredID(PreAllocSplittingID
);
144 AU
.addRequired
<LiveStacks
>();
145 AU
.addPreserved
<LiveStacks
>();
146 AU
.addRequired
<MachineLoopInfo
>();
147 AU
.addPreserved
<MachineLoopInfo
>();
148 AU
.addRequired
<VirtRegMap
>();
149 AU
.addPreserved
<VirtRegMap
>();
150 AU
.addPreservedID(MachineDominatorsID
);
151 MachineFunctionPass::getAnalysisUsage(AU
);
154 /// runOnMachineFunction - register allocate the whole function
155 bool runOnMachineFunction(MachineFunction
&);
158 /// linearScan - the linear scan algorithm
161 /// initIntervalSets - initialize the interval sets.
163 void initIntervalSets();
165 /// processActiveIntervals - expire old intervals and move non-overlapping
166 /// ones to the inactive list.
167 void processActiveIntervals(unsigned CurPoint
);
169 /// processInactiveIntervals - expire old intervals and move overlapping
170 /// ones to the active list.
171 void processInactiveIntervals(unsigned CurPoint
);
173 /// hasNextReloadInterval - Return the next liveinterval that's being
174 /// defined by a reload from the same SS as the specified one.
175 LiveInterval
*hasNextReloadInterval(LiveInterval
*cur
);
177 /// DowngradeRegister - Downgrade a register for allocation.
178 void DowngradeRegister(LiveInterval
*li
, unsigned Reg
);
180 /// UpgradeRegister - Upgrade a register for allocation.
181 void UpgradeRegister(unsigned Reg
);
183 /// assignRegOrStackSlotAtInterval - assign a register if one
184 /// is available, or spill.
185 void assignRegOrStackSlotAtInterval(LiveInterval
* cur
);
187 void updateSpillWeights(std::vector
<float> &Weights
,
188 unsigned reg
, float weight
,
189 const TargetRegisterClass
*RC
);
191 /// findIntervalsToSpill - Determine the intervals to spill for the
192 /// specified interval. It's passed the physical registers whose spill
193 /// weight is the lowest among all the registers whose live intervals
194 /// conflict with the interval.
195 void findIntervalsToSpill(LiveInterval
*cur
,
196 std::vector
<std::pair
<unsigned,float> > &Candidates
,
198 SmallVector
<LiveInterval
*, 8> &SpillIntervals
);
200 /// attemptTrivialCoalescing - If a simple interval is defined by a copy,
201 /// try allocate the definition the same register as the source register
202 /// if the register is not defined during live time of the interval. This
203 /// eliminate a copy. This is used to coalesce copies which were not
204 /// coalesced away before allocation either due to dest and src being in
205 /// different register classes or because the coalescer was overly
207 unsigned attemptTrivialCoalescing(LiveInterval
&cur
, unsigned Reg
);
210 /// Register usage / availability tracking helpers.
214 regUse_
.resize(tri_
->getNumRegs(), 0);
215 regUseBackUp_
.resize(tri_
->getNumRegs(), 0);
218 void finalizeRegUses() {
220 // Verify all the registers are "freed".
222 for (unsigned i
= 0, e
= tri_
->getNumRegs(); i
!= e
; ++i
) {
223 if (regUse_
[i
] != 0) {
224 cerr
<< tri_
->getName(i
) << " is still in use!\n";
232 regUseBackUp_
.clear();
235 void addRegUse(unsigned physReg
) {
236 assert(TargetRegisterInfo::isPhysicalRegister(physReg
) &&
237 "should be physical register!");
239 for (const unsigned* as
= tri_
->getAliasSet(physReg
); *as
; ++as
)
243 void delRegUse(unsigned physReg
) {
244 assert(TargetRegisterInfo::isPhysicalRegister(physReg
) &&
245 "should be physical register!");
246 assert(regUse_
[physReg
] != 0);
248 for (const unsigned* as
= tri_
->getAliasSet(physReg
); *as
; ++as
) {
249 assert(regUse_
[*as
] != 0);
254 bool isRegAvail(unsigned physReg
) const {
255 assert(TargetRegisterInfo::isPhysicalRegister(physReg
) &&
256 "should be physical register!");
257 return regUse_
[physReg
] == 0;
260 void backUpRegUses() {
261 regUseBackUp_
= regUse_
;
264 void restoreRegUses() {
265 regUse_
= regUseBackUp_
;
269 /// Register handling helpers.
272 /// getFreePhysReg - return a free physical register for this virtual
273 /// register interval if we have one, otherwise return 0.
274 unsigned getFreePhysReg(LiveInterval
* cur
);
275 unsigned getFreePhysReg(const TargetRegisterClass
*RC
,
276 unsigned MaxInactiveCount
,
277 SmallVector
<unsigned, 256> &inactiveCounts
,
280 /// assignVirt2StackSlot - assigns this virtual register to a
281 /// stack slot. returns the stack slot
282 int assignVirt2StackSlot(unsigned virtReg
);
284 void ComputeRelatedRegClasses();
286 template <typename ItTy
>
287 void printIntervals(const char* const str
, ItTy i
, ItTy e
) const {
288 if (str
) DOUT
<< str
<< " intervals:\n";
289 for (; i
!= e
; ++i
) {
290 DOUT
<< "\t" << *i
->first
<< " -> ";
291 unsigned reg
= i
->first
->reg
;
292 if (TargetRegisterInfo::isVirtualRegister(reg
)) {
293 reg
= vrm_
->getPhys(reg
);
295 DOUT
<< tri_
->getName(reg
) << '\n';
299 char RALinScan::ID
= 0;
302 static RegisterPass
<RALinScan
>
303 X("linearscan-regalloc", "Linear Scan Register Allocator");
305 void RALinScan::ComputeRelatedRegClasses() {
306 // First pass, add all reg classes to the union, and determine at least one
307 // reg class that each register is in.
308 bool HasAliases
= false;
309 for (TargetRegisterInfo::regclass_iterator RCI
= tri_
->regclass_begin(),
310 E
= tri_
->regclass_end(); RCI
!= E
; ++RCI
) {
311 RelatedRegClasses
.insert(*RCI
);
312 for (TargetRegisterClass::iterator I
= (*RCI
)->begin(), E
= (*RCI
)->end();
314 HasAliases
= HasAliases
|| *tri_
->getAliasSet(*I
) != 0;
316 const TargetRegisterClass
*&PRC
= OneClassForEachPhysReg
[*I
];
318 // Already processed this register. Just make sure we know that
319 // multiple register classes share a register.
320 RelatedRegClasses
.unionSets(PRC
, *RCI
);
327 // Second pass, now that we know conservatively what register classes each reg
328 // belongs to, add info about aliases. We don't need to do this for targets
329 // without register aliases.
331 for (DenseMap
<unsigned, const TargetRegisterClass
*>::iterator
332 I
= OneClassForEachPhysReg
.begin(), E
= OneClassForEachPhysReg
.end();
334 for (const unsigned *AS
= tri_
->getAliasSet(I
->first
); *AS
; ++AS
)
335 RelatedRegClasses
.unionSets(I
->second
, OneClassForEachPhysReg
[*AS
]);
338 /// attemptTrivialCoalescing - If a simple interval is defined by a copy,
339 /// try allocate the definition the same register as the source register
340 /// if the register is not defined during live time of the interval. This
341 /// eliminate a copy. This is used to coalesce copies which were not
342 /// coalesced away before allocation either due to dest and src being in
343 /// different register classes or because the coalescer was overly
345 unsigned RALinScan::attemptTrivialCoalescing(LiveInterval
&cur
, unsigned Reg
) {
346 if ((cur
.preference
&& cur
.preference
== Reg
) || !cur
.containsOneValue())
349 VNInfo
*vni
= cur
.begin()->valno
;
350 if (!vni
->def
|| vni
->def
== ~1U || vni
->def
== ~0U)
352 MachineInstr
*CopyMI
= li_
->getInstructionFromIndex(vni
->def
);
353 unsigned SrcReg
, DstReg
, SrcSubReg
, DstSubReg
, PhysReg
;
355 !tii_
->isMoveInstr(*CopyMI
, SrcReg
, DstReg
, SrcSubReg
, DstSubReg
))
358 if (TargetRegisterInfo::isVirtualRegister(SrcReg
)) {
359 if (!vrm_
->isAssignedReg(SrcReg
))
361 PhysReg
= vrm_
->getPhys(SrcReg
);
366 const TargetRegisterClass
*RC
= mri_
->getRegClass(cur
.reg
);
367 if (!RC
->contains(PhysReg
))
371 if (!li_
->conflictsWithPhysRegDef(cur
, *vrm_
, PhysReg
)) {
372 DOUT
<< "Coalescing: " << cur
<< " -> " << tri_
->getName(PhysReg
)
374 vrm_
->clearVirt(cur
.reg
);
375 vrm_
->assignVirt2Phys(cur
.reg
, PhysReg
);
377 // Remove unnecessary kills since a copy does not clobber the register.
378 if (li_
->hasInterval(SrcReg
)) {
379 LiveInterval
&SrcLI
= li_
->getInterval(SrcReg
);
380 for (MachineRegisterInfo::reg_iterator I
= mri_
->reg_begin(cur
.reg
),
381 E
= mri_
->reg_end(); I
!= E
; ++I
) {
382 MachineOperand
&O
= I
.getOperand();
383 if (!O
.isUse() || !O
.isKill())
385 MachineInstr
*MI
= &*I
;
386 if (SrcLI
.liveAt(li_
->getDefIndex(li_
->getInstructionIndex(MI
))))
398 bool RALinScan::runOnMachineFunction(MachineFunction
&fn
) {
400 mri_
= &fn
.getRegInfo();
401 tm_
= &fn
.getTarget();
402 tri_
= tm_
->getRegisterInfo();
403 tii_
= tm_
->getInstrInfo();
404 allocatableRegs_
= tri_
->getAllocatableSet(fn
);
405 li_
= &getAnalysis
<LiveIntervals
>();
406 ls_
= &getAnalysis
<LiveStacks
>();
407 loopInfo
= &getAnalysis
<MachineLoopInfo
>();
409 // We don't run the coalescer here because we have no reason to
410 // interact with it. If the coalescer requires interaction, it
411 // won't do anything. If it doesn't require interaction, we assume
412 // it was run as a separate pass.
414 // If this is the first function compiled, compute the related reg classes.
415 if (RelatedRegClasses
.empty())
416 ComputeRelatedRegClasses();
418 // Also resize register usage trackers.
421 vrm_
= &getAnalysis
<VirtRegMap
>();
422 if (!rewriter_
.get()) rewriter_
.reset(createVirtRegRewriter());
428 // Rewrite spill code and update the PhysRegsUsed set.
429 rewriter_
->runOnMachineFunction(*mf_
, *vrm_
, li_
);
431 assert(unhandled_
.empty() && "Unhandled live intervals remain!");
439 NextReloadMap
.clear();
440 DowngradedRegs
.clear();
441 DowngradeMap
.clear();
446 /// initIntervalSets - initialize the interval sets.
448 void RALinScan::initIntervalSets()
450 assert(unhandled_
.empty() && fixed_
.empty() &&
451 active_
.empty() && inactive_
.empty() &&
452 "interval sets should be empty on initialization");
454 handled_
.reserve(li_
->getNumIntervals());
456 for (LiveIntervals::iterator i
= li_
->begin(), e
= li_
->end(); i
!= e
; ++i
) {
457 if (TargetRegisterInfo::isPhysicalRegister(i
->second
->reg
)) {
458 mri_
->setPhysRegUsed(i
->second
->reg
);
459 fixed_
.push_back(std::make_pair(i
->second
, i
->second
->begin()));
461 unhandled_
.push(i
->second
);
465 void RALinScan::linearScan()
467 // linear scan algorithm
468 DOUT
<< "********** LINEAR SCAN **********\n";
469 DOUT
<< "********** Function: " << mf_
->getFunction()->getName() << '\n';
471 DEBUG(printIntervals("fixed", fixed_
.begin(), fixed_
.end()));
473 while (!unhandled_
.empty()) {
474 // pick the interval with the earliest start point
475 LiveInterval
* cur
= unhandled_
.top();
478 DOUT
<< "\n*** CURRENT ***: " << *cur
<< '\n';
481 processActiveIntervals(cur
->beginNumber());
482 processInactiveIntervals(cur
->beginNumber());
484 assert(TargetRegisterInfo::isVirtualRegister(cur
->reg
) &&
485 "Can only allocate virtual registers!");
488 // Allocating a virtual register. try to find a free
489 // physical register or spill an interval (possibly this one) in order to
491 assignRegOrStackSlotAtInterval(cur
);
493 DEBUG(printIntervals("active", active_
.begin(), active_
.end()));
494 DEBUG(printIntervals("inactive", inactive_
.begin(), inactive_
.end()));
497 // Expire any remaining active intervals
498 while (!active_
.empty()) {
499 IntervalPtr
&IP
= active_
.back();
500 unsigned reg
= IP
.first
->reg
;
501 DOUT
<< "\tinterval " << *IP
.first
<< " expired\n";
502 assert(TargetRegisterInfo::isVirtualRegister(reg
) &&
503 "Can only allocate virtual registers!");
504 reg
= vrm_
->getPhys(reg
);
509 // Expire any remaining inactive intervals
510 DEBUG(for (IntervalPtrs::reverse_iterator
511 i
= inactive_
.rbegin(); i
!= inactive_
.rend(); ++i
)
512 DOUT
<< "\tinterval " << *i
->first
<< " expired\n");
515 // Add live-ins to every BB except for entry. Also perform trivial coalescing.
516 MachineFunction::iterator EntryMBB
= mf_
->begin();
517 SmallVector
<MachineBasicBlock
*, 8> LiveInMBBs
;
518 for (LiveIntervals::iterator i
= li_
->begin(), e
= li_
->end(); i
!= e
; ++i
) {
519 LiveInterval
&cur
= *i
->second
;
521 bool isPhys
= TargetRegisterInfo::isPhysicalRegister(cur
.reg
);
524 else if (vrm_
->isAssignedReg(cur
.reg
))
525 Reg
= attemptTrivialCoalescing(cur
, vrm_
->getPhys(cur
.reg
));
528 // Ignore splited live intervals.
529 if (!isPhys
&& vrm_
->getPreSplitReg(cur
.reg
))
531 for (LiveInterval::Ranges::const_iterator I
= cur
.begin(), E
= cur
.end();
533 const LiveRange
&LR
= *I
;
534 if (li_
->findLiveInMBBs(LR
.start
, LR
.end
, LiveInMBBs
)) {
535 for (unsigned i
= 0, e
= LiveInMBBs
.size(); i
!= e
; ++i
)
536 if (LiveInMBBs
[i
] != EntryMBB
)
537 LiveInMBBs
[i
]->addLiveIn(Reg
);
545 // Look for physical registers that end up not being allocated even though
546 // register allocator had to spill other registers in its register class.
547 if (ls_
->getNumIntervals() == 0)
549 if (!vrm_
->FindUnusedRegisters(tri_
, li_
))
553 /// processActiveIntervals - expire old intervals and move non-overlapping ones
554 /// to the inactive list.
555 void RALinScan::processActiveIntervals(unsigned CurPoint
)
557 DOUT
<< "\tprocessing active intervals:\n";
559 for (unsigned i
= 0, e
= active_
.size(); i
!= e
; ++i
) {
560 LiveInterval
*Interval
= active_
[i
].first
;
561 LiveInterval::iterator IntervalPos
= active_
[i
].second
;
562 unsigned reg
= Interval
->reg
;
564 IntervalPos
= Interval
->advanceTo(IntervalPos
, CurPoint
);
566 if (IntervalPos
== Interval
->end()) { // Remove expired intervals.
567 DOUT
<< "\t\tinterval " << *Interval
<< " expired\n";
568 assert(TargetRegisterInfo::isVirtualRegister(reg
) &&
569 "Can only allocate virtual registers!");
570 reg
= vrm_
->getPhys(reg
);
573 // Pop off the end of the list.
574 active_
[i
] = active_
.back();
578 } else if (IntervalPos
->start
> CurPoint
) {
579 // Move inactive intervals to inactive list.
580 DOUT
<< "\t\tinterval " << *Interval
<< " inactive\n";
581 assert(TargetRegisterInfo::isVirtualRegister(reg
) &&
582 "Can only allocate virtual registers!");
583 reg
= vrm_
->getPhys(reg
);
586 inactive_
.push_back(std::make_pair(Interval
, IntervalPos
));
588 // Pop off the end of the list.
589 active_
[i
] = active_
.back();
593 // Otherwise, just update the iterator position.
594 active_
[i
].second
= IntervalPos
;
599 /// processInactiveIntervals - expire old intervals and move overlapping
600 /// ones to the active list.
601 void RALinScan::processInactiveIntervals(unsigned CurPoint
)
603 DOUT
<< "\tprocessing inactive intervals:\n";
605 for (unsigned i
= 0, e
= inactive_
.size(); i
!= e
; ++i
) {
606 LiveInterval
*Interval
= inactive_
[i
].first
;
607 LiveInterval::iterator IntervalPos
= inactive_
[i
].second
;
608 unsigned reg
= Interval
->reg
;
610 IntervalPos
= Interval
->advanceTo(IntervalPos
, CurPoint
);
612 if (IntervalPos
== Interval
->end()) { // remove expired intervals.
613 DOUT
<< "\t\tinterval " << *Interval
<< " expired\n";
615 // Pop off the end of the list.
616 inactive_
[i
] = inactive_
.back();
617 inactive_
.pop_back();
619 } else if (IntervalPos
->start
<= CurPoint
) {
620 // move re-activated intervals in active list
621 DOUT
<< "\t\tinterval " << *Interval
<< " active\n";
622 assert(TargetRegisterInfo::isVirtualRegister(reg
) &&
623 "Can only allocate virtual registers!");
624 reg
= vrm_
->getPhys(reg
);
627 active_
.push_back(std::make_pair(Interval
, IntervalPos
));
629 // Pop off the end of the list.
630 inactive_
[i
] = inactive_
.back();
631 inactive_
.pop_back();
634 // Otherwise, just update the iterator position.
635 inactive_
[i
].second
= IntervalPos
;
640 /// updateSpillWeights - updates the spill weights of the specifed physical
641 /// register and its weight.
642 void RALinScan::updateSpillWeights(std::vector
<float> &Weights
,
643 unsigned reg
, float weight
,
644 const TargetRegisterClass
*RC
) {
645 SmallSet
<unsigned, 4> Processed
;
646 SmallSet
<unsigned, 4> SuperAdded
;
647 SmallVector
<unsigned, 4> Supers
;
648 Weights
[reg
] += weight
;
649 Processed
.insert(reg
);
650 for (const unsigned* as
= tri_
->getAliasSet(reg
); *as
; ++as
) {
651 Weights
[*as
] += weight
;
652 Processed
.insert(*as
);
653 if (tri_
->isSubRegister(*as
, reg
) &&
654 SuperAdded
.insert(*as
) &&
656 Supers
.push_back(*as
);
660 // If the alias is a super-register, and the super-register is in the
661 // register class we are trying to allocate. Then add the weight to all
662 // sub-registers of the super-register even if they are not aliases.
663 // e.g. allocating for GR32, bh is not used, updating bl spill weight.
664 // bl should get the same spill weight otherwise it will be choosen
665 // as a spill candidate since spilling bh doesn't make ebx available.
666 for (unsigned i
= 0, e
= Supers
.size(); i
!= e
; ++i
) {
667 for (const unsigned *sr
= tri_
->getSubRegisters(Supers
[i
]); *sr
; ++sr
)
668 if (!Processed
.count(*sr
))
669 Weights
[*sr
] += weight
;
674 RALinScan::IntervalPtrs::iterator
675 FindIntervalInVector(RALinScan::IntervalPtrs
&IP
, LiveInterval
*LI
) {
676 for (RALinScan::IntervalPtrs::iterator I
= IP
.begin(), E
= IP
.end();
678 if (I
->first
== LI
) return I
;
682 static void RevertVectorIteratorsTo(RALinScan::IntervalPtrs
&V
, unsigned Point
){
683 for (unsigned i
= 0, e
= V
.size(); i
!= e
; ++i
) {
684 RALinScan::IntervalPtr
&IP
= V
[i
];
685 LiveInterval::iterator I
= std::upper_bound(IP
.first
->begin(),
687 if (I
!= IP
.first
->begin()) --I
;
692 /// addStackInterval - Create a LiveInterval for stack if the specified live
693 /// interval has been spilled.
694 static void addStackInterval(LiveInterval
*cur
, LiveStacks
*ls_
,
696 MachineRegisterInfo
* mri_
, VirtRegMap
&vrm_
) {
697 int SS
= vrm_
.getStackSlot(cur
->reg
);
698 if (SS
== VirtRegMap::NO_STACK_SLOT
)
701 const TargetRegisterClass
*RC
= mri_
->getRegClass(cur
->reg
);
702 LiveInterval
&SI
= ls_
->getOrCreateInterval(SS
, RC
);
705 if (SI
.hasAtLeastOneValue())
706 VNI
= SI
.getValNumInfo(0);
708 VNI
= SI
.getNextValue(~0U, 0, ls_
->getVNInfoAllocator());
710 LiveInterval
&RI
= li_
->getInterval(cur
->reg
);
711 // FIXME: This may be overly conservative.
712 SI
.MergeRangesInAsValue(RI
, VNI
);
715 /// getConflictWeight - Return the number of conflicts between cur
716 /// live interval and defs and uses of Reg weighted by loop depthes.
718 float getConflictWeight(LiveInterval
*cur
, unsigned Reg
, LiveIntervals
*li_
,
719 MachineRegisterInfo
*mri_
,
720 const MachineLoopInfo
*loopInfo
) {
722 for (MachineRegisterInfo::reg_iterator I
= mri_
->reg_begin(Reg
),
723 E
= mri_
->reg_end(); I
!= E
; ++I
) {
724 MachineInstr
*MI
= &*I
;
725 if (cur
->liveAt(li_
->getInstructionIndex(MI
))) {
726 unsigned loopDepth
= loopInfo
->getLoopDepth(MI
->getParent());
727 Conflicts
+= powf(10.0f
, (float)loopDepth
);
733 /// findIntervalsToSpill - Determine the intervals to spill for the
734 /// specified interval. It's passed the physical registers whose spill
735 /// weight is the lowest among all the registers whose live intervals
736 /// conflict with the interval.
737 void RALinScan::findIntervalsToSpill(LiveInterval
*cur
,
738 std::vector
<std::pair
<unsigned,float> > &Candidates
,
740 SmallVector
<LiveInterval
*, 8> &SpillIntervals
) {
741 // We have figured out the *best* register to spill. But there are other
742 // registers that are pretty good as well (spill weight within 3%). Spill
743 // the one that has fewest defs and uses that conflict with cur.
744 float Conflicts
[3] = { 0.0f
, 0.0f
, 0.0f
};
745 SmallVector
<LiveInterval
*, 8> SLIs
[3];
747 DOUT
<< "\tConsidering " << NumCands
<< " candidates: ";
748 DEBUG(for (unsigned i
= 0; i
!= NumCands
; ++i
)
749 DOUT
<< tri_
->getName(Candidates
[i
].first
) << " ";
752 // Calculate the number of conflicts of each candidate.
753 for (IntervalPtrs::iterator i
= active_
.begin(); i
!= active_
.end(); ++i
) {
754 unsigned Reg
= i
->first
->reg
;
755 unsigned PhysReg
= vrm_
->getPhys(Reg
);
756 if (!cur
->overlapsFrom(*i
->first
, i
->second
))
758 for (unsigned j
= 0; j
< NumCands
; ++j
) {
759 unsigned Candidate
= Candidates
[j
].first
;
760 if (tri_
->regsOverlap(PhysReg
, Candidate
)) {
762 Conflicts
[j
] += getConflictWeight(cur
, Reg
, li_
, mri_
, loopInfo
);
763 SLIs
[j
].push_back(i
->first
);
768 for (IntervalPtrs::iterator i
= inactive_
.begin(); i
!= inactive_
.end(); ++i
){
769 unsigned Reg
= i
->first
->reg
;
770 unsigned PhysReg
= vrm_
->getPhys(Reg
);
771 if (!cur
->overlapsFrom(*i
->first
, i
->second
-1))
773 for (unsigned j
= 0; j
< NumCands
; ++j
) {
774 unsigned Candidate
= Candidates
[j
].first
;
775 if (tri_
->regsOverlap(PhysReg
, Candidate
)) {
777 Conflicts
[j
] += getConflictWeight(cur
, Reg
, li_
, mri_
, loopInfo
);
778 SLIs
[j
].push_back(i
->first
);
783 // Which is the best candidate?
784 unsigned BestCandidate
= 0;
785 float MinConflicts
= Conflicts
[0];
786 for (unsigned i
= 1; i
!= NumCands
; ++i
) {
787 if (Conflicts
[i
] < MinConflicts
) {
789 MinConflicts
= Conflicts
[i
];
793 std::copy(SLIs
[BestCandidate
].begin(), SLIs
[BestCandidate
].end(),
794 std::back_inserter(SpillIntervals
));
798 struct WeightCompare
{
799 typedef std::pair
<unsigned, float> RegWeightPair
;
800 bool operator()(const RegWeightPair
&LHS
, const RegWeightPair
&RHS
) const {
801 return LHS
.second
< RHS
.second
;
806 static bool weightsAreClose(float w1
, float w2
) {
810 float diff
= w1
- w2
;
811 if (diff
<= 0.02f
) // Within 0.02f
813 return (diff
/ w2
) <= 0.05f
; // Within 5%.
816 LiveInterval
*RALinScan::hasNextReloadInterval(LiveInterval
*cur
) {
817 DenseMap
<unsigned, unsigned>::iterator I
= NextReloadMap
.find(cur
->reg
);
818 if (I
== NextReloadMap
.end())
820 return &li_
->getInterval(I
->second
);
823 void RALinScan::DowngradeRegister(LiveInterval
*li
, unsigned Reg
) {
824 bool isNew
= DowngradedRegs
.insert(Reg
);
825 isNew
= isNew
; // Silence compiler warning.
826 assert(isNew
&& "Multiple reloads holding the same register?");
827 DowngradeMap
.insert(std::make_pair(li
->reg
, Reg
));
828 for (const unsigned *AS
= tri_
->getAliasSet(Reg
); *AS
; ++AS
) {
829 isNew
= DowngradedRegs
.insert(*AS
);
830 isNew
= isNew
; // Silence compiler warning.
831 assert(isNew
&& "Multiple reloads holding the same register?");
832 DowngradeMap
.insert(std::make_pair(li
->reg
, *AS
));
837 void RALinScan::UpgradeRegister(unsigned Reg
) {
839 DowngradedRegs
.erase(Reg
);
840 for (const unsigned *AS
= tri_
->getAliasSet(Reg
); *AS
; ++AS
)
841 DowngradedRegs
.erase(*AS
);
847 bool operator()(LiveInterval
* A
, LiveInterval
* B
) {
848 return A
->beginNumber() < B
->beginNumber();
853 /// assignRegOrStackSlotAtInterval - assign a register if one is available, or
855 void RALinScan::assignRegOrStackSlotAtInterval(LiveInterval
* cur
)
857 DOUT
<< "\tallocating current interval: ";
859 // This is an implicitly defined live interval, just assign any register.
860 const TargetRegisterClass
*RC
= mri_
->getRegClass(cur
->reg
);
862 unsigned physReg
= cur
->preference
;
864 physReg
= *RC
->allocation_order_begin(*mf_
);
865 DOUT
<< tri_
->getName(physReg
) << '\n';
866 // Note the register is not really in use.
867 vrm_
->assignVirt2Phys(cur
->reg
, physReg
);
873 std::vector
<std::pair
<unsigned, float> > SpillWeightsToAdd
;
874 unsigned StartPosition
= cur
->beginNumber();
875 const TargetRegisterClass
*RCLeader
= RelatedRegClasses
.getLeaderValue(RC
);
877 // If start of this live interval is defined by a move instruction and its
878 // source is assigned a physical register that is compatible with the target
879 // register class, then we should try to assign it the same register.
880 // This can happen when the move is from a larger register class to a smaller
881 // one, e.g. X86::mov32to32_. These move instructions are not coalescable.
882 if (!cur
->preference
&& cur
->hasAtLeastOneValue()) {
883 VNInfo
*vni
= cur
->begin()->valno
;
884 if (vni
->def
&& vni
->def
!= ~1U && vni
->def
!= ~0U) {
885 MachineInstr
*CopyMI
= li_
->getInstructionFromIndex(vni
->def
);
886 unsigned SrcReg
, DstReg
, SrcSubReg
, DstSubReg
;
888 tii_
->isMoveInstr(*CopyMI
, SrcReg
, DstReg
, SrcSubReg
, DstSubReg
)) {
890 if (TargetRegisterInfo::isPhysicalRegister(SrcReg
))
892 else if (vrm_
->isAssignedReg(SrcReg
))
893 Reg
= vrm_
->getPhys(SrcReg
);
896 Reg
= tri_
->getSubReg(Reg
, SrcSubReg
);
898 Reg
= tri_
->getMatchingSuperReg(Reg
, DstSubReg
, RC
);
899 if (Reg
&& allocatableRegs_
[Reg
] && RC
->contains(Reg
))
900 cur
->preference
= Reg
;
906 // For every interval in inactive we overlap with, mark the
907 // register as not free and update spill weights.
908 for (IntervalPtrs::const_iterator i
= inactive_
.begin(),
909 e
= inactive_
.end(); i
!= e
; ++i
) {
910 unsigned Reg
= i
->first
->reg
;
911 assert(TargetRegisterInfo::isVirtualRegister(Reg
) &&
912 "Can only allocate virtual registers!");
913 const TargetRegisterClass
*RegRC
= mri_
->getRegClass(Reg
);
914 // If this is not in a related reg class to the register we're allocating,
916 if (RelatedRegClasses
.getLeaderValue(RegRC
) == RCLeader
&&
917 cur
->overlapsFrom(*i
->first
, i
->second
-1)) {
918 Reg
= vrm_
->getPhys(Reg
);
920 SpillWeightsToAdd
.push_back(std::make_pair(Reg
, i
->first
->weight
));
924 // Speculatively check to see if we can get a register right now. If not,
925 // we know we won't be able to by adding more constraints. If so, we can
926 // check to see if it is valid. Doing an exhaustive search of the fixed_ list
927 // is very bad (it contains all callee clobbered registers for any functions
928 // with a call), so we want to avoid doing that if possible.
929 unsigned physReg
= getFreePhysReg(cur
);
930 unsigned BestPhysReg
= physReg
;
932 // We got a register. However, if it's in the fixed_ list, we might
933 // conflict with it. Check to see if we conflict with it or any of its
935 SmallSet
<unsigned, 8> RegAliases
;
936 for (const unsigned *AS
= tri_
->getAliasSet(physReg
); *AS
; ++AS
)
937 RegAliases
.insert(*AS
);
939 bool ConflictsWithFixed
= false;
940 for (unsigned i
= 0, e
= fixed_
.size(); i
!= e
; ++i
) {
941 IntervalPtr
&IP
= fixed_
[i
];
942 if (physReg
== IP
.first
->reg
|| RegAliases
.count(IP
.first
->reg
)) {
943 // Okay, this reg is on the fixed list. Check to see if we actually
945 LiveInterval
*I
= IP
.first
;
946 if (I
->endNumber() > StartPosition
) {
947 LiveInterval::iterator II
= I
->advanceTo(IP
.second
, StartPosition
);
949 if (II
!= I
->begin() && II
->start
> StartPosition
)
951 if (cur
->overlapsFrom(*I
, II
)) {
952 ConflictsWithFixed
= true;
959 // Okay, the register picked by our speculative getFreePhysReg call turned
960 // out to be in use. Actually add all of the conflicting fixed registers to
961 // regUse_ so we can do an accurate query.
962 if (ConflictsWithFixed
) {
963 // For every interval in fixed we overlap with, mark the register as not
964 // free and update spill weights.
965 for (unsigned i
= 0, e
= fixed_
.size(); i
!= e
; ++i
) {
966 IntervalPtr
&IP
= fixed_
[i
];
967 LiveInterval
*I
= IP
.first
;
969 const TargetRegisterClass
*RegRC
= OneClassForEachPhysReg
[I
->reg
];
970 if (RelatedRegClasses
.getLeaderValue(RegRC
) == RCLeader
&&
971 I
->endNumber() > StartPosition
) {
972 LiveInterval::iterator II
= I
->advanceTo(IP
.second
, StartPosition
);
974 if (II
!= I
->begin() && II
->start
> StartPosition
)
976 if (cur
->overlapsFrom(*I
, II
)) {
977 unsigned reg
= I
->reg
;
979 SpillWeightsToAdd
.push_back(std::make_pair(reg
, I
->weight
));
984 // Using the newly updated regUse_ object, which includes conflicts in the
985 // future, see if there are any registers available.
986 physReg
= getFreePhysReg(cur
);
990 // Restore the physical register tracker, removing information about the
994 // If we find a free register, we are done: assign this virtual to
995 // the free physical register and add this interval to the active
998 DOUT
<< tri_
->getName(physReg
) << '\n';
999 vrm_
->assignVirt2Phys(cur
->reg
, physReg
);
1001 active_
.push_back(std::make_pair(cur
, cur
->begin()));
1002 handled_
.push_back(cur
);
1004 // "Upgrade" the physical register since it has been allocated.
1005 UpgradeRegister(physReg
);
1006 if (LiveInterval
*NextReloadLI
= hasNextReloadInterval(cur
)) {
1007 // "Downgrade" physReg to try to keep physReg from being allocated until
1008 // the next reload from the same SS is allocated.
1009 NextReloadLI
->preference
= physReg
;
1010 DowngradeRegister(cur
, physReg
);
1014 DOUT
<< "no free registers\n";
1016 // Compile the spill weights into an array that is better for scanning.
1017 std::vector
<float> SpillWeights(tri_
->getNumRegs(), 0.0f
);
1018 for (std::vector
<std::pair
<unsigned, float> >::iterator
1019 I
= SpillWeightsToAdd
.begin(), E
= SpillWeightsToAdd
.end(); I
!= E
; ++I
)
1020 updateSpillWeights(SpillWeights
, I
->first
, I
->second
, RC
);
1022 // for each interval in active, update spill weights.
1023 for (IntervalPtrs::const_iterator i
= active_
.begin(), e
= active_
.end();
1025 unsigned reg
= i
->first
->reg
;
1026 assert(TargetRegisterInfo::isVirtualRegister(reg
) &&
1027 "Can only allocate virtual registers!");
1028 reg
= vrm_
->getPhys(reg
);
1029 updateSpillWeights(SpillWeights
, reg
, i
->first
->weight
, RC
);
1032 DOUT
<< "\tassigning stack slot at interval "<< *cur
<< ":\n";
1034 // Find a register to spill.
1035 float minWeight
= HUGE_VALF
;
1036 unsigned minReg
= 0; /*cur->preference*/; // Try the pref register first.
1039 std::vector
<std::pair
<unsigned,float> > RegsWeights
;
1040 if (!minReg
|| SpillWeights
[minReg
] == HUGE_VALF
)
1041 for (TargetRegisterClass::iterator i
= RC
->allocation_order_begin(*mf_
),
1042 e
= RC
->allocation_order_end(*mf_
); i
!= e
; ++i
) {
1044 float regWeight
= SpillWeights
[reg
];
1045 if (minWeight
> regWeight
)
1047 RegsWeights
.push_back(std::make_pair(reg
, regWeight
));
1050 // If we didn't find a register that is spillable, try aliases?
1052 for (TargetRegisterClass::iterator i
= RC
->allocation_order_begin(*mf_
),
1053 e
= RC
->allocation_order_end(*mf_
); i
!= e
; ++i
) {
1055 // No need to worry about if the alias register size < regsize of RC.
1056 // We are going to spill all registers that alias it anyway.
1057 for (const unsigned* as
= tri_
->getAliasSet(reg
); *as
; ++as
)
1058 RegsWeights
.push_back(std::make_pair(*as
, SpillWeights
[*as
]));
1062 // Sort all potential spill candidates by weight.
1063 std::sort(RegsWeights
.begin(), RegsWeights
.end(), WeightCompare());
1064 minReg
= RegsWeights
[0].first
;
1065 minWeight
= RegsWeights
[0].second
;
1066 if (minWeight
== HUGE_VALF
) {
1067 // All registers must have inf weight. Just grab one!
1068 minReg
= BestPhysReg
? BestPhysReg
: *RC
->allocation_order_begin(*mf_
);
1069 if (cur
->weight
== HUGE_VALF
||
1070 li_
->getApproximateInstructionCount(*cur
) == 0) {
1071 // Spill a physical register around defs and uses.
1072 if (li_
->spillPhysRegAroundRegDefsUses(*cur
, minReg
, *vrm_
)) {
1073 // spillPhysRegAroundRegDefsUses may have invalidated iterator stored
1074 // in fixed_. Reset them.
1075 for (unsigned i
= 0, e
= fixed_
.size(); i
!= e
; ++i
) {
1076 IntervalPtr
&IP
= fixed_
[i
];
1077 LiveInterval
*I
= IP
.first
;
1078 if (I
->reg
== minReg
|| tri_
->isSubRegister(minReg
, I
->reg
))
1079 IP
.second
= I
->advanceTo(I
->begin(), StartPosition
);
1082 DowngradedRegs
.clear();
1083 assignRegOrStackSlotAtInterval(cur
);
1085 cerr
<< "Ran out of registers during register allocation!\n";
1092 // Find up to 3 registers to consider as spill candidates.
1093 unsigned LastCandidate
= RegsWeights
.size() >= 3 ? 3 : 1;
1094 while (LastCandidate
> 1) {
1095 if (weightsAreClose(RegsWeights
[LastCandidate
-1].second
, minWeight
))
1100 DOUT
<< "\t\tregister(s) with min weight(s): ";
1101 DEBUG(for (unsigned i
= 0; i
!= LastCandidate
; ++i
)
1102 DOUT
<< tri_
->getName(RegsWeights
[i
].first
)
1103 << " (" << RegsWeights
[i
].second
<< ")\n");
1105 // If the current has the minimum weight, we need to spill it and
1106 // add any added intervals back to unhandled, and restart
1108 if (cur
->weight
!= HUGE_VALF
&& cur
->weight
<= minWeight
) {
1109 DOUT
<< "\t\t\tspilling(c): " << *cur
<< '\n';
1110 SmallVector
<LiveInterval
*, 8> spillIs
;
1111 std::vector
<LiveInterval
*> added
=
1112 li_
->addIntervalsForSpills(*cur
, spillIs
, loopInfo
, *vrm_
);
1113 std::sort(added
.begin(), added
.end(), LISorter());
1114 addStackInterval(cur
, ls_
, li_
, mri_
, *vrm_
);
1116 return; // Early exit if all spills were folded.
1118 // Merge added with unhandled. Note that we have already sorted
1119 // intervals returned by addIntervalsForSpills by their starting
1121 // This also update the NextReloadMap. That is, it adds mapping from a
1122 // register defined by a reload from SS to the next reload from SS in the
1123 // same basic block.
1124 MachineBasicBlock
*LastReloadMBB
= 0;
1125 LiveInterval
*LastReload
= 0;
1126 int LastReloadSS
= VirtRegMap::NO_STACK_SLOT
;
1127 for (unsigned i
= 0, e
= added
.size(); i
!= e
; ++i
) {
1128 LiveInterval
*ReloadLi
= added
[i
];
1129 if (ReloadLi
->weight
== HUGE_VALF
&&
1130 li_
->getApproximateInstructionCount(*ReloadLi
) == 0) {
1131 unsigned ReloadIdx
= ReloadLi
->beginNumber();
1132 MachineBasicBlock
*ReloadMBB
= li_
->getMBBFromIndex(ReloadIdx
);
1133 int ReloadSS
= vrm_
->getStackSlot(ReloadLi
->reg
);
1134 if (LastReloadMBB
== ReloadMBB
&& LastReloadSS
== ReloadSS
) {
1135 // Last reload of same SS is in the same MBB. We want to try to
1136 // allocate both reloads the same register and make sure the reg
1137 // isn't clobbered in between if at all possible.
1138 assert(LastReload
->beginNumber() < ReloadIdx
);
1139 NextReloadMap
.insert(std::make_pair(LastReload
->reg
, ReloadLi
->reg
));
1141 LastReloadMBB
= ReloadMBB
;
1142 LastReload
= ReloadLi
;
1143 LastReloadSS
= ReloadSS
;
1145 unhandled_
.push(ReloadLi
);
1152 // Push the current interval back to unhandled since we are going
1153 // to re-run at least this iteration. Since we didn't modify it it
1154 // should go back right in the front of the list
1155 unhandled_
.push(cur
);
1157 assert(TargetRegisterInfo::isPhysicalRegister(minReg
) &&
1158 "did not choose a register to spill?");
1160 // We spill all intervals aliasing the register with
1161 // minimum weight, rollback to the interval with the earliest
1162 // start point and let the linear scan algorithm run again
1163 SmallVector
<LiveInterval
*, 8> spillIs
;
1165 // Determine which intervals have to be spilled.
1166 findIntervalsToSpill(cur
, RegsWeights
, LastCandidate
, spillIs
);
1168 // Set of spilled vregs (used later to rollback properly)
1169 SmallSet
<unsigned, 8> spilled
;
1171 // The earliest start of a Spilled interval indicates up to where
1172 // in handled we need to roll back
1173 unsigned earliestStart
= cur
->beginNumber();
1175 // Spill live intervals of virtual regs mapped to the physical register we
1176 // want to clear (and its aliases). We only spill those that overlap with the
1177 // current interval as the rest do not affect its allocation. we also keep
1178 // track of the earliest start of all spilled live intervals since this will
1179 // mark our rollback point.
1180 std::vector
<LiveInterval
*> added
;
1181 while (!spillIs
.empty()) {
1182 LiveInterval
*sli
= spillIs
.back();
1184 DOUT
<< "\t\t\tspilling(a): " << *sli
<< '\n';
1185 earliestStart
= std::min(earliestStart
, sli
->beginNumber());
1186 std::vector
<LiveInterval
*> newIs
=
1187 li_
->addIntervalsForSpills(*sli
, spillIs
, loopInfo
, *vrm_
);
1188 addStackInterval(sli
, ls_
, li_
, mri_
, *vrm_
);
1189 std::copy(newIs
.begin(), newIs
.end(), std::back_inserter(added
));
1190 spilled
.insert(sli
->reg
);
1193 DOUT
<< "\t\trolling back to: " << earliestStart
<< '\n';
1195 // Scan handled in reverse order up to the earliest start of a
1196 // spilled live interval and undo each one, restoring the state of
1198 while (!handled_
.empty()) {
1199 LiveInterval
* i
= handled_
.back();
1200 // If this interval starts before t we are done.
1201 if (i
->beginNumber() < earliestStart
)
1203 DOUT
<< "\t\t\tundo changes for: " << *i
<< '\n';
1204 handled_
.pop_back();
1206 // When undoing a live interval allocation we must know if it is active or
1207 // inactive to properly update regUse_ and the VirtRegMap.
1208 IntervalPtrs::iterator it
;
1209 if ((it
= FindIntervalInVector(active_
, i
)) != active_
.end()) {
1211 assert(!TargetRegisterInfo::isPhysicalRegister(i
->reg
));
1212 if (!spilled
.count(i
->reg
))
1214 delRegUse(vrm_
->getPhys(i
->reg
));
1215 vrm_
->clearVirt(i
->reg
);
1216 } else if ((it
= FindIntervalInVector(inactive_
, i
)) != inactive_
.end()) {
1217 inactive_
.erase(it
);
1218 assert(!TargetRegisterInfo::isPhysicalRegister(i
->reg
));
1219 if (!spilled
.count(i
->reg
))
1221 vrm_
->clearVirt(i
->reg
);
1223 assert(TargetRegisterInfo::isVirtualRegister(i
->reg
) &&
1224 "Can only allocate virtual registers!");
1225 vrm_
->clearVirt(i
->reg
);
1229 DenseMap
<unsigned, unsigned>::iterator ii
= DowngradeMap
.find(i
->reg
);
1230 if (ii
== DowngradeMap
.end())
1231 // It interval has a preference, it must be defined by a copy. Clear the
1232 // preference now since the source interval allocation may have been
1236 UpgradeRegister(ii
->second
);
1240 // Rewind the iterators in the active, inactive, and fixed lists back to the
1241 // point we reverted to.
1242 RevertVectorIteratorsTo(active_
, earliestStart
);
1243 RevertVectorIteratorsTo(inactive_
, earliestStart
);
1244 RevertVectorIteratorsTo(fixed_
, earliestStart
);
1246 // Scan the rest and undo each interval that expired after t and
1247 // insert it in active (the next iteration of the algorithm will
1248 // put it in inactive if required)
1249 for (unsigned i
= 0, e
= handled_
.size(); i
!= e
; ++i
) {
1250 LiveInterval
*HI
= handled_
[i
];
1251 if (!HI
->expiredAt(earliestStart
) &&
1252 HI
->expiredAt(cur
->beginNumber())) {
1253 DOUT
<< "\t\t\tundo changes for: " << *HI
<< '\n';
1254 active_
.push_back(std::make_pair(HI
, HI
->begin()));
1255 assert(!TargetRegisterInfo::isPhysicalRegister(HI
->reg
));
1256 addRegUse(vrm_
->getPhys(HI
->reg
));
1260 // Merge added with unhandled.
1261 // This also update the NextReloadMap. That is, it adds mapping from a
1262 // register defined by a reload from SS to the next reload from SS in the
1263 // same basic block.
1264 MachineBasicBlock
*LastReloadMBB
= 0;
1265 LiveInterval
*LastReload
= 0;
1266 int LastReloadSS
= VirtRegMap::NO_STACK_SLOT
;
1267 std::sort(added
.begin(), added
.end(), LISorter());
1268 for (unsigned i
= 0, e
= added
.size(); i
!= e
; ++i
) {
1269 LiveInterval
*ReloadLi
= added
[i
];
1270 if (ReloadLi
->weight
== HUGE_VALF
&&
1271 li_
->getApproximateInstructionCount(*ReloadLi
) == 0) {
1272 unsigned ReloadIdx
= ReloadLi
->beginNumber();
1273 MachineBasicBlock
*ReloadMBB
= li_
->getMBBFromIndex(ReloadIdx
);
1274 int ReloadSS
= vrm_
->getStackSlot(ReloadLi
->reg
);
1275 if (LastReloadMBB
== ReloadMBB
&& LastReloadSS
== ReloadSS
) {
1276 // Last reload of same SS is in the same MBB. We want to try to
1277 // allocate both reloads the same register and make sure the reg
1278 // isn't clobbered in between if at all possible.
1279 assert(LastReload
->beginNumber() < ReloadIdx
);
1280 NextReloadMap
.insert(std::make_pair(LastReload
->reg
, ReloadLi
->reg
));
1282 LastReloadMBB
= ReloadMBB
;
1283 LastReload
= ReloadLi
;
1284 LastReloadSS
= ReloadSS
;
1286 unhandled_
.push(ReloadLi
);
1290 unsigned RALinScan::getFreePhysReg(const TargetRegisterClass
*RC
,
1291 unsigned MaxInactiveCount
,
1292 SmallVector
<unsigned, 256> &inactiveCounts
,
1294 unsigned FreeReg
= 0;
1295 unsigned FreeRegInactiveCount
= 0;
1297 TargetRegisterClass::iterator I
= RC
->allocation_order_begin(*mf_
);
1298 TargetRegisterClass::iterator E
= RC
->allocation_order_end(*mf_
);
1299 assert(I
!= E
&& "No allocatable register in this register class!");
1301 // Scan for the first available register.
1302 for (; I
!= E
; ++I
) {
1304 // Ignore "downgraded" registers.
1305 if (SkipDGRegs
&& DowngradedRegs
.count(Reg
))
1307 if (isRegAvail(Reg
)) {
1309 if (FreeReg
< inactiveCounts
.size())
1310 FreeRegInactiveCount
= inactiveCounts
[FreeReg
];
1312 FreeRegInactiveCount
= 0;
1317 // If there are no free regs, or if this reg has the max inactive count,
1318 // return this register.
1319 if (FreeReg
== 0 || FreeRegInactiveCount
== MaxInactiveCount
)
1322 // Continue scanning the registers, looking for the one with the highest
1323 // inactive count. Alkis found that this reduced register pressure very
1324 // slightly on X86 (in rev 1.94 of this file), though this should probably be
1326 for (; I
!= E
; ++I
) {
1328 // Ignore "downgraded" registers.
1329 if (SkipDGRegs
&& DowngradedRegs
.count(Reg
))
1331 if (isRegAvail(Reg
) && Reg
< inactiveCounts
.size() &&
1332 FreeRegInactiveCount
< inactiveCounts
[Reg
]) {
1334 FreeRegInactiveCount
= inactiveCounts
[Reg
];
1335 if (FreeRegInactiveCount
== MaxInactiveCount
)
1336 break; // We found the one with the max inactive count.
1343 /// getFreePhysReg - return a free physical register for this virtual register
1344 /// interval if we have one, otherwise return 0.
1345 unsigned RALinScan::getFreePhysReg(LiveInterval
*cur
) {
1346 SmallVector
<unsigned, 256> inactiveCounts
;
1347 unsigned MaxInactiveCount
= 0;
1349 const TargetRegisterClass
*RC
= mri_
->getRegClass(cur
->reg
);
1350 const TargetRegisterClass
*RCLeader
= RelatedRegClasses
.getLeaderValue(RC
);
1352 for (IntervalPtrs::iterator i
= inactive_
.begin(), e
= inactive_
.end();
1354 unsigned reg
= i
->first
->reg
;
1355 assert(TargetRegisterInfo::isVirtualRegister(reg
) &&
1356 "Can only allocate virtual registers!");
1358 // If this is not in a related reg class to the register we're allocating,
1360 const TargetRegisterClass
*RegRC
= mri_
->getRegClass(reg
);
1361 if (RelatedRegClasses
.getLeaderValue(RegRC
) == RCLeader
) {
1362 reg
= vrm_
->getPhys(reg
);
1363 if (inactiveCounts
.size() <= reg
)
1364 inactiveCounts
.resize(reg
+1);
1365 ++inactiveCounts
[reg
];
1366 MaxInactiveCount
= std::max(MaxInactiveCount
, inactiveCounts
[reg
]);
1370 // If copy coalescer has assigned a "preferred" register, check if it's
1372 if (cur
->preference
) {
1373 DOUT
<< "(preferred: " << tri_
->getName(cur
->preference
) << ") ";
1374 if (isRegAvail(cur
->preference
) &&
1375 RC
->contains(cur
->preference
))
1376 return cur
->preference
;
1379 if (!DowngradedRegs
.empty()) {
1380 unsigned FreeReg
= getFreePhysReg(RC
, MaxInactiveCount
, inactiveCounts
,
1385 return getFreePhysReg(RC
, MaxInactiveCount
, inactiveCounts
, false);
1388 FunctionPass
* llvm::createLinearScanRegisterAllocator() {
1389 return new RALinScan();