llvm.org GIT mirror llvm / 14e8d71
This is a prototype of an experimental register allocation framework. It's purpose is not to improve register allocation per se, but to make it easier to develop powerful live range splitting. I call it the basic allocator because it is as simple as a global allocator can be but provides the building blocks for sophisticated register allocation with live range splitting. A minimal implementation is provided that trivially spills whenever it runs out of registers. I'm checking in now to get high-level design and style feedback. I've only done minimal testing. The next step is implementing a "greedy" allocation algorithm that does some register reassignment and makes better splitting decisions. git-svn-id: https://llvm.org/svn/llvm-project/llvm/trunk@117174 91177308-0d34-0410-b5e6-96231b3b80d8 Andrew Trick 9 years ago
8 changed file(s) with 807 addition(s) and 1 deletion(s). Raw diff Collapse all Expand all
3333 (void) llvm::createDeadMachineInstructionElimPass();
3434
3535 (void) llvm::createFastRegisterAllocator();
36 (void) llvm::createBasicRegisterAllocator();
3637 (void) llvm::createLinearScanRegisterAllocator();
3738 (void) llvm::createDefaultPBQPRegisterAllocator();
3839
9494 ///
9595 FunctionPass *createFastRegisterAllocator();
9696
97 /// BasicRegisterAllocation Pass - This pass implements a degenerate global
98 /// register allocator using the basic regalloc framework.
99 ///
100 FunctionPass *createBasicRegisterAllocator();
101
97102 /// LinearScanRegisterAllocation Pass - This pass implements the linear scan
98103 /// register allocation algorithm, a global register allocator.
99104 ///
2020 LatencyPriorityQueue.cpp
2121 LiveInterval.cpp
2222 LiveIntervalAnalysis.cpp
23 LiveIntervalUnion.cpp
2324 LiveStackAnalysis.cpp
2425 LiveVariables.cpp
2526 LiveRangeEdit.cpp
5455 ProcessImplicitDefs.cpp
5556 PrologEpilogInserter.cpp
5657 PseudoSourceValue.cpp
58 RegAllocBasic.cpp
5759 RegAllocFast.cpp
5860 RegAllocLinearScan.cpp
5961 RegAllocPBQP.cpp
0 //===-- LiveIntervalUnion.cpp - Live interval union data structure --------===//
1 //
2 // The LLVM Compiler Infrastructure
3 //
4 // This file is distributed under the University of Illinois Open Source
5 // License. See LICENSE.TXT for details.
6 //
7 //===----------------------------------------------------------------------===//
8 //
9 // LiveIntervalUnion represents a coalesced set of live intervals. This may be
10 // used during coalescing to represent a congruence class, or during register
11 // allocation to model liveness of a physical register.
12 //
13 //===----------------------------------------------------------------------===//
14
15 #define DEBUG_TYPE "regalloc"
16 #include "LiveIntervalUnion.h"
17 #include "llvm/Support/Debug.h"
18 #include "llvm/Support/raw_ostream.h"
19 #include
20 using namespace llvm;
21
22 // Merge a LiveInterval's segments. Guarantee no overlaps.
23 void LiveIntervalUnion::unify(LiveInterval &lvr) {
24 // Add this live virtual register to the union
25 LiveVirtRegs::iterator pos = std::upper_bound(lvrs_.begin(), lvrs_.end(),
26 &lvr, less_ptr());
27 assert(pos == lvrs_.end() || *pos != &lvr && "duplicate LVR insertion");
28 lvrs_.insert(pos, &lvr);
29 // Insert each of the virtual register's live segments into the map
30 SegmentIter segPos = segments_.begin();
31 for (LiveInterval::iterator lvrI = lvr.begin(), lvrEnd = lvr.end();
32 lvrI != lvrEnd; ++lvrI ) {
33 LiveSegment segment(lvrI->start, lvrI->end, lvr);
34 segPos = segments_.insert(segPos, segment);
35 assert(*segPos == segment && "need equal val for equal key");
36 }
37 }
38
39 namespace {
40
41 // Keep LVRs sorted for fast membership test and extraction.
42 struct LessReg
43 : public std::binary_function {
44 bool operator()(const LiveInterval *left, const LiveInterval *right) const {
45 return left->reg < right->reg;
46 }
47 };
48
49 // Low-level helper to find the first segment in the range [segI,segEnd) that
50 // intersects with a live virtual register segment, or segI.start >= lvr.end
51 //
52 // This logic is tied to the underlying LiveSegments data structure. For now, we
53 // use a binary search within the vector to find the nearest starting position,
54 // then reverse iterate to find the first overlap.
55 //
56 // Upon entry we have segI.start < lvrSeg.end
57 // seg |--...
58 // \ .
59 // lvr ...-|
60 //
61 // After binary search, we have segI.start >= lvrSeg.start:
62 // seg |--...
63 // /
64 // lvr |--...
65 //
66 // Assuming intervals are disjoint, if an intersection exists, it must be the
67 // segment found or immediately behind it. We continue reverse iterating to
68 // return the first overlap.
69 //
70 // FIXME: support extract(), handle tombstones of extracted lvrs.
71 typedef LiveIntervalUnion::SegmentIter SegmentIter;
72 SegmentIter upperBound(SegmentIter segBegin,
73 SegmentIter segEnd,
74 const LiveRange &lvrSeg) {
75 assert(lvrSeg.end > segBegin->start && "segment iterator precondition");
76 // get the next LIU segment such that setg.start is not less than
77 // lvrSeg.start
78 SegmentIter segI = std::upper_bound(segBegin, segEnd, lvrSeg.start);
79 while (segI != segBegin) {
80 --segI;
81 if (lvrSeg.start >= segI->end)
82 return ++segI;
83 }
84 return segI;
85 }
86 } // end anonymous namespace
87
88 // Private interface accessed by Query.
89 //
90 // Find a pair of segments that intersect, one in the live virtual register
91 // (LiveInterval), and the other in this LiveIntervalUnion. The caller (Query)
92 // is responsible for advancing the LiveIntervalUnion segments to find a
93 // "notable" intersection, which requires query-specific logic.
94 //
95 // This design assumes only a fast mechanism for intersecting a single live
96 // virtual register segment with a set of LiveIntervalUnion segments. This may
97 // be ok since most LVRs have very few segments. If we had a data
98 // structure that optimizd MxN intersection of segments, then we would bypass
99 // the loop that advances within the LiveInterval.
100 //
101 // If no intersection exists, set lvrI = lvrEnd, and set segI to the first
102 // segment whose start point is greater than LiveInterval's end point.
103 //
104 // Assumes that segments are sorted by start position in both
105 // LiveInterval and LiveSegments.
106 void LiveIntervalUnion::Query::findIntersection(InterferenceResult &ir) const {
107 LiveInterval::iterator lvrEnd = lvr_.end();
108 SegmentIter liuEnd = liu_.end();
109 while (ir.liuSegI_ != liuEnd) {
110 // Slowly advance the live virtual reg iterator until we surpass the next
111 // segment in this union. If this is ever used for coalescing of fixed
112 // registers and we have a LiveInterval with thousands of segments, then use
113 // upper bound instead.
114 while (ir.lvrSegI_ != lvrEnd && ir.lvrSegI_->end <= ir.liuSegI_->start)
115 ++ir.lvrSegI_;
116 if (ir.lvrSegI_ == lvrEnd)
117 break;
118 // lvrSegI_ may have advanced far beyond liuSegI_,
119 // do a fast intersection test to "catch up"
120 ir.liuSegI_ = upperBound(ir.liuSegI_, liuEnd, *ir.lvrSegI_);
121 // Check if no liuSegI_ exists with lvrSegI_->start < liuSegI_.end
122 if (ir.liuSegI_ == liuEnd)
123 break;
124 if (ir.liuSegI_->start < ir.lvrSegI_->end) {
125 assert(overlap(*ir.lvrSegI_, *ir.liuSegI_) && "upperBound postcondition");
126 break;
127 }
128 }
129 if (ir.liuSegI_ == liuEnd)
130 ir.lvrSegI_ = lvrEnd;
131 }
132
133 // Find the first intersection, and cache interference info
134 // (retain segment iterators into both lvr_ and liu_).
135 LiveIntervalUnion::InterferenceResult
136 LiveIntervalUnion::Query::firstInterference() {
137 if (firstInterference_ != LiveIntervalUnion::InterferenceResult()) {
138 return firstInterference_;
139 }
140 firstInterference_ = InterferenceResult(lvr_.begin(), liu_.begin());
141 findIntersection(firstInterference_);
142 return firstInterference_;
143 }
144
145 // Treat the result as an iterator and advance to the next interfering pair
146 // of segments. This is a plain iterator with no filter.
147 bool LiveIntervalUnion::Query::nextInterference(InterferenceResult &ir) const {
148 assert(isInterference(ir) && "iteration past end of interferences");
149 // Advance either the lvr or liu segment to ensure that we visit all unique
150 // overlapping pairs.
151 if (ir.lvrSegI_->end < ir.liuSegI_->end) {
152 if (++ir.lvrSegI_ == lvr_.end())
153 return false;
154 }
155 else {
156 if (++ir.liuSegI_ == liu_.end()) {
157 ir.lvrSegI_ = lvr_.end();
158 return false;
159 }
160 }
161 if (overlap(*ir.lvrSegI_, *ir.liuSegI_))
162 return true;
163 // find the next intersection
164 findIntersection(ir);
165 return isInterference(ir);
166 }
0 //===-- LiveIntervalUnion.h - Live interval union data struct --*- C++ -*--===//
1 //
2 // The LLVM Compiler Infrastructure
3 //
4 // This file is distributed under the University of Illinois Open Source
5 // License. See LICENSE.TXT for details.
6 //
7 //===----------------------------------------------------------------------===//
8 //
9 // LiveIntervalUnion is a union of live segments across multiple live virtual
10 // registers. This may be used during coalescing to represent a congruence
11 // class, or during register allocation to model liveness of a physical
12 // register.
13 //
14 //===----------------------------------------------------------------------===//
15
16 #ifndef LLVM_CODEGEN_LIVEINTERVALUNION
17 #define LLVM_CODEGEN_LIVEINTERVALUNION
18
19 #include "llvm/CodeGen/LiveInterval.h"
20 #include
21 #include
22
23 namespace llvm {
24
25 // A LiveSegment is a copy of a LiveRange object used within
26 // LiveIntervalUnion. LiveSegment additionally contains a pointer to its
27 // original live virtual register (LiveInterval). This allows quick lookup of
28 // the live virtual register as we iterate over live segments in a union. Note
29 // that LiveRange is misnamed and actually represents only a single contiguous
30 // interval within a virtual register's liveness. To limit confusion, in this
31 // file we refer it as a live segment.
32 struct LiveSegment {
33 SlotIndex start;
34 SlotIndex end;
35 LiveInterval *liveVirtReg;
36
37 LiveSegment(SlotIndex s, SlotIndex e, LiveInterval &lvr)
38 : start(s), end(e), liveVirtReg(&lvr) {}
39
40 bool operator==(const LiveSegment &ls) const {
41 return start == ls.start && end == ls.end && liveVirtReg == ls.liveVirtReg;
42 }
43
44 bool operator!=(const LiveSegment &ls) const {
45 return !operator==(ls);
46 }
47
48 bool operator<(const LiveSegment &ls) const {
49 return start < ls.start || (start == ls.start && end < ls.end);
50 }
51 };
52
53 /// Compare a live virtual register segment to a LiveIntervalUnion segment.
54 inline bool overlap(const LiveRange &lvrSeg, const LiveSegment &liuSeg) {
55 return lvrSeg.start < liuSeg.end && liuSeg.start < lvrSeg.end;
56 }
57
58 inline bool operator<(SlotIndex V, const LiveSegment &ls) {
59 return V < ls.start;
60 }
61
62 inline bool operator<(const LiveSegment &ls, SlotIndex V) {
63 return ls.start < V;
64 }
65
66 /// Union of live intervals that are strong candidates for coalescing into a
67 /// single register (either physical or virtual depending on the context). We
68 /// expect the constituent live intervals to be disjoint, although we may
69 /// eventually make exceptions to handle value-based interference.
70 class LiveIntervalUnion {
71 // A set of live virtual register segments that supports fast insertion,
72 // intersection, and removal.
73 //
74 // FIXME: std::set is a placeholder until we decide how to
75 // efficiently represent it. Probably need to roll our own B-tree.
76 typedef std::set LiveSegments;
77
78 // A set of live virtual registers. Elements have type LiveInterval, where
79 // each element represents the liveness of a single live virtual register.
80 // This is traditionally known as a live range, but we refer is as a live
81 // virtual register to avoid confusing it with the misnamed LiveRange
82 // class.
83 typedef std::vector LiveVirtRegs;
84
85 public:
86 // SegmentIter can advance to the next segment ordered by starting position
87 // which may belong to a different live virtual register. We also must be able
88 // to reach the current segment's containing virtual register.
89 typedef LiveSegments::iterator SegmentIter;
90
91 class InterferenceResult;
92 class Query;
93
94 private:
95 unsigned repReg_; // representative register number
96 LiveSegments segments_; // union of virtual reg segements
97 LiveVirtRegs lvrs_; // set of live virtual regs in the union
98
99 public:
100 // default ctor avoids placement new
101 LiveIntervalUnion() : repReg_(0) {}
102
103 void init(unsigned repReg) { repReg_ = repReg; }
104
105 SegmentIter begin() { return segments_.begin(); }
106 SegmentIter end() { return segments_.end(); }
107
108 /// FIXME: !!!!!!!!!!! Keeps a non-const ref
109 void unify(LiveInterval &lvr);
110
111 // FIXME: needed by RegAllocGreedy
112 //void extract(const LiveInterval &li);
113
114 /// Cache a single interference test result in the form of two intersecting
115 /// segments. This allows efficiently iterating over the interferences. The
116 /// iteration logic is handled by LiveIntervalUnion::Query which may
117 /// filter interferences depending on the type of query.
118 class InterferenceResult {
119 friend class Query;
120
121 LiveInterval::iterator lvrSegI_; // current position in _lvr
122 SegmentIter liuSegI_; // current position in _liu
123
124 // Internal ctor.
125 InterferenceResult(LiveInterval::iterator lvrSegI, SegmentIter liuSegI)
126 : lvrSegI_(lvrSegI), liuSegI_(liuSegI) {}
127
128 public:
129 // Public default ctor.
130 InterferenceResult(): lvrSegI_(), liuSegI_() {}
131
132 // Note: this interface provides raw access to the iterators because the
133 // result has no way to tell if it's valid to dereference them.
134
135 // Access the lvr segment.
136 const LiveInterval::iterator &lvrSegPos() const { return lvrSegI_; }
137
138 // Access the liu segment.
139 const SegmentIter &liuSeg() const { return liuSegI_; }
140
141 bool operator==(const InterferenceResult &ir) const {
142 return lvrSegI_ == ir.lvrSegI_ && liuSegI_ == ir.liuSegI_;
143 }
144 bool operator!=(const InterferenceResult &ir) const {
145 return !operator==(ir);
146 }
147 };
148
149 /// Query interferences between a single live virtual register and a live
150 /// interval union.
151 class Query {
152 LiveIntervalUnion &liu_;
153 LiveInterval &lvr_;
154 InterferenceResult firstInterference_;
155 // TBD: interfering vregs
156
157 public:
158 Query(LiveInterval &lvr, LiveIntervalUnion &liu): liu_(liu), lvr_(lvr) {}
159
160 LiveInterval &lvr() const { return lvr_; }
161
162 bool isInterference(const InterferenceResult &ir) const {
163 if (ir.lvrSegI_ != lvr_.end()) {
164 assert(overlap(*ir.lvrSegI_, *ir.liuSegI_) &&
165 "invalid segment iterators");
166 return true;
167 }
168 return false;
169 }
170
171 // Does this live virtual register interfere with the union.
172 bool checkInterference() { return isInterference(firstInterference()); }
173
174 // First pair of interfering segments, or a noninterfering result.
175 InterferenceResult firstInterference();
176
177 // Treat the result as an iterator and advance to the next interfering pair
178 // of segments. Visiting each unique interfering pairs means that the same
179 // lvr or liu segment may be visited multiple times.
180 bool nextInterference(InterferenceResult &ir) const;
181
182 // TBD: bool collectInterferingVirtRegs(unsigned maxInterference)
183
184 private:
185 // Private interface for queries
186 void findIntersection(InterferenceResult &ir) const;
187 };
188 };
189
190 } // end namespace llvm
191
192 #endif // !defined(LLVM_CODEGEN_LIVEINTERVALUNION)
0 //===-- RegAllocBase.h - basic regalloc interface and driver --*- C++ -*---===//
1 //
2 // The LLVM Compiler Infrastructure
3 //
4 // This file is distributed under the University of Illinois Open Source
5 // License. See LICENSE.TXT for details.
6 //
7 //===----------------------------------------------------------------------===//
8 //
9 // This file defines the RegAllocBase class, which is the skeleton of a basic
10 // register allocation algorithm and interface for extending it. It provides the
11 // building blocks on which to construct other experimental allocators and test
12 // the validity of two principles:
13 //
14 // - If virtual and physical register liveness is modeled using intervals, then
15 // on-the-fly interference checking is cheap. Furthermore, interferences can be
16 // lazily cached and reused.
17 //
18 // - Register allocation complexity, and generated code performance is
19 // determined by the effectiveness of live range splitting rather than optimal
20 // coloring.
21 //
22 // Following the first principle, interfering checking revolves around the
23 // LiveIntervalUnion data structure.
24 //
25 // To fulfill the second principle, the basic allocator provides a driver for
26 // incremental splitting. It essentially punts on the problem of register
27 // coloring, instead driving the assignment of virtual to physical registers by
28 // the cost of splitting. The basic allocator allows for heuristic reassignment
29 // of registers, if a more sophisticated allocator chooses to do that.
30 //
31 // This framework provides a way to engineer the compile time vs. code
32 // quality trade-off without relying a particular theoretical solver.
33 //
34 //===----------------------------------------------------------------------===//
35
36 #ifndef LLVM_CODEGEN_REGALLOCBASE
37 #define LLVM_CODEGEN_REGALLOCBASE
38
39 #include "LiveIntervalUnion.h"
40 #include "VirtRegMap.h"
41 #include "llvm/CodeGen/LiveIntervalAnalysis.h"
42 #include "llvm/Target/TargetRegisterInfo.h"
43 #include "llvm/ADT/OwningPtr.h"
44 #include
45 #include
46
47 namespace llvm {
48
49 class VirtRegMap;
50
51 /// RegAllocBase provides the register allocation driver and interface that can
52 /// be extended to add interesting heuristics.
53 ///
54 /// More sophisticated allocators must override the selectOrSplit() method to
55 /// implement live range splitting and must specify a comparator to determine
56 /// register assignment priority. LessSpillWeightPriority is provided as a
57 /// standard comparator.
58 class RegAllocBase {
59 protected:
60 typedef SmallVector LiveVirtRegs;
61 typedef LiveVirtRegs::iterator LVRIter;
62
63 // Array of LiveIntervalUnions indexed by physical register.
64 class LIUArray {
65 unsigned nRegs_;
66 OwningArrayPtr array_;
67 public:
68 LIUArray(): nRegs_(0) {}
69
70 unsigned numRegs() const { return nRegs_; }
71
72 void init(unsigned nRegs);
73
74 void clear();
75
76 LiveIntervalUnion& operator[](unsigned physReg) {
77 assert(physReg < nRegs_ && "physReg out of bounds");
78 return array_[physReg];
79 }
80 };
81
82 const TargetRegisterInfo *tri_;
83 VirtRegMap *vrm_;
84 LiveIntervals *lis_;
85 LIUArray physReg2liu_;
86
87 RegAllocBase(): tri_(0), vrm_(0), lis_(0) {}
88
89 // A RegAlloc pass should call this before allocatePhysRegs.
90 void init(const TargetRegisterInfo &tri, VirtRegMap &vrm, LiveIntervals &lis);
91
92 // The top-level driver. Specialize with the comparator that determines the
93 // priority of assigning live virtual registers. The output is a VirtRegMap
94 // that us updated with physical register assignments.
95 template
96 void allocatePhysRegs(LICompare liCompare);
97
98 // A RegAlloc pass should override this to provide the allocation heuristics.
99 // Each call must guarantee forward progess by returning an available
100 // PhysReg or new set of split LiveVirtRegs. It is up to the splitter to
101 // converge quickly toward fully spilled live ranges.
102 virtual unsigned selectOrSplit(LiveInterval &lvr,
103 LiveVirtRegs &splitLVRs) = 0;
104
105 // A RegAlloc pass should call this when PassManager releases its memory.
106 virtual void releaseMemory();
107
108 // Helper for checking interference between a live virtual register and a
109 // physical register, including all its register aliases.
110 bool checkPhysRegInterference(LiveIntervalUnion::Query &query, unsigned preg);
111
112 private:
113 template
114 void seedLiveVirtRegs(PQ &lvrQ);
115 };
116
117 // Heuristic that determines the priority of assigning virtual to physical
118 // registers. The main impact of the heuristic is expected to be compile time.
119 // The default is to simply compare spill weights.
120 struct LessSpillWeightPriority
121 : public std::binary_function {
122 bool operator()(const LiveInterval *left, const LiveInterval *right) const {
123 return left->weight < right->weight;
124 }
125 };
126
127 // Visit all the live virtual registers. If they are already assigned to a
128 // physical register, unify them with the corresponding LiveIntervalUnion,
129 // otherwise push them on the priority queue for later assignment.
130 template
131 void RegAllocBase::seedLiveVirtRegs(PQ &lvrQ) {
132 for (LiveIntervals::iterator liItr = lis_->begin(), liEnd = lis_->end();
133 liItr != liEnd; ++liItr) {
134 unsigned reg = liItr->first;
135 LiveInterval &li = *liItr->second;
136 if (TargetRegisterInfo::isPhysicalRegister(reg)) {
137 physReg2liu_[reg].unify(li);
138 }
139 else {
140 lvrQ.push(&li);
141 }
142 }
143 }
144
145 // Top-level driver to manage the queue of unassigned LiveVirtRegs and call the
146 // selectOrSplit implementation.
147 template
148 void RegAllocBase::allocatePhysRegs(LICompare liCompare) {
149 typedef std::priority_queue
150 , LICompare> LiveVirtRegQueue;
151
152 LiveVirtRegQueue lvrQ(liCompare);
153 seedLiveVirtRegs(lvrQ);
154 while (!lvrQ.empty()) {
155 LiveInterval *lvr = lvrQ.top();
156 lvrQ.pop();
157 LiveVirtRegs splitLVRs;
158 unsigned availablePhysReg = selectOrSplit(*lvr, splitLVRs);
159 if (availablePhysReg) {
160 assert(splitLVRs.empty() && "inconsistent splitting");
161 assert(!vrm_->hasPhys(lvr->reg) && "duplicate vreg in interval unions");
162 vrm_->assignVirt2Phys(lvr->reg, availablePhysReg);
163 physReg2liu_[availablePhysReg].unify(*lvr);
164 }
165 else {
166 for (LVRIter lvrI = splitLVRs.begin(), lvrEnd = splitLVRs.end();
167 lvrI != lvrEnd; ++lvrI ) {
168 assert(TargetRegisterInfo::isVirtualRegister((*lvrI)->reg) &&
169 "expect split value in virtual register");
170 lvrQ.push(*lvrI);
171 }
172 }
173 }
174 }
175
176 } // end namespace llvm
177
178 #endif // !defined(LLVM_CODEGEN_REGALLOCBASE)
0 //===-- RegAllocBasic.cpp - basic register allocator ----------------------===//
1 //
2 // The LLVM Compiler Infrastructure
3 //
4 // This file is distributed under the University of Illinois Open Source
5 // License. See LICENSE.TXT for details.
6 //
7 //===----------------------------------------------------------------------===//
8 //
9 // This file defines the RABasic function pass, which provides a minimal
10 // implementation of the basic register allocator.
11 //
12 //===----------------------------------------------------------------------===//
13
14 #define DEBUG_TYPE "regalloc"
15 #include "RegAllocBase.h"
16 #include "RenderMachineFunction.h"
17 #include "Spiller.h"
18 #include "VirtRegRewriter.h"
19 #include "llvm/Function.h"
20 #include "llvm/PassAnalysisSupport.h"
21 #include "llvm/CodeGen/CalcSpillWeights.h"
22 #include "llvm/CodeGen/LiveStackAnalysis.h"
23 #include "llvm/CodeGen/MachineFunctionPass.h"
24 #include "llvm/CodeGen/MachineInstr.h"
25 #include "llvm/CodeGen/MachineLoopInfo.h"
26 #include "llvm/CodeGen/MachineRegisterInfo.h"
27 #include "llvm/CodeGen/Passes.h"
28 #include "llvm/CodeGen/RegAllocRegistry.h"
29 #include "llvm/CodeGen/RegisterCoalescer.h"
30 #include "llvm/Target/TargetMachine.h"
31 #include "llvm/Target/TargetOptions.h"
32 #include "llvm/Support/Debug.h"
33 #include "llvm/Support/raw_ostream.h"
34
35 using namespace llvm;
36
37 static RegisterRegAlloc basicRegAlloc("basic", "basic register allocator",
38 createBasicRegisterAllocator);
39
40 namespace {
41
42 /// RABasic provides a minimal implementation of the basic register allocation
43 /// algorithm. It prioritizes live virtual registers by spill weight and spills
44 /// whenever a register is unavailable. This is not practical in production but
45 /// provides a useful baseline both for measuring other allocators and comparing
46 /// the speed of the basic algorithm against other styles of allocators.
47 class RABasic : public MachineFunctionPass, public RegAllocBase
48 {
49 // context
50 MachineFunction *mf_;
51 const TargetMachine *tm_;
52 MachineRegisterInfo *mri_;
53
54 // analyses
55 LiveStacks *ls_;
56 RenderMachineFunction *rmf_;
57
58 // state
59 std::auto_ptr spiller_;
60
61 public:
62 RABasic();
63
64 /// Return the pass name.
65 virtual const char* getPassName() const {
66 return "Basic Register Allocator";
67 }
68
69 /// RABasic analysis usage.
70 virtual void getAnalysisUsage(AnalysisUsage &au) const;
71
72 virtual void releaseMemory();
73
74 virtual unsigned selectOrSplit(LiveInterval &lvr, LiveVirtRegs &splitLVRs);
75
76 /// Perform register allocation.
77 virtual bool runOnMachineFunction(MachineFunction &mf);
78
79 static char ID;
80 };
81
82 char RABasic::ID = 0;
83
84 } // end anonymous namespace
85
86 // We should not need to publish the initializer as long as no other passes
87 // require RABasic.
88 #if 0 // disable INITIALIZE_PASS
89 INITIALIZE_PASS_BEGIN(RABasic, "basic-regalloc",
90 "Basic Register Allocator", false, false)
91 INITIALIZE_PASS_DEPENDENCY(LiveIntervals)
92 INITIALIZE_PASS_DEPENDENCY(StrongPHIElimination)
93 INITIALIZE_AG_DEPENDENCY(RegisterCoalescer)
94 INITIALIZE_PASS_DEPENDENCY(CalculateSpillWeights)
95 INITIALIZE_PASS_DEPENDENCY(LiveStacks)
96 INITIALIZE_PASS_DEPENDENCY(MachineLoopInfo)
97 INITIALIZE_PASS_DEPENDENCY(VirtRegMap)
98 #ifndef NDEBUG
99 INITIALIZE_PASS_DEPENDENCY(RenderMachineFunction)
100 #endif
101 INITIALIZE_PASS_END(RABasic, "basic-regalloc",
102 "Basic Register Allocator", false, false)
103 #endif // INITIALIZE_PASS
104
105 RABasic::RABasic(): MachineFunctionPass(ID) {
106 initializeLiveIntervalsPass(*PassRegistry::getPassRegistry());
107 initializeSlotIndexesPass(*PassRegistry::getPassRegistry());
108 initializeStrongPHIEliminationPass(*PassRegistry::getPassRegistry());
109 initializeRegisterCoalescerAnalysisGroup(*PassRegistry::getPassRegistry());
110 initializeCalculateSpillWeightsPass(*PassRegistry::getPassRegistry());
111 initializeLiveStacksPass(*PassRegistry::getPassRegistry());
112 initializeMachineLoopInfoPass(*PassRegistry::getPassRegistry());
113 initializeVirtRegMapPass(*PassRegistry::getPassRegistry());
114 initializeRenderMachineFunctionPass(*PassRegistry::getPassRegistry());
115 }
116
117 void RABasic::getAnalysisUsage(AnalysisUsage &au) const {
118 au.setPreservesCFG();
119 au.addRequired();
120 au.addPreserved();
121 if (StrongPHIElim)
122 au.addRequiredID(StrongPHIEliminationID);
123 au.addRequiredTransitive();
124 au.addRequired();
125 au.addRequired();
126 au.addPreserved();
127 au.addRequired();
128 au.addPreserved();
129 au.addRequired();
130 au.addPreserved();
131 DEBUG(au.addRequired());
132 MachineFunctionPass::getAnalysisUsage(au);
133 }
134
135 void RABasic::releaseMemory() {
136 spiller_.reset(0);
137 RegAllocBase::releaseMemory();
138 }
139
140 //===----------------------------------------------------------------------===//
141 // RegAllocBase Implementation
142 //===----------------------------------------------------------------------===//
143
144 // Instantiate a LiveIntervalUnion for each physical register.
145 void RegAllocBase::LIUArray::init(unsigned nRegs) {
146 array_.reset(new LiveIntervalUnion[nRegs]);
147 nRegs_ = nRegs;
148 for (unsigned pr = 0; pr < nRegs; ++pr) {
149 array_[pr].init(pr);
150 }
151 }
152
153 void RegAllocBase::init(const TargetRegisterInfo &tri, VirtRegMap &vrm,
154 LiveIntervals &lis) {
155 tri_ = &tri;
156 vrm_ = &vrm;
157 lis_ = &lis;
158 physReg2liu_.init(tri_->getNumRegs());
159 }
160
161 void RegAllocBase::LIUArray::clear() {
162 nRegs_ = 0;
163 array_.reset(0);
164 }
165
166 void RegAllocBase::releaseMemory() {
167 physReg2liu_.clear();
168 }
169
170 // Check if this live virtual reg interferes with a physical register. If not,
171 // then check for interference on each register that aliases with the physical
172 // register.
173 bool RegAllocBase::checkPhysRegInterference(LiveIntervalUnion::Query &query,
174 unsigned preg) {
175 if (query.checkInterference())
176 return true;
177 for (const unsigned *asI = tri_->getAliasSet(preg); *asI; ++asI) {
178 // We assume it's very unlikely for a register in the alias set to also be
179 // in the original register class. So we don't bother caching the
180 // interference.
181 LiveIntervalUnion::Query subQuery(query.lvr(), physReg2liu_[*asI] );
182 if (subQuery.checkInterference())
183 return true;
184 }
185 return false;
186 }
187
188 //===----------------------------------------------------------------------===//
189 // RABasic Implementation
190 //===----------------------------------------------------------------------===//
191
192 // Driver for the register assignment and splitting heuristics.
193 // Manages iteration over the LiveIntervalUnions.
194 //
195 // Minimal implementation of register assignment and splitting--spills whenever
196 // we run out of registers.
197 //
198 // selectOrSplit can only be called once per live virtual register. We then do a
199 // single interference test for each register the correct class until we find an
200 // available register. So, the number of interference tests in the worst case is
201 // |vregs| * |machineregs|. And since the number of interference tests is
202 // minimal, there is no value in caching them.
203 unsigned RABasic::selectOrSplit(LiveInterval &lvr, LiveVirtRegs &splitLVRs) {
204 // Check for an available reg in this class.
205 const TargetRegisterClass *trc = mri_->getRegClass(lvr.reg);
206 for (TargetRegisterClass::iterator trcI = trc->allocation_order_begin(*mf_),
207 trcEnd = trc->allocation_order_end(*mf_);
208 trcI != trcEnd; ++trcI) {
209 unsigned preg = *trcI;
210 LiveIntervalUnion::Query query(lvr, physReg2liu_[preg]);
211 if (!checkPhysRegInterference(query, preg)) {
212 DEBUG(dbgs() << "\tallocating: " << tri_->getName(preg) << lvr << '\n');
213 return preg;
214 }
215 }
216 DEBUG(dbgs() << "\tspilling: " << lvr << '\n');
217 SmallVector spillIs; // ignored
218 spiller_->spill(&lvr, splitLVRs, spillIs);
219
220 // FIXME: update LiveStacks
221 return 0;
222 }
223
224 bool RABasic::runOnMachineFunction(MachineFunction &mf) {
225 DEBUG(dbgs() << "********** BASIC REGISTER ALLOCATION **********\n"
226 << "********** Function: "
227 << ((Value*)mf.getFunction())->getName() << '\n');
228
229 mf_ = &mf;
230 tm_ = &mf.getTarget();
231 mri_ = &mf.getRegInfo();
232
233 DEBUG(rmf_ = &getAnalysis());
234
235 RegAllocBase::init(*tm_->getRegisterInfo(), getAnalysis(),
236 getAnalysis());
237
238 spiller_.reset(createSpiller(*this, *mf_, *vrm_));
239
240 allocatePhysRegs(LessSpillWeightPriority());
241
242 // Diagnostic output before rewriting
243 DEBUG(dbgs() << "Post alloc VirtRegMap:\n" << *vrm_ << "\n");
244
245 // optional HTML output
246 DEBUG(rmf_->renderMachineFunction("After basic register allocation.", vrm_));
247
248 // Run rewriter
249 std::auto_ptr rewriter(createVirtRegRewriter());
250 rewriter->runOnMachineFunction(*mf_, *vrm_, lis_);
251
252 return true;
253 }
254
255 FunctionPass* llvm::createBasicRegisterAllocator()
256 {
257 return new RABasic();
258 }
None //===---------- SplitKit.cpp - Toolkit for splitting live ranges ----------===//
0 //===-------- SplitKit.cpp - Toolkit for splitting live ranges --*- C++ -*-===//
11 //
22 // The LLVM Compiler Infrastructure
33 //