1 //===-- RegAllocLinearScan.cpp - Linear Scan register allocator -----------===//
3 // The LLVM Compiler Infrastructure
5 // This file was developed by the LLVM research group and is distributed under
6 // the University of Illinois Open Source License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
10 // This file implements a linear scan register allocator.
12 //===----------------------------------------------------------------------===//
14 #define DEBUG_TYPE "regalloc"
15 #include "llvm/CodeGen/LiveIntervalAnalysis.h"
16 #include "PhysRegTracker.h"
17 #include "VirtRegMap.h"
18 #include "llvm/Function.h"
19 #include "llvm/CodeGen/MachineFunctionPass.h"
20 #include "llvm/CodeGen/MachineInstr.h"
21 #include "llvm/CodeGen/Passes.h"
22 #include "llvm/CodeGen/RegAllocRegistry.h"
23 #include "llvm/CodeGen/SSARegMap.h"
24 #include "llvm/Target/MRegisterInfo.h"
25 #include "llvm/Target/TargetMachine.h"
26 #include "llvm/ADT/EquivalenceClasses.h"
27 #include "llvm/ADT/Statistic.h"
28 #include "llvm/ADT/STLExtras.h"
29 #include "llvm/Support/Debug.h"
30 #include "llvm/Support/Visibility.h"
41 static Statistic
<double> efficiency
42 ("regalloc", "Ratio of intervals processed over total intervals");
43 static Statistic
<> NumBacktracks
44 ("regalloc", "Number of times we had to backtrack");
46 static RegisterRegAlloc
47 linearscanRegAlloc("linearscan", " linear scan register allocator",
48 createLinearScanRegisterAllocator
);
50 static unsigned numIterations
= 0;
51 static unsigned numIntervals
= 0;
53 struct VISIBILITY_HIDDEN RA
: public MachineFunctionPass
{
54 typedef std::pair
<LiveInterval
*, LiveInterval::iterator
> IntervalPtr
;
55 typedef std::vector
<IntervalPtr
> IntervalPtrs
;
57 /// RelatedRegClasses - This structure is built the first time a function is
58 /// compiled, and keeps track of which register classes have registers that
59 /// belong to multiple classes or have aliases that are in other classes.
60 EquivalenceClasses
<const TargetRegisterClass
*> RelatedRegClasses
;
61 std::map
<unsigned, const TargetRegisterClass
*> OneClassForEachPhysReg
;
64 const TargetMachine
* tm_
;
65 const MRegisterInfo
* mri_
;
69 /// handled_ - Intervals are added to the handled_ set in the order of their
70 /// start value. This is uses for backtracking.
71 std::vector
<LiveInterval
*> handled_
;
73 /// fixed_ - Intervals that correspond to machine registers.
77 /// active_ - Intervals that are currently being processed, and which have a
78 /// live range active for the current point.
81 /// inactive_ - Intervals that are currently being processed, but which have
82 /// a hold at the current point.
83 IntervalPtrs inactive_
;
85 typedef std::priority_queue
<LiveInterval
*,
86 std::vector
<LiveInterval
*>,
87 greater_ptr
<LiveInterval
> > IntervalHeap
;
88 IntervalHeap unhandled_
;
89 std::auto_ptr
<PhysRegTracker
> prt_
;
90 std::auto_ptr
<VirtRegMap
> vrm_
;
91 std::auto_ptr
<Spiller
> spiller_
;
94 virtual const char* getPassName() const {
95 return "Linear Scan Register Allocator";
98 virtual void getAnalysisUsage(AnalysisUsage
&AU
) const {
99 AU
.addRequired
<LiveIntervals
>();
100 MachineFunctionPass::getAnalysisUsage(AU
);
103 /// runOnMachineFunction - register allocate the whole function
104 bool runOnMachineFunction(MachineFunction
&);
107 /// linearScan - the linear scan algorithm
110 /// initIntervalSets - initialize the interval sets.
112 void initIntervalSets();
114 /// processActiveIntervals - expire old intervals and move non-overlapping
115 /// ones to the inactive list.
116 void processActiveIntervals(unsigned CurPoint
);
118 /// processInactiveIntervals - expire old intervals and move overlapping
119 /// ones to the active list.
120 void processInactiveIntervals(unsigned CurPoint
);
122 /// assignRegOrStackSlotAtInterval - assign a register if one
123 /// is available, or spill.
124 void assignRegOrStackSlotAtInterval(LiveInterval
* cur
);
127 /// register handling helpers
130 /// getFreePhysReg - return a free physical register for this virtual
131 /// register interval if we have one, otherwise return 0.
132 unsigned getFreePhysReg(LiveInterval
* cur
);
134 /// assignVirt2StackSlot - assigns this virtual register to a
135 /// stack slot. returns the stack slot
136 int assignVirt2StackSlot(unsigned virtReg
);
138 void ComputeRelatedRegClasses();
140 template <typename ItTy
>
141 void printIntervals(const char* const str
, ItTy i
, ItTy e
) const {
142 if (str
) std::cerr
<< str
<< " intervals:\n";
143 for (; i
!= e
; ++i
) {
144 std::cerr
<< "\t" << *i
->first
<< " -> ";
145 unsigned reg
= i
->first
->reg
;
146 if (MRegisterInfo::isVirtualRegister(reg
)) {
147 reg
= vrm_
->getPhys(reg
);
149 std::cerr
<< mri_
->getName(reg
) << '\n';
155 void RA::ComputeRelatedRegClasses() {
156 const MRegisterInfo
&MRI
= *mri_
;
158 // First pass, add all reg classes to the union, and determine at least one
159 // reg class that each register is in.
160 bool HasAliases
= false;
161 for (MRegisterInfo::regclass_iterator RCI
= MRI
.regclass_begin(),
162 E
= MRI
.regclass_end(); RCI
!= E
; ++RCI
) {
163 RelatedRegClasses
.insert(*RCI
);
164 for (TargetRegisterClass::iterator I
= (*RCI
)->begin(), E
= (*RCI
)->end();
166 HasAliases
= HasAliases
|| *MRI
.getAliasSet(*I
) != 0;
168 const TargetRegisterClass
*&PRC
= OneClassForEachPhysReg
[*I
];
170 // Already processed this register. Just make sure we know that
171 // multiple register classes share a register.
172 RelatedRegClasses
.unionSets(PRC
, *RCI
);
179 // Second pass, now that we know conservatively what register classes each reg
180 // belongs to, add info about aliases. We don't need to do this for targets
181 // without register aliases.
183 for (std::map
<unsigned, const TargetRegisterClass
*>::iterator
184 I
= OneClassForEachPhysReg
.begin(), E
= OneClassForEachPhysReg
.end();
186 for (const unsigned *AS
= MRI
.getAliasSet(I
->first
); *AS
; ++AS
)
187 RelatedRegClasses
.unionSets(I
->second
, OneClassForEachPhysReg
[*AS
]);
190 bool RA::runOnMachineFunction(MachineFunction
&fn
) {
192 tm_
= &fn
.getTarget();
193 mri_
= tm_
->getRegisterInfo();
194 li_
= &getAnalysis
<LiveIntervals
>();
196 // If this is the first function compiled, compute the related reg classes.
197 if (RelatedRegClasses
.empty())
198 ComputeRelatedRegClasses();
200 PhysRegsUsed
= new bool[mri_
->getNumRegs()];
201 std::fill(PhysRegsUsed
, PhysRegsUsed
+mri_
->getNumRegs(), false);
202 fn
.setUsedPhysRegs(PhysRegsUsed
);
204 if (!prt_
.get()) prt_
.reset(new PhysRegTracker(*mri_
));
205 vrm_
.reset(new VirtRegMap(*mf_
));
206 if (!spiller_
.get()) spiller_
.reset(createSpiller());
212 // Rewrite spill code and update the PhysRegsUsed set.
213 spiller_
->runOnMachineFunction(*mf_
, *vrm_
);
215 vrm_
.reset(); // Free the VirtRegMap
218 while (!unhandled_
.empty()) unhandled_
.pop();
227 /// initIntervalSets - initialize the interval sets.
229 void RA::initIntervalSets()
231 assert(unhandled_
.empty() && fixed_
.empty() &&
232 active_
.empty() && inactive_
.empty() &&
233 "interval sets should be empty on initialization");
235 for (LiveIntervals::iterator i
= li_
->begin(), e
= li_
->end(); i
!= e
; ++i
) {
236 if (MRegisterInfo::isPhysicalRegister(i
->second
.reg
)) {
237 PhysRegsUsed
[i
->second
.reg
] = true;
238 fixed_
.push_back(std::make_pair(&i
->second
, i
->second
.begin()));
240 unhandled_
.push(&i
->second
);
244 void RA::linearScan()
246 // linear scan algorithm
247 DEBUG(std::cerr
<< "********** LINEAR SCAN **********\n");
248 DEBUG(std::cerr
<< "********** Function: "
249 << mf_
->getFunction()->getName() << '\n');
251 // DEBUG(printIntervals("unhandled", unhandled_.begin(), unhandled_.end()));
252 DEBUG(printIntervals("fixed", fixed_
.begin(), fixed_
.end()));
253 DEBUG(printIntervals("active", active_
.begin(), active_
.end()));
254 DEBUG(printIntervals("inactive", inactive_
.begin(), inactive_
.end()));
256 while (!unhandled_
.empty()) {
257 // pick the interval with the earliest start point
258 LiveInterval
* cur
= unhandled_
.top();
261 DEBUG(std::cerr
<< "\n*** CURRENT ***: " << *cur
<< '\n');
263 processActiveIntervals(cur
->beginNumber());
264 processInactiveIntervals(cur
->beginNumber());
266 assert(MRegisterInfo::isVirtualRegister(cur
->reg
) &&
267 "Can only allocate virtual registers!");
269 // Allocating a virtual register. try to find a free
270 // physical register or spill an interval (possibly this one) in order to
272 assignRegOrStackSlotAtInterval(cur
);
274 DEBUG(printIntervals("active", active_
.begin(), active_
.end()));
275 DEBUG(printIntervals("inactive", inactive_
.begin(), inactive_
.end()));
277 numIntervals
+= li_
->getNumIntervals();
278 efficiency
= double(numIterations
) / double(numIntervals
);
280 // expire any remaining active intervals
281 for (IntervalPtrs::reverse_iterator
282 i
= active_
.rbegin(); i
!= active_
.rend(); ) {
283 unsigned reg
= i
->first
->reg
;
284 DEBUG(std::cerr
<< "\tinterval " << *i
->first
<< " expired\n");
285 assert(MRegisterInfo::isVirtualRegister(reg
) &&
286 "Can only allocate virtual registers!");
287 reg
= vrm_
->getPhys(reg
);
288 prt_
->delRegUse(reg
);
289 i
= IntervalPtrs::reverse_iterator(active_
.erase(i
.base()-1));
292 // expire any remaining inactive intervals
293 for (IntervalPtrs::reverse_iterator
294 i
= inactive_
.rbegin(); i
!= inactive_
.rend(); ) {
295 DEBUG(std::cerr
<< "\tinterval " << *i
->first
<< " expired\n");
296 i
= IntervalPtrs::reverse_iterator(inactive_
.erase(i
.base()-1));
299 DEBUG(std::cerr
<< *vrm_
);
302 /// processActiveIntervals - expire old intervals and move non-overlapping ones
303 /// to the inactive list.
304 void RA::processActiveIntervals(unsigned CurPoint
)
306 DEBUG(std::cerr
<< "\tprocessing active intervals:\n");
308 for (unsigned i
= 0, e
= active_
.size(); i
!= e
; ++i
) {
309 LiveInterval
*Interval
= active_
[i
].first
;
310 LiveInterval::iterator IntervalPos
= active_
[i
].second
;
311 unsigned reg
= Interval
->reg
;
313 IntervalPos
= Interval
->advanceTo(IntervalPos
, CurPoint
);
315 if (IntervalPos
== Interval
->end()) { // Remove expired intervals.
316 DEBUG(std::cerr
<< "\t\tinterval " << *Interval
<< " expired\n");
317 assert(MRegisterInfo::isVirtualRegister(reg
) &&
318 "Can only allocate virtual registers!");
319 reg
= vrm_
->getPhys(reg
);
320 prt_
->delRegUse(reg
);
322 // Pop off the end of the list.
323 active_
[i
] = active_
.back();
327 } else if (IntervalPos
->start
> CurPoint
) {
328 // Move inactive intervals to inactive list.
329 DEBUG(std::cerr
<< "\t\tinterval " << *Interval
<< " inactive\n");
330 assert(MRegisterInfo::isVirtualRegister(reg
) &&
331 "Can only allocate virtual registers!");
332 reg
= vrm_
->getPhys(reg
);
333 prt_
->delRegUse(reg
);
335 inactive_
.push_back(std::make_pair(Interval
, IntervalPos
));
337 // Pop off the end of the list.
338 active_
[i
] = active_
.back();
342 // Otherwise, just update the iterator position.
343 active_
[i
].second
= IntervalPos
;
348 /// processInactiveIntervals - expire old intervals and move overlapping
349 /// ones to the active list.
350 void RA::processInactiveIntervals(unsigned CurPoint
)
352 DEBUG(std::cerr
<< "\tprocessing inactive intervals:\n");
354 for (unsigned i
= 0, e
= inactive_
.size(); i
!= e
; ++i
) {
355 LiveInterval
*Interval
= inactive_
[i
].first
;
356 LiveInterval::iterator IntervalPos
= inactive_
[i
].second
;
357 unsigned reg
= Interval
->reg
;
359 IntervalPos
= Interval
->advanceTo(IntervalPos
, CurPoint
);
361 if (IntervalPos
== Interval
->end()) { // remove expired intervals.
362 DEBUG(std::cerr
<< "\t\tinterval " << *Interval
<< " expired\n");
364 // Pop off the end of the list.
365 inactive_
[i
] = inactive_
.back();
366 inactive_
.pop_back();
368 } else if (IntervalPos
->start
<= CurPoint
) {
369 // move re-activated intervals in active list
370 DEBUG(std::cerr
<< "\t\tinterval " << *Interval
<< " active\n");
371 assert(MRegisterInfo::isVirtualRegister(reg
) &&
372 "Can only allocate virtual registers!");
373 reg
= vrm_
->getPhys(reg
);
374 prt_
->addRegUse(reg
);
376 active_
.push_back(std::make_pair(Interval
, IntervalPos
));
378 // Pop off the end of the list.
379 inactive_
[i
] = inactive_
.back();
380 inactive_
.pop_back();
383 // Otherwise, just update the iterator position.
384 inactive_
[i
].second
= IntervalPos
;
389 /// updateSpillWeights - updates the spill weights of the specifed physical
390 /// register and its weight.
391 static void updateSpillWeights(std::vector
<float> &Weights
,
392 unsigned reg
, float weight
,
393 const MRegisterInfo
*MRI
) {
394 Weights
[reg
] += weight
;
395 for (const unsigned* as
= MRI
->getAliasSet(reg
); *as
; ++as
)
396 Weights
[*as
] += weight
;
399 static RA::IntervalPtrs::iterator
FindIntervalInVector(RA::IntervalPtrs
&IP
,
401 for (RA::IntervalPtrs::iterator I
= IP
.begin(), E
= IP
.end(); I
!= E
; ++I
)
402 if (I
->first
== LI
) return I
;
406 static void RevertVectorIteratorsTo(RA::IntervalPtrs
&V
, unsigned Point
) {
407 for (unsigned i
= 0, e
= V
.size(); i
!= e
; ++i
) {
408 RA::IntervalPtr
&IP
= V
[i
];
409 LiveInterval::iterator I
= std::upper_bound(IP
.first
->begin(),
411 if (I
!= IP
.first
->begin()) --I
;
416 /// assignRegOrStackSlotAtInterval - assign a register if one is available, or
418 void RA::assignRegOrStackSlotAtInterval(LiveInterval
* cur
)
420 DEBUG(std::cerr
<< "\tallocating current interval: ");
422 PhysRegTracker backupPrt
= *prt_
;
424 std::vector
<std::pair
<unsigned, float> > SpillWeightsToAdd
;
425 unsigned StartPosition
= cur
->beginNumber();
426 const TargetRegisterClass
*RC
= mf_
->getSSARegMap()->getRegClass(cur
->reg
);
427 const TargetRegisterClass
*RCLeader
= RelatedRegClasses
.getLeaderValue(RC
);
429 // for every interval in inactive we overlap with, mark the
430 // register as not free and update spill weights.
431 for (IntervalPtrs::const_iterator i
= inactive_
.begin(),
432 e
= inactive_
.end(); i
!= e
; ++i
) {
433 unsigned Reg
= i
->first
->reg
;
434 assert(MRegisterInfo::isVirtualRegister(Reg
) &&
435 "Can only allocate virtual registers!");
436 const TargetRegisterClass
*RegRC
= mf_
->getSSARegMap()->getRegClass(Reg
);
437 // If this is not in a related reg class to the register we're allocating,
439 if (RelatedRegClasses
.getLeaderValue(RegRC
) == RCLeader
&&
440 cur
->overlapsFrom(*i
->first
, i
->second
-1)) {
441 Reg
= vrm_
->getPhys(Reg
);
442 prt_
->addRegUse(Reg
);
443 SpillWeightsToAdd
.push_back(std::make_pair(Reg
, i
->first
->weight
));
447 // Speculatively check to see if we can get a register right now. If not,
448 // we know we won't be able to by adding more constraints. If so, we can
449 // check to see if it is valid. Doing an exhaustive search of the fixed_ list
450 // is very bad (it contains all callee clobbered registers for any functions
451 // with a call), so we want to avoid doing that if possible.
452 unsigned physReg
= getFreePhysReg(cur
);
454 // We got a register. However, if it's in the fixed_ list, we might
455 // conflict with it. Check to see if we conflict with it or any of its
457 std::set
<unsigned> RegAliases
;
458 for (const unsigned *AS
= mri_
->getAliasSet(physReg
); *AS
; ++AS
)
459 RegAliases
.insert(*AS
);
461 bool ConflictsWithFixed
= false;
462 for (unsigned i
= 0, e
= fixed_
.size(); i
!= e
; ++i
) {
463 if (physReg
== fixed_
[i
].first
->reg
||
464 RegAliases
.count(fixed_
[i
].first
->reg
)) {
465 // Okay, this reg is on the fixed list. Check to see if we actually
467 IntervalPtr
&IP
= fixed_
[i
];
468 LiveInterval
*I
= IP
.first
;
469 if (I
->endNumber() > StartPosition
) {
470 LiveInterval::iterator II
= I
->advanceTo(IP
.second
, StartPosition
);
472 if (II
!= I
->begin() && II
->start
> StartPosition
)
474 if (cur
->overlapsFrom(*I
, II
)) {
475 ConflictsWithFixed
= true;
482 // Okay, the register picked by our speculative getFreePhysReg call turned
483 // out to be in use. Actually add all of the conflicting fixed registers to
484 // prt so we can do an accurate query.
485 if (ConflictsWithFixed
) {
486 // For every interval in fixed we overlap with, mark the register as not
487 // free and update spill weights.
488 for (unsigned i
= 0, e
= fixed_
.size(); i
!= e
; ++i
) {
489 IntervalPtr
&IP
= fixed_
[i
];
490 LiveInterval
*I
= IP
.first
;
492 const TargetRegisterClass
*RegRC
= OneClassForEachPhysReg
[I
->reg
];
493 if (RelatedRegClasses
.getLeaderValue(RegRC
) == RCLeader
&&
494 I
->endNumber() > StartPosition
) {
495 LiveInterval::iterator II
= I
->advanceTo(IP
.second
, StartPosition
);
497 if (II
!= I
->begin() && II
->start
> StartPosition
)
499 if (cur
->overlapsFrom(*I
, II
)) {
500 unsigned reg
= I
->reg
;
501 prt_
->addRegUse(reg
);
502 SpillWeightsToAdd
.push_back(std::make_pair(reg
, I
->weight
));
507 // Using the newly updated prt_ object, which includes conflicts in the
508 // future, see if there are any registers available.
509 physReg
= getFreePhysReg(cur
);
513 // Restore the physical register tracker, removing information about the
517 // if we find a free register, we are done: assign this virtual to
518 // the free physical register and add this interval to the active
521 DEBUG(std::cerr
<< mri_
->getName(physReg
) << '\n');
522 vrm_
->assignVirt2Phys(cur
->reg
, physReg
);
523 prt_
->addRegUse(physReg
);
524 active_
.push_back(std::make_pair(cur
, cur
->begin()));
525 handled_
.push_back(cur
);
528 DEBUG(std::cerr
<< "no free registers\n");
530 // Compile the spill weights into an array that is better for scanning.
531 std::vector
<float> SpillWeights(mri_
->getNumRegs(), 0.0);
532 for (std::vector
<std::pair
<unsigned, float> >::iterator
533 I
= SpillWeightsToAdd
.begin(), E
= SpillWeightsToAdd
.end(); I
!= E
; ++I
)
534 updateSpillWeights(SpillWeights
, I
->first
, I
->second
, mri_
);
536 // for each interval in active, update spill weights.
537 for (IntervalPtrs::const_iterator i
= active_
.begin(), e
= active_
.end();
539 unsigned reg
= i
->first
->reg
;
540 assert(MRegisterInfo::isVirtualRegister(reg
) &&
541 "Can only allocate virtual registers!");
542 reg
= vrm_
->getPhys(reg
);
543 updateSpillWeights(SpillWeights
, reg
, i
->first
->weight
, mri_
);
546 DEBUG(std::cerr
<< "\tassigning stack slot at interval "<< *cur
<< ":\n");
548 // Find a register to spill.
549 float minWeight
= float(HUGE_VAL
);
551 for (TargetRegisterClass::iterator i
= RC
->allocation_order_begin(*mf_
),
552 e
= RC
->allocation_order_end(*mf_
); i
!= e
; ++i
) {
554 if (minWeight
> SpillWeights
[reg
]) {
555 minWeight
= SpillWeights
[reg
];
560 // If we didn't find a register that is spillable, try aliases?
562 for (TargetRegisterClass::iterator i
= RC
->allocation_order_begin(*mf_
),
563 e
= RC
->allocation_order_end(*mf_
); i
!= e
; ++i
) {
565 // No need to worry about if the alias register size < regsize of RC.
566 // We are going to spill all registers that alias it anyway.
567 for (const unsigned* as
= mri_
->getAliasSet(reg
); *as
; ++as
) {
568 if (minWeight
> SpillWeights
[*as
]) {
569 minWeight
= SpillWeights
[*as
];
575 // All registers must have inf weight. Just grab one!
577 minReg
= *RC
->allocation_order_begin(*mf_
);
580 DEBUG(std::cerr
<< "\t\tregister with min weight: "
581 << mri_
->getName(minReg
) << " (" << minWeight
<< ")\n");
583 // if the current has the minimum weight, we need to spill it and
584 // add any added intervals back to unhandled, and restart
586 if (cur
->weight
!= float(HUGE_VAL
) && cur
->weight
<= minWeight
) {
587 DEBUG(std::cerr
<< "\t\t\tspilling(c): " << *cur
<< '\n';);
588 int slot
= vrm_
->assignVirt2StackSlot(cur
->reg
);
589 std::vector
<LiveInterval
*> added
=
590 li_
->addIntervalsForSpills(*cur
, *vrm_
, slot
);
592 return; // Early exit if all spills were folded.
594 // Merge added with unhandled. Note that we know that
595 // addIntervalsForSpills returns intervals sorted by their starting
597 for (unsigned i
= 0, e
= added
.size(); i
!= e
; ++i
)
598 unhandled_
.push(added
[i
]);
604 // push the current interval back to unhandled since we are going
605 // to re-run at least this iteration. Since we didn't modify it it
606 // should go back right in the front of the list
607 unhandled_
.push(cur
);
609 // otherwise we spill all intervals aliasing the register with
610 // minimum weight, rollback to the interval with the earliest
611 // start point and let the linear scan algorithm run again
612 std::vector
<LiveInterval
*> added
;
613 assert(MRegisterInfo::isPhysicalRegister(minReg
) &&
614 "did not choose a register to spill?");
615 std::vector
<bool> toSpill(mri_
->getNumRegs(), false);
617 // We are going to spill minReg and all its aliases.
618 toSpill
[minReg
] = true;
619 for (const unsigned* as
= mri_
->getAliasSet(minReg
); *as
; ++as
)
622 // the earliest start of a spilled interval indicates up to where
623 // in handled we need to roll back
624 unsigned earliestStart
= cur
->beginNumber();
626 // set of spilled vregs (used later to rollback properly)
627 std::set
<unsigned> spilled
;
629 // spill live intervals of virtual regs mapped to the physical register we
630 // want to clear (and its aliases). We only spill those that overlap with the
631 // current interval as the rest do not affect its allocation. we also keep
632 // track of the earliest start of all spilled live intervals since this will
633 // mark our rollback point.
634 for (IntervalPtrs::iterator i
= active_
.begin(); i
!= active_
.end(); ++i
) {
635 unsigned reg
= i
->first
->reg
;
636 if (//MRegisterInfo::isVirtualRegister(reg) &&
637 toSpill
[vrm_
->getPhys(reg
)] &&
638 cur
->overlapsFrom(*i
->first
, i
->second
)) {
639 DEBUG(std::cerr
<< "\t\t\tspilling(a): " << *i
->first
<< '\n');
640 earliestStart
= std::min(earliestStart
, i
->first
->beginNumber());
641 int slot
= vrm_
->assignVirt2StackSlot(i
->first
->reg
);
642 std::vector
<LiveInterval
*> newIs
=
643 li_
->addIntervalsForSpills(*i
->first
, *vrm_
, slot
);
644 std::copy(newIs
.begin(), newIs
.end(), std::back_inserter(added
));
648 for (IntervalPtrs::iterator i
= inactive_
.begin(); i
!= inactive_
.end(); ++i
){
649 unsigned reg
= i
->first
->reg
;
650 if (//MRegisterInfo::isVirtualRegister(reg) &&
651 toSpill
[vrm_
->getPhys(reg
)] &&
652 cur
->overlapsFrom(*i
->first
, i
->second
-1)) {
653 DEBUG(std::cerr
<< "\t\t\tspilling(i): " << *i
->first
<< '\n');
654 earliestStart
= std::min(earliestStart
, i
->first
->beginNumber());
655 int slot
= vrm_
->assignVirt2StackSlot(reg
);
656 std::vector
<LiveInterval
*> newIs
=
657 li_
->addIntervalsForSpills(*i
->first
, *vrm_
, slot
);
658 std::copy(newIs
.begin(), newIs
.end(), std::back_inserter(added
));
663 DEBUG(std::cerr
<< "\t\trolling back to: " << earliestStart
<< '\n');
665 // Scan handled in reverse order up to the earliest start of a
666 // spilled live interval and undo each one, restoring the state of
668 while (!handled_
.empty()) {
669 LiveInterval
* i
= handled_
.back();
670 // If this interval starts before t we are done.
671 if (i
->beginNumber() < earliestStart
)
673 DEBUG(std::cerr
<< "\t\t\tundo changes for: " << *i
<< '\n');
676 // When undoing a live interval allocation we must know if it is active or
677 // inactive to properly update the PhysRegTracker and the VirtRegMap.
678 IntervalPtrs::iterator it
;
679 if ((it
= FindIntervalInVector(active_
, i
)) != active_
.end()) {
681 assert(!MRegisterInfo::isPhysicalRegister(i
->reg
));
682 if (!spilled
.count(i
->reg
))
684 prt_
->delRegUse(vrm_
->getPhys(i
->reg
));
685 vrm_
->clearVirt(i
->reg
);
686 } else if ((it
= FindIntervalInVector(inactive_
, i
)) != inactive_
.end()) {
688 assert(!MRegisterInfo::isPhysicalRegister(i
->reg
));
689 if (!spilled
.count(i
->reg
))
691 vrm_
->clearVirt(i
->reg
);
693 assert(MRegisterInfo::isVirtualRegister(i
->reg
) &&
694 "Can only allocate virtual registers!");
695 vrm_
->clearVirt(i
->reg
);
700 // Rewind the iterators in the active, inactive, and fixed lists back to the
701 // point we reverted to.
702 RevertVectorIteratorsTo(active_
, earliestStart
);
703 RevertVectorIteratorsTo(inactive_
, earliestStart
);
704 RevertVectorIteratorsTo(fixed_
, earliestStart
);
706 // scan the rest and undo each interval that expired after t and
707 // insert it in active (the next iteration of the algorithm will
708 // put it in inactive if required)
709 for (unsigned i
= 0, e
= handled_
.size(); i
!= e
; ++i
) {
710 LiveInterval
*HI
= handled_
[i
];
711 if (!HI
->expiredAt(earliestStart
) &&
712 HI
->expiredAt(cur
->beginNumber())) {
713 DEBUG(std::cerr
<< "\t\t\tundo changes for: " << *HI
<< '\n');
714 active_
.push_back(std::make_pair(HI
, HI
->begin()));
715 assert(!MRegisterInfo::isPhysicalRegister(HI
->reg
));
716 prt_
->addRegUse(vrm_
->getPhys(HI
->reg
));
720 // merge added with unhandled
721 for (unsigned i
= 0, e
= added
.size(); i
!= e
; ++i
)
722 unhandled_
.push(added
[i
]);
725 /// getFreePhysReg - return a free physical register for this virtual register
726 /// interval if we have one, otherwise return 0.
727 unsigned RA::getFreePhysReg(LiveInterval
*cur
) {
728 std::vector
<unsigned> inactiveCounts(mri_
->getNumRegs(), 0);
729 unsigned MaxInactiveCount
= 0;
731 const TargetRegisterClass
*RC
= mf_
->getSSARegMap()->getRegClass(cur
->reg
);
732 const TargetRegisterClass
*RCLeader
= RelatedRegClasses
.getLeaderValue(RC
);
734 for (IntervalPtrs::iterator i
= inactive_
.begin(), e
= inactive_
.end();
736 unsigned reg
= i
->first
->reg
;
737 assert(MRegisterInfo::isVirtualRegister(reg
) &&
738 "Can only allocate virtual registers!");
740 // If this is not in a related reg class to the register we're allocating,
742 const TargetRegisterClass
*RegRC
= mf_
->getSSARegMap()->getRegClass(reg
);
743 if (RelatedRegClasses
.getLeaderValue(RegRC
) == RCLeader
) {
744 reg
= vrm_
->getPhys(reg
);
745 ++inactiveCounts
[reg
];
746 MaxInactiveCount
= std::max(MaxInactiveCount
, inactiveCounts
[reg
]);
750 const TargetRegisterClass
* rc
= mf_
->getSSARegMap()->getRegClass(cur
->reg
);
752 unsigned FreeReg
= 0;
753 unsigned FreeRegInactiveCount
= 0;
755 // Scan for the first available register.
756 TargetRegisterClass::iterator I
= rc
->allocation_order_begin(*mf_
);
757 TargetRegisterClass::iterator E
= rc
->allocation_order_end(*mf_
);
759 if (prt_
->isRegAvail(*I
)) {
761 FreeRegInactiveCount
= inactiveCounts
[FreeReg
];
765 // If there are no free regs, or if this reg has the max inactive count,
766 // return this register.
767 if (FreeReg
== 0 || FreeRegInactiveCount
== MaxInactiveCount
) return FreeReg
;
769 // Continue scanning the registers, looking for the one with the highest
770 // inactive count. Alkis found that this reduced register pressure very
771 // slightly on X86 (in rev 1.94 of this file), though this should probably be
773 for (; I
!= E
; ++I
) {
775 if (prt_
->isRegAvail(Reg
) && FreeRegInactiveCount
< inactiveCounts
[Reg
]) {
777 FreeRegInactiveCount
= inactiveCounts
[Reg
];
778 if (FreeRegInactiveCount
== MaxInactiveCount
)
779 break; // We found the one with the max inactive count.
786 FunctionPass
* llvm::createLinearScanRegisterAllocator() {