2 * Copyright 2011 Christoph Bumiller
4 * Permission is hereby granted, free of charge, to any person obtaining a
5 * copy of this software and associated documentation files (the "Software"),
6 * to deal in the Software without restriction, including without limitation
7 * the rights to use, copy, modify, merge, publish, distribute, sublicense,
8 * and/or sell copies of the Software, and to permit persons to whom the
9 * Software is furnished to do so, subject to the following conditions:
11 * The above copyright notice and this permission notice shall be included in
12 * all copies or substantial portions of the Software.
14 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
15 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
16 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
17 * THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR
18 * OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE,
19 * ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
20 * OTHER DEALINGS IN THE SOFTWARE.
23 #include "codegen/nv50_ir.h"
24 #include "codegen/nv50_ir_target.h"
31 #define MAX_REGISTER_FILE_SIZE 256
36 RegisterSet(const Target
*);
38 void init(const Target
*);
39 void reset(DataFile
, bool resetMax
= false);
41 void periodicMask(DataFile f
, uint32_t lock
, uint32_t unlock
);
42 void intersect(DataFile f
, const RegisterSet
*);
44 bool assign(int32_t& reg
, DataFile f
, unsigned int size
);
45 void release(DataFile f
, int32_t reg
, unsigned int size
);
46 void occupy(DataFile f
, int32_t reg
, unsigned int size
);
47 void occupy(const Value
*);
48 void occupyMask(DataFile f
, int32_t reg
, uint8_t mask
);
49 bool isOccupied(DataFile f
, int32_t reg
, unsigned int size
) const;
50 bool testOccupy(const Value
*);
51 bool testOccupy(DataFile f
, int32_t reg
, unsigned int size
);
53 inline int getMaxAssigned(DataFile f
) const { return fill
[f
]; }
55 inline unsigned int getFileSize(DataFile f
, uint8_t regSize
) const
57 if (restrictedGPR16Range
&& f
== FILE_GPR
&& regSize
== 2)
58 return (last
[f
] + 1) / 2;
62 inline unsigned int units(DataFile f
, unsigned int size
) const
64 return size
>> unit
[f
];
66 // for regs of size >= 4, id is counted in 4-byte words (like nv50/c0 binary)
67 inline unsigned int idToBytes(const Value
*v
) const
69 return v
->reg
.data
.id
* MIN2(v
->reg
.size
, 4);
71 inline unsigned int idToUnits(const Value
*v
) const
73 return units(v
->reg
.file
, idToBytes(v
));
75 inline int bytesToId(Value
*v
, unsigned int bytes
) const
78 return units(v
->reg
.file
, bytes
);
81 inline int unitsToId(DataFile f
, int u
, uint8_t size
) const
85 return (size
< 4) ? u
: ((u
<< unit
[f
]) / 4);
91 BitSet bits
[LAST_REGISTER_FILE
+ 1];
93 int unit
[LAST_REGISTER_FILE
+ 1]; // log2 of allocation granularity
95 int last
[LAST_REGISTER_FILE
+ 1];
96 int fill
[LAST_REGISTER_FILE
+ 1];
98 const bool restrictedGPR16Range
;
102 RegisterSet::reset(DataFile f
, bool resetMax
)
110 RegisterSet::init(const Target
*targ
)
112 for (unsigned int rf
= 0; rf
<= FILE_ADDRESS
; ++rf
) {
113 DataFile f
= static_cast<DataFile
>(rf
);
114 last
[rf
] = targ
->getFileSize(f
) - 1;
115 unit
[rf
] = targ
->getFileUnit(f
);
117 assert(last
[rf
] < MAX_REGISTER_FILE_SIZE
);
118 bits
[rf
].allocate(last
[rf
] + 1, true);
122 RegisterSet::RegisterSet(const Target
*targ
)
123 : restrictedGPR16Range(targ
->getChipset() < 0xc0)
126 for (unsigned int i
= 0; i
<= LAST_REGISTER_FILE
; ++i
)
127 reset(static_cast<DataFile
>(i
));
131 RegisterSet::periodicMask(DataFile f
, uint32_t lock
, uint32_t unlock
)
133 bits
[f
].periodicMask32(lock
, unlock
);
137 RegisterSet::intersect(DataFile f
, const RegisterSet
*set
)
139 bits
[f
] |= set
->bits
[f
];
143 RegisterSet::print() const
146 bits
[FILE_GPR
].print();
151 RegisterSet::assign(int32_t& reg
, DataFile f
, unsigned int size
)
153 reg
= bits
[f
].findFreeRange(size
);
156 fill
[f
] = MAX2(fill
[f
], (int32_t)(reg
+ size
- 1));
161 RegisterSet::isOccupied(DataFile f
, int32_t reg
, unsigned int size
) const
163 return bits
[f
].testRange(reg
, size
);
167 RegisterSet::occupy(const Value
*v
)
169 occupy(v
->reg
.file
, idToUnits(v
), v
->reg
.size
>> unit
[v
->reg
.file
]);
173 RegisterSet::occupyMask(DataFile f
, int32_t reg
, uint8_t mask
)
175 bits
[f
].setMask(reg
& ~31, static_cast<uint32_t>(mask
) << (reg
% 32));
179 RegisterSet::occupy(DataFile f
, int32_t reg
, unsigned int size
)
181 bits
[f
].setRange(reg
, size
);
183 INFO_DBG(0, REG_ALLOC
, "reg occupy: %u[%i] %u\n", f
, reg
, size
);
185 fill
[f
] = MAX2(fill
[f
], (int32_t)(reg
+ size
- 1));
189 RegisterSet::testOccupy(const Value
*v
)
191 return testOccupy(v
->reg
.file
,
192 idToUnits(v
), v
->reg
.size
>> unit
[v
->reg
.file
]);
196 RegisterSet::testOccupy(DataFile f
, int32_t reg
, unsigned int size
)
198 if (isOccupied(f
, reg
, size
))
200 occupy(f
, reg
, size
);
205 RegisterSet::release(DataFile f
, int32_t reg
, unsigned int size
)
207 bits
[f
].clrRange(reg
, size
);
209 INFO_DBG(0, REG_ALLOC
, "reg release: %u[%i] %u\n", f
, reg
, size
);
215 RegAlloc(Program
*program
) : prog(program
), sequence(0) { }
221 class PhiMovesPass
: public Pass
{
223 virtual bool visit(BasicBlock
*);
224 inline bool needNewElseBlock(BasicBlock
*b
, BasicBlock
*p
);
227 class ArgumentMovesPass
: public Pass
{
229 virtual bool visit(BasicBlock
*);
232 class BuildIntervalsPass
: public Pass
{
234 virtual bool visit(BasicBlock
*);
235 void collectLiveValues(BasicBlock
*);
236 void addLiveRange(Value
*, const BasicBlock
*, int end
);
239 class InsertConstraintsPass
: public Pass
{
241 bool exec(Function
*func
);
243 virtual bool visit(BasicBlock
*);
245 bool insertConstraintMoves();
247 void condenseDefs(Instruction
*);
248 void condenseSrcs(Instruction
*, const int first
, const int last
);
250 void addHazard(Instruction
*i
, const ValueRef
*src
);
251 void textureMask(TexInstruction
*);
252 void addConstraint(Instruction
*, int s
, int n
);
253 bool detectConflict(Instruction
*, int s
);
255 // target specific functions, TODO: put in subclass or Target
256 void texConstraintNV50(TexInstruction
*);
257 void texConstraintNVC0(TexInstruction
*);
258 void texConstraintNVE0(TexInstruction
*);
260 std::list
<Instruction
*> constrList
;
265 bool buildLiveSets(BasicBlock
*);
271 // instructions in control flow / chronological order
274 int sequence
; // for manual passes through CFG
277 typedef std::pair
<Value
*, Value
*> ValuePair
;
279 class SpillCodeInserter
282 SpillCodeInserter(Function
*fn
) : func(fn
), stackSize(0), stackBase(0) { }
284 bool run(const std::list
<ValuePair
>&);
286 Symbol
*assignSlot(const Interval
&, const unsigned int size
);
287 Value
*offsetSlot(Value
*, const LValue
*);
288 inline int32_t getStackSize() const { return stackSize
; }
296 std::list
<Value
*> residents
; // needed to recalculate occup
299 inline uint8_t size() const { return sym
->reg
.size
; }
301 std::list
<SpillSlot
> slots
;
305 LValue
*unspill(Instruction
*usei
, LValue
*, Value
*slot
);
306 void spill(Instruction
*defi
, Value
*slot
, LValue
*);
310 RegAlloc::BuildIntervalsPass::addLiveRange(Value
*val
,
311 const BasicBlock
*bb
,
314 Instruction
*insn
= val
->getUniqueInsn();
317 insn
= bb
->getFirst();
319 assert(bb
->getFirst()->serial
<= bb
->getExit()->serial
);
320 assert(bb
->getExit()->serial
+ 1 >= end
);
322 int begin
= insn
->serial
;
323 if (begin
< bb
->getEntry()->serial
|| begin
> bb
->getExit()->serial
)
324 begin
= bb
->getEntry()->serial
;
326 INFO_DBG(prog
->dbgFlags
, REG_ALLOC
, "%%%i <- live range [%i(%i), %i)\n",
327 val
->id
, begin
, insn
->serial
, end
);
329 if (begin
!= end
) // empty ranges are only added as hazards for fixed regs
330 val
->livei
.extend(begin
, end
);
334 RegAlloc::PhiMovesPass::needNewElseBlock(BasicBlock
*b
, BasicBlock
*p
)
336 if (b
->cfg
.incidentCount() <= 1)
340 for (Graph::EdgeIterator ei
= p
->cfg
.outgoing(); !ei
.end(); ei
.next())
341 if (ei
.getType() == Graph::Edge::TREE
||
342 ei
.getType() == Graph::Edge::FORWARD
)
347 // For each operand of each PHI in b, generate a new value by inserting a MOV
348 // at the end of the block it is coming from and replace the operand with its
349 // result. This eliminates liveness conflicts and enables us to let values be
350 // copied to the right register if such a conflict exists nonetheless.
352 // These MOVs are also crucial in making sure the live intervals of phi srces
353 // are extended until the end of the loop, since they are not included in the
356 RegAlloc::PhiMovesPass::visit(BasicBlock
*bb
)
358 Instruction
*phi
, *mov
;
361 std::stack
<BasicBlock
*> stack
;
363 for (Graph::EdgeIterator ei
= bb
->cfg
.incident(); !ei
.end(); ei
.next()) {
364 pb
= BasicBlock::get(ei
.getNode());
366 if (needNewElseBlock(bb
, pb
))
369 while (!stack
.empty()) {
371 pn
= new BasicBlock(func
);
374 pb
->cfg
.detach(&bb
->cfg
);
375 pb
->cfg
.attach(&pn
->cfg
, Graph::Edge::TREE
);
376 pn
->cfg
.attach(&bb
->cfg
, Graph::Edge::FORWARD
);
378 assert(pb
->getExit()->op
!= OP_CALL
);
379 if (pb
->getExit()->asFlow()->target
.bb
== bb
)
380 pb
->getExit()->asFlow()->target
.bb
= pn
;
383 // insert MOVs (phi->src(j) should stem from j-th in-BB)
385 for (Graph::EdgeIterator ei
= bb
->cfg
.incident(); !ei
.end(); ei
.next()) {
386 pb
= BasicBlock::get(ei
.getNode());
387 if (!pb
->isTerminated())
388 pb
->insertTail(new_FlowInstruction(func
, OP_BRA
, bb
));
390 for (phi
= bb
->getPhi(); phi
&& phi
->op
== OP_PHI
; phi
= phi
->next
) {
391 mov
= new_Instruction(func
, OP_MOV
, TYPE_U32
);
393 mov
->setSrc(0, phi
->getSrc(j
));
394 mov
->setDef(0, new_LValue(func
, phi
->getDef(0)->asLValue()));
395 phi
->setSrc(j
, mov
->getDef(0));
397 pb
->insertBefore(pb
->getExit(), mov
);
406 RegAlloc::ArgumentMovesPass::visit(BasicBlock
*bb
)
408 // Bind function call inputs/outputs to the same physical register
409 // the callee uses, inserting moves as appropriate for the case a
411 for (Instruction
*i
= bb
->getEntry(); i
; i
= i
->next
) {
412 FlowInstruction
*cal
= i
->asFlow();
413 // TODO: Handle indirect calls.
414 // Right now they should only be generated for builtins.
415 if (!cal
|| cal
->op
!= OP_CALL
|| cal
->builtin
|| cal
->indirect
)
417 RegisterSet
clobberSet(prog
->getTarget());
419 // Bind input values.
420 for (int s
= cal
->indirect
? 1 : 0; cal
->srcExists(s
); ++s
) {
421 const int t
= cal
->indirect
? (s
- 1) : s
;
422 LValue
*tmp
= new_LValue(func
, cal
->getSrc(s
)->asLValue());
423 tmp
->reg
.data
.id
= cal
->target
.fn
->ins
[t
].rep()->reg
.data
.id
;
426 new_Instruction(func
, OP_MOV
, typeOfSize(tmp
->reg
.size
));
428 mov
->setSrc(0, cal
->getSrc(s
));
431 bb
->insertBefore(cal
, mov
);
434 // Bind output values.
435 for (int d
= 0; cal
->defExists(d
); ++d
) {
436 LValue
*tmp
= new_LValue(func
, cal
->getDef(d
)->asLValue());
437 tmp
->reg
.data
.id
= cal
->target
.fn
->outs
[d
].rep()->reg
.data
.id
;
440 new_Instruction(func
, OP_MOV
, typeOfSize(tmp
->reg
.size
));
442 mov
->setDef(0, cal
->getDef(d
));
445 bb
->insertAfter(cal
, mov
);
446 clobberSet
.occupy(tmp
);
449 // Bind clobbered values.
450 for (std::deque
<Value
*>::iterator it
= cal
->target
.fn
->clobbers
.begin();
451 it
!= cal
->target
.fn
->clobbers
.end();
453 if (clobberSet
.testOccupy(*it
)) {
454 Value
*tmp
= new_LValue(func
, (*it
)->asLValue());
455 tmp
->reg
.data
.id
= (*it
)->reg
.data
.id
;
456 cal
->setDef(cal
->defCount(), tmp
);
461 // Update the clobber set of the function.
462 if (BasicBlock::get(func
->cfgExit
) == bb
) {
463 func
->buildDefSets();
464 for (unsigned int i
= 0; i
< bb
->defSet
.getSize(); ++i
)
465 if (bb
->defSet
.test(i
))
466 func
->clobbers
.push_back(func
->getLValue(i
));
472 // Build the set of live-in variables of bb.
474 RegAlloc::buildLiveSets(BasicBlock
*bb
)
476 Function
*f
= bb
->getFunction();
481 INFO_DBG(prog
->dbgFlags
, REG_ALLOC
, "buildLiveSets(BB:%i)\n", bb
->getId());
483 bb
->liveSet
.allocate(func
->allLValues
.getSize(), false);
486 for (Graph::EdgeIterator ei
= bb
->cfg
.outgoing(); !ei
.end(); ei
.next()) {
487 bn
= BasicBlock::get(ei
.getNode());
490 if (bn
->cfg
.visit(sequence
))
491 if (!buildLiveSets(bn
))
493 if (n
++ || bb
->liveSet
.marker
)
494 bb
->liveSet
|= bn
->liveSet
;
496 bb
->liveSet
= bn
->liveSet
;
498 if (!n
&& !bb
->liveSet
.marker
)
500 bb
->liveSet
.marker
= true;
502 if (prog
->dbgFlags
& NV50_IR_DEBUG_REG_ALLOC
) {
503 INFO("BB:%i live set of out blocks:\n", bb
->getId());
507 // if (!bb->getEntry())
510 if (bb
== BasicBlock::get(f
->cfgExit
)) {
511 for (std::deque
<ValueRef
>::iterator it
= f
->outs
.begin();
512 it
!= f
->outs
.end(); ++it
) {
513 assert(it
->get()->asLValue());
514 bb
->liveSet
.set(it
->get()->id
);
518 for (i
= bb
->getExit(); i
&& i
!= bb
->getEntry()->prev
; i
= i
->prev
) {
519 for (d
= 0; i
->defExists(d
); ++d
)
520 bb
->liveSet
.clr(i
->getDef(d
)->id
);
521 for (s
= 0; i
->srcExists(s
); ++s
)
522 if (i
->getSrc(s
)->asLValue())
523 bb
->liveSet
.set(i
->getSrc(s
)->id
);
525 for (i
= bb
->getPhi(); i
&& i
->op
== OP_PHI
; i
= i
->next
)
526 bb
->liveSet
.clr(i
->getDef(0)->id
);
528 if (prog
->dbgFlags
& NV50_IR_DEBUG_REG_ALLOC
) {
529 INFO("BB:%i live set after propagation:\n", bb
->getId());
537 RegAlloc::BuildIntervalsPass::collectLiveValues(BasicBlock
*bb
)
539 BasicBlock
*bbA
= NULL
, *bbB
= NULL
;
541 if (bb
->cfg
.outgoingCount()) {
542 // trickery to save a loop of OR'ing liveSets
543 // aliasing works fine with BitSet::setOr
544 for (Graph::EdgeIterator ei
= bb
->cfg
.outgoing(); !ei
.end(); ei
.next()) {
545 if (ei
.getType() == Graph::Edge::DUMMY
)
548 bb
->liveSet
.setOr(&bbA
->liveSet
, &bbB
->liveSet
);
553 bbB
= BasicBlock::get(ei
.getNode());
555 bb
->liveSet
.setOr(&bbB
->liveSet
, bbA
? &bbA
->liveSet
: NULL
);
557 if (bb
->cfg
.incidentCount()) {
563 RegAlloc::BuildIntervalsPass::visit(BasicBlock
*bb
)
565 collectLiveValues(bb
);
567 INFO_DBG(prog
->dbgFlags
, REG_ALLOC
, "BuildIntervals(BB:%i)\n", bb
->getId());
569 // go through out blocks and delete phi sources that do not originate from
570 // the current block from the live set
571 for (Graph::EdgeIterator ei
= bb
->cfg
.outgoing(); !ei
.end(); ei
.next()) {
572 BasicBlock
*out
= BasicBlock::get(ei
.getNode());
574 for (Instruction
*i
= out
->getPhi(); i
&& i
->op
== OP_PHI
; i
= i
->next
) {
575 bb
->liveSet
.clr(i
->getDef(0)->id
);
577 for (int s
= 0; i
->srcExists(s
); ++s
) {
578 assert(i
->src(s
).getInsn());
579 if (i
->getSrc(s
)->getUniqueInsn()->bb
== bb
) // XXX: reachableBy ?
580 bb
->liveSet
.set(i
->getSrc(s
)->id
);
582 bb
->liveSet
.clr(i
->getSrc(s
)->id
);
587 // remaining live-outs are live until end
589 for (unsigned int j
= 0; j
< bb
->liveSet
.getSize(); ++j
)
590 if (bb
->liveSet
.test(j
))
591 addLiveRange(func
->getLValue(j
), bb
, bb
->getExit()->serial
+ 1);
594 for (Instruction
*i
= bb
->getExit(); i
&& i
->op
!= OP_PHI
; i
= i
->prev
) {
595 for (int d
= 0; i
->defExists(d
); ++d
) {
596 bb
->liveSet
.clr(i
->getDef(d
)->id
);
597 if (i
->getDef(d
)->reg
.data
.id
>= 0) // add hazard for fixed regs
598 i
->getDef(d
)->livei
.extend(i
->serial
, i
->serial
);
601 for (int s
= 0; i
->srcExists(s
); ++s
) {
602 if (!i
->getSrc(s
)->asLValue())
604 if (!bb
->liveSet
.test(i
->getSrc(s
)->id
)) {
605 bb
->liveSet
.set(i
->getSrc(s
)->id
);
606 addLiveRange(i
->getSrc(s
), bb
, i
->serial
);
611 if (bb
== BasicBlock::get(func
->cfg
.getRoot())) {
612 for (std::deque
<ValueDef
>::iterator it
= func
->ins
.begin();
613 it
!= func
->ins
.end(); ++it
) {
614 if (it
->get()->reg
.data
.id
>= 0) // add hazard for fixed regs
615 it
->get()->livei
.extend(0, 1);
623 #define JOIN_MASK_PHI (1 << 0)
624 #define JOIN_MASK_UNION (1 << 1)
625 #define JOIN_MASK_MOV (1 << 2)
626 #define JOIN_MASK_TEX (1 << 3)
631 GCRA(Function
*, SpillCodeInserter
&);
634 bool allocateRegisters(ArrayList
& insns
);
636 void printNodeInfo() const;
639 class RIG_Node
: public Graph::Node
644 void init(const RegisterSet
&, LValue
*);
646 void addInterference(RIG_Node
*);
647 void addRegPreference(RIG_Node
*);
649 inline LValue
*getValue() const
651 return reinterpret_cast<LValue
*>(data
);
653 inline void setValue(LValue
*lval
) { data
= lval
; }
655 inline uint8_t getCompMask() const
657 return ((1 << colors
) - 1) << (reg
& 7);
660 static inline RIG_Node
*get(const Graph::EdgeIterator
& ei
)
662 return static_cast<RIG_Node
*>(ei
.getNode());
667 uint16_t degreeLimit
; // if deg < degLimit, node is trivially colourable
675 // list pointers for simplify() phase
679 // union of the live intervals of all coalesced values (we want to retain
680 // the separate intervals for testing interference of compound values)
683 std::list
<RIG_Node
*> prefRegs
;
687 inline RIG_Node
*getNode(const LValue
*v
) const { return &nodes
[v
->id
]; }
689 void buildRIG(ArrayList
&);
690 bool coalesce(ArrayList
&);
691 bool doCoalesce(ArrayList
&, unsigned int mask
);
692 void calculateSpillWeights();
694 bool selectRegisters();
695 void cleanup(const bool success
);
697 void simplifyEdge(RIG_Node
*, RIG_Node
*);
698 void simplifyNode(RIG_Node
*);
700 bool coalesceValues(Value
*, Value
*, bool force
);
701 void resolveSplitsAndMerges();
702 void makeCompound(Instruction
*, bool isSplit
);
704 inline void checkInterference(const RIG_Node
*, Graph::EdgeIterator
&);
706 inline void insertOrderedTail(std::list
<RIG_Node
*>&, RIG_Node
*);
707 void checkList(std::list
<RIG_Node
*>&);
710 std::stack
<uint32_t> stack
;
712 // list headers for simplify() phase
718 unsigned int nodeCount
;
723 static uint8_t relDegree
[17][17];
727 // need to fixup register id for participants of OP_MERGE/SPLIT
728 std::list
<Instruction
*> merges
;
729 std::list
<Instruction
*> splits
;
731 SpillCodeInserter
& spill
;
732 std::list
<ValuePair
> mustSpill
;
735 uint8_t GCRA::relDegree
[17][17];
737 GCRA::RIG_Node::RIG_Node() : Node(NULL
), next(this), prev(this)
743 GCRA::printNodeInfo() const
745 for (unsigned int i
= 0; i
< nodeCount
; ++i
) {
746 if (!nodes
[i
].colors
)
748 INFO("RIG_Node[%%%i]($[%u]%i): %u colors, weight %f, deg %u/%u\n X",
750 nodes
[i
].f
,nodes
[i
].reg
,nodes
[i
].colors
,
752 nodes
[i
].degree
, nodes
[i
].degreeLimit
);
754 for (Graph::EdgeIterator ei
= nodes
[i
].outgoing(); !ei
.end(); ei
.next())
755 INFO(" %%%i", RIG_Node::get(ei
)->getValue()->id
);
756 for (Graph::EdgeIterator ei
= nodes
[i
].incident(); !ei
.end(); ei
.next())
757 INFO(" %%%i", RIG_Node::get(ei
)->getValue()->id
);
763 GCRA::RIG_Node::init(const RegisterSet
& regs
, LValue
*lval
)
766 if (lval
->reg
.data
.id
>= 0)
767 lval
->noSpill
= lval
->fixedReg
= 1;
769 colors
= regs
.units(lval
->reg
.file
, lval
->reg
.size
);
772 if (lval
->reg
.data
.id
>= 0)
773 reg
= regs
.idToUnits(lval
);
775 weight
= std::numeric_limits
<float>::infinity();
777 degreeLimit
= regs
.getFileSize(f
, lval
->reg
.size
);
778 degreeLimit
-= relDegree
[1][colors
] - 1;
780 livei
.insert(lval
->livei
);
784 GCRA::coalesceValues(Value
*dst
, Value
*src
, bool force
)
786 LValue
*rep
= dst
->join
->asLValue();
787 LValue
*val
= src
->join
->asLValue();
789 if (!force
&& val
->reg
.data
.id
>= 0) {
790 rep
= src
->join
->asLValue();
791 val
= dst
->join
->asLValue();
793 RIG_Node
*nRep
= &nodes
[rep
->id
];
794 RIG_Node
*nVal
= &nodes
[val
->id
];
796 if (src
->reg
.file
!= dst
->reg
.file
) {
799 WARN("forced coalescing of values in different files !\n");
801 if (!force
&& dst
->reg
.size
!= src
->reg
.size
)
804 if ((rep
->reg
.data
.id
>= 0) && (rep
->reg
.data
.id
!= val
->reg
.data
.id
)) {
806 if (val
->reg
.data
.id
>= 0)
807 WARN("forced coalescing of values in different fixed regs !\n");
809 if (val
->reg
.data
.id
>= 0)
811 // make sure that there is no overlap with the fixed register of rep
812 for (ArrayList::Iterator it
= func
->allLValues
.iterator();
813 !it
.end(); it
.next()) {
814 Value
*reg
= reinterpret_cast<Value
*>(it
.get())->asLValue();
816 if (reg
->interfers(rep
) && reg
->livei
.overlaps(nVal
->livei
))
822 if (!force
&& nRep
->livei
.overlaps(nVal
->livei
))
825 INFO_DBG(prog
->dbgFlags
, REG_ALLOC
, "joining %%%i($%i) <- %%%i\n",
826 rep
->id
, rep
->reg
.data
.id
, val
->id
);
828 // set join pointer of all values joined with val
829 for (Value::DefIterator def
= val
->defs
.begin(); def
!= val
->defs
.end();
831 (*def
)->get()->join
= rep
;
832 assert(rep
->join
== rep
&& val
->join
== rep
);
834 // add val's definitions to rep and extend the live interval of its RIG node
835 rep
->defs
.insert(rep
->defs
.end(), val
->defs
.begin(), val
->defs
.end());
836 nRep
->livei
.unify(nVal
->livei
);
841 GCRA::coalesce(ArrayList
& insns
)
843 bool ret
= doCoalesce(insns
, JOIN_MASK_PHI
);
846 switch (func
->getProgram()->getTarget()->getChipset() & ~0xf) {
851 ret
= doCoalesce(insns
, JOIN_MASK_UNION
| JOIN_MASK_TEX
);
858 ret
= doCoalesce(insns
, JOIN_MASK_UNION
);
865 return doCoalesce(insns
, JOIN_MASK_MOV
);
868 static inline uint8_t makeCompMask(int compSize
, int base
, int size
)
870 uint8_t m
= ((1 << size
) - 1) << base
;
882 assert(compSize
<= 8);
887 // Used when coalescing moves. The non-compound value will become one, e.g.:
888 // mov b32 $r0 $r2 / merge b64 $r0d { $r0 $r1 }
889 // split b64 { $r0 $r1 } $r0d / mov b64 $r0d f64 $r2d
890 static inline void copyCompound(Value
*dst
, Value
*src
)
892 LValue
*ldst
= dst
->asLValue();
893 LValue
*lsrc
= src
->asLValue();
895 if (ldst
->compound
&& !lsrc
->compound
) {
901 ldst
->compound
= lsrc
->compound
;
902 ldst
->compMask
= lsrc
->compMask
;
906 GCRA::makeCompound(Instruction
*insn
, bool split
)
908 LValue
*rep
= (split
? insn
->getSrc(0) : insn
->getDef(0))->asLValue();
910 if (prog
->dbgFlags
& NV50_IR_DEBUG_REG_ALLOC
) {
911 INFO("makeCompound(split = %i): ", split
);
915 const unsigned int size
= getNode(rep
)->colors
;
916 unsigned int base
= 0;
919 rep
->compMask
= 0xff;
922 for (int c
= 0; split
? insn
->defExists(c
) : insn
->srcExists(c
); ++c
) {
923 LValue
*val
= (split
? insn
->getDef(c
) : insn
->getSrc(c
))->asLValue();
927 val
->compMask
= 0xff;
928 val
->compMask
&= makeCompMask(size
, base
, getNode(val
)->colors
);
929 assert(val
->compMask
);
931 INFO_DBG(prog
->dbgFlags
, REG_ALLOC
, "compound: %%%i:%02x <- %%%i:%02x\n",
932 rep
->id
, rep
->compMask
, val
->id
, val
->compMask
);
934 base
+= getNode(val
)->colors
;
936 assert(base
== size
);
940 GCRA::doCoalesce(ArrayList
& insns
, unsigned int mask
)
944 for (n
= 0; n
< insns
.getSize(); ++n
) {
946 Instruction
*insn
= reinterpret_cast<Instruction
*>(insns
.get(n
));
950 if (!(mask
& JOIN_MASK_PHI
))
952 for (c
= 0; insn
->srcExists(c
); ++c
)
953 if (!coalesceValues(insn
->getDef(0), insn
->getSrc(c
), false)) {
955 ERROR("failed to coalesce phi operands\n");
961 if (!(mask
& JOIN_MASK_UNION
))
963 for (c
= 0; insn
->srcExists(c
); ++c
)
964 coalesceValues(insn
->getDef(0), insn
->getSrc(c
), true);
965 if (insn
->op
== OP_MERGE
) {
966 merges
.push_back(insn
);
967 if (insn
->srcExists(1))
968 makeCompound(insn
, false);
972 if (!(mask
& JOIN_MASK_UNION
))
974 splits
.push_back(insn
);
975 for (c
= 0; insn
->defExists(c
); ++c
)
976 coalesceValues(insn
->getSrc(0), insn
->getDef(c
), true);
977 makeCompound(insn
, true);
980 if (!(mask
& JOIN_MASK_MOV
))
983 if (!insn
->getDef(0)->uses
.empty())
984 i
= insn
->getDef(0)->uses
.front()->getInsn();
985 // if this is a contraint-move there will only be a single use
986 if (i
&& i
->op
== OP_MERGE
) // do we really still need this ?
988 i
= insn
->getSrc(0)->getUniqueInsn();
989 if (i
&& !i
->constrainedDefs()) {
990 if (coalesceValues(insn
->getDef(0), insn
->getSrc(0), false))
991 copyCompound(insn
->getSrc(0), insn
->getDef(0));
1002 if (!(mask
& JOIN_MASK_TEX
))
1004 for (c
= 0; insn
->srcExists(c
) && c
!= insn
->predSrc
; ++c
)
1005 coalesceValues(insn
->getDef(c
), insn
->getSrc(c
), true);
1015 GCRA::RIG_Node::addInterference(RIG_Node
*node
)
1017 this->degree
+= relDegree
[node
->colors
][colors
];
1018 node
->degree
+= relDegree
[colors
][node
->colors
];
1020 this->attach(node
, Graph::Edge::CROSS
);
1024 GCRA::RIG_Node::addRegPreference(RIG_Node
*node
)
1026 prefRegs
.push_back(node
);
1029 GCRA::GCRA(Function
*fn
, SpillCodeInserter
& spill
) :
1031 regs(fn
->getProgram()->getTarget()),
1034 prog
= func
->getProgram();
1036 // initialize relative degrees array - i takes away from j
1037 for (int i
= 1; i
<= 16; ++i
)
1038 for (int j
= 1; j
<= 16; ++j
)
1039 relDegree
[i
][j
] = j
* ((i
+ j
- 1) / j
);
1049 GCRA::checkList(std::list
<RIG_Node
*>& lst
)
1051 GCRA::RIG_Node
*prev
= NULL
;
1053 for (std::list
<RIG_Node
*>::iterator it
= lst
.begin();
1056 assert((*it
)->getValue()->join
== (*it
)->getValue());
1058 assert(prev
->livei
.begin() <= (*it
)->livei
.begin());
1064 GCRA::insertOrderedTail(std::list
<RIG_Node
*>& list
, RIG_Node
*node
)
1066 if (node
->livei
.isEmpty())
1068 // only the intervals of joined values don't necessarily arrive in order
1069 std::list
<RIG_Node
*>::iterator prev
, it
;
1070 for (it
= list
.end(); it
!= list
.begin(); it
= prev
) {
1073 if ((*prev
)->livei
.begin() <= node
->livei
.begin())
1076 list
.insert(it
, node
);
1080 GCRA::buildRIG(ArrayList
& insns
)
1082 std::list
<RIG_Node
*> values
, active
;
1084 for (std::deque
<ValueDef
>::iterator it
= func
->ins
.begin();
1085 it
!= func
->ins
.end(); ++it
)
1086 insertOrderedTail(values
, getNode(it
->get()->asLValue()));
1088 for (int i
= 0; i
< insns
.getSize(); ++i
) {
1089 Instruction
*insn
= reinterpret_cast<Instruction
*>(insns
.get(i
));
1090 for (int d
= 0; insn
->defExists(d
); ++d
)
1091 if (insn
->getDef(d
)->rep() == insn
->getDef(d
))
1092 insertOrderedTail(values
, getNode(insn
->getDef(d
)->asLValue()));
1096 while (!values
.empty()) {
1097 RIG_Node
*cur
= values
.front();
1099 for (std::list
<RIG_Node
*>::iterator it
= active
.begin();
1100 it
!= active
.end();) {
1101 RIG_Node
*node
= *it
;
1103 if (node
->livei
.end() <= cur
->livei
.begin()) {
1104 it
= active
.erase(it
);
1106 if (node
->f
== cur
->f
&& node
->livei
.overlaps(cur
->livei
))
1107 cur
->addInterference(node
);
1112 active
.push_back(cur
);
1117 GCRA::calculateSpillWeights()
1119 for (unsigned int i
= 0; i
< nodeCount
; ++i
) {
1120 RIG_Node
*const n
= &nodes
[i
];
1121 if (!nodes
[i
].colors
|| nodes
[i
].livei
.isEmpty())
1123 if (nodes
[i
].reg
>= 0) {
1125 regs
.occupy(n
->f
, n
->reg
, n
->colors
);
1128 LValue
*val
= nodes
[i
].getValue();
1130 if (!val
->noSpill
) {
1132 for (Value::DefIterator it
= val
->defs
.begin();
1133 it
!= val
->defs
.end();
1135 rc
+= (*it
)->get()->refCount();
1138 (float)rc
* (float)rc
/ (float)nodes
[i
].livei
.extent();
1141 if (nodes
[i
].degree
< nodes
[i
].degreeLimit
) {
1143 if (val
->reg
.size
> 4)
1145 DLLIST_ADDHEAD(&lo
[l
], &nodes
[i
]);
1147 DLLIST_ADDHEAD(&hi
, &nodes
[i
]);
1150 if (prog
->dbgFlags
& NV50_IR_DEBUG_REG_ALLOC
)
1155 GCRA::simplifyEdge(RIG_Node
*a
, RIG_Node
*b
)
1157 bool move
= b
->degree
>= b
->degreeLimit
;
1159 INFO_DBG(prog
->dbgFlags
, REG_ALLOC
,
1160 "edge: (%%%i, deg %u/%u) >-< (%%%i, deg %u/%u)\n",
1161 a
->getValue()->id
, a
->degree
, a
->degreeLimit
,
1162 b
->getValue()->id
, b
->degree
, b
->degreeLimit
);
1164 b
->degree
-= relDegree
[a
->colors
][b
->colors
];
1166 move
= move
&& b
->degree
< b
->degreeLimit
;
1167 if (move
&& !DLLIST_EMPTY(b
)) {
1168 int l
= (b
->getValue()->reg
.size
> 4) ? 1 : 0;
1170 DLLIST_ADDTAIL(&lo
[l
], b
);
1175 GCRA::simplifyNode(RIG_Node
*node
)
1177 for (Graph::EdgeIterator ei
= node
->outgoing(); !ei
.end(); ei
.next())
1178 simplifyEdge(node
, RIG_Node::get(ei
));
1180 for (Graph::EdgeIterator ei
= node
->incident(); !ei
.end(); ei
.next())
1181 simplifyEdge(node
, RIG_Node::get(ei
));
1184 stack
.push(node
->getValue()->id
);
1186 INFO_DBG(prog
->dbgFlags
, REG_ALLOC
, "SIMPLIFY: pushed %%%i%s\n",
1187 node
->getValue()->id
,
1188 (node
->degree
< node
->degreeLimit
) ? "" : "(spill)");
1195 if (!DLLIST_EMPTY(&lo
[0])) {
1197 simplifyNode(lo
[0].next
);
1198 } while (!DLLIST_EMPTY(&lo
[0]));
1200 if (!DLLIST_EMPTY(&lo
[1])) {
1201 simplifyNode(lo
[1].next
);
1203 if (!DLLIST_EMPTY(&hi
)) {
1204 RIG_Node
*best
= hi
.next
;
1205 float bestScore
= best
->weight
/ (float)best
->degree
;
1207 for (RIG_Node
*it
= best
->next
; it
!= &hi
; it
= it
->next
) {
1208 float score
= it
->weight
/ (float)it
->degree
;
1209 if (score
< bestScore
) {
1214 if (isinf(bestScore
)) {
1215 ERROR("no viable spill candidates left\n");
1226 GCRA::checkInterference(const RIG_Node
*node
, Graph::EdgeIterator
& ei
)
1228 const RIG_Node
*intf
= RIG_Node::get(ei
);
1232 const LValue
*vA
= node
->getValue();
1233 const LValue
*vB
= intf
->getValue();
1235 const uint8_t intfMask
= ((1 << intf
->colors
) - 1) << (intf
->reg
& 7);
1237 if (vA
->compound
| vB
->compound
) {
1238 // NOTE: this only works for >aligned< register tuples !
1239 for (Value::DefCIterator D
= vA
->defs
.begin(); D
!= vA
->defs
.end(); ++D
) {
1240 for (Value::DefCIterator d
= vB
->defs
.begin(); d
!= vB
->defs
.end(); ++d
) {
1241 const LValue
*vD
= (*D
)->get()->asLValue();
1242 const LValue
*vd
= (*d
)->get()->asLValue();
1244 if (!vD
->livei
.overlaps(vd
->livei
)) {
1245 INFO_DBG(prog
->dbgFlags
, REG_ALLOC
, "(%%%i) X (%%%i): no overlap\n",
1250 uint8_t mask
= vD
->compound
? vD
->compMask
: ~0;
1252 assert(vB
->compound
);
1253 mask
&= vd
->compMask
& vB
->compMask
;
1258 INFO_DBG(prog
->dbgFlags
, REG_ALLOC
,
1259 "(%%%i)%02x X (%%%i)%02x & %02x: $r%i.%02x\n",
1261 vD
->compound
? vD
->compMask
: 0xff,
1263 vd
->compound
? vd
->compMask
: intfMask
,
1264 vB
->compMask
, intf
->reg
& ~7, mask
);
1266 regs
.occupyMask(node
->f
, intf
->reg
& ~7, mask
);
1270 INFO_DBG(prog
->dbgFlags
, REG_ALLOC
,
1271 "(%%%i) X (%%%i): $r%i + %u\n",
1272 vA
->id
, vB
->id
, intf
->reg
, intf
->colors
);
1273 regs
.occupy(node
->f
, intf
->reg
, intf
->colors
);
1278 GCRA::selectRegisters()
1280 INFO_DBG(prog
->dbgFlags
, REG_ALLOC
, "\nSELECT phase\n");
1282 while (!stack
.empty()) {
1283 RIG_Node
*node
= &nodes
[stack
.top()];
1286 regs
.reset(node
->f
);
1288 INFO_DBG(prog
->dbgFlags
, REG_ALLOC
, "\nNODE[%%%i, %u colors]\n",
1289 node
->getValue()->id
, node
->colors
);
1291 for (Graph::EdgeIterator ei
= node
->outgoing(); !ei
.end(); ei
.next())
1292 checkInterference(node
, ei
);
1293 for (Graph::EdgeIterator ei
= node
->incident(); !ei
.end(); ei
.next())
1294 checkInterference(node
, ei
);
1296 if (!node
->prefRegs
.empty()) {
1297 for (std::list
<RIG_Node
*>::const_iterator it
= node
->prefRegs
.begin();
1298 it
!= node
->prefRegs
.end();
1300 if ((*it
)->reg
>= 0 &&
1301 regs
.testOccupy(node
->f
, (*it
)->reg
, node
->colors
)) {
1302 node
->reg
= (*it
)->reg
;
1309 LValue
*lval
= node
->getValue();
1310 if (prog
->dbgFlags
& NV50_IR_DEBUG_REG_ALLOC
)
1312 bool ret
= regs
.assign(node
->reg
, node
->f
, node
->colors
);
1314 INFO_DBG(prog
->dbgFlags
, REG_ALLOC
, "assigned reg %i\n", node
->reg
);
1315 lval
->compMask
= node
->getCompMask();
1317 INFO_DBG(prog
->dbgFlags
, REG_ALLOC
, "must spill: %%%i (size %u)\n",
1318 lval
->id
, lval
->reg
.size
);
1319 Symbol
*slot
= NULL
;
1320 if (lval
->reg
.file
== FILE_GPR
)
1321 slot
= spill
.assignSlot(node
->livei
, lval
->reg
.size
);
1322 mustSpill
.push_back(ValuePair(lval
, slot
));
1325 if (!mustSpill
.empty())
1327 for (unsigned int i
= 0; i
< nodeCount
; ++i
) {
1328 LValue
*lval
= nodes
[i
].getValue();
1329 if (nodes
[i
].reg
>= 0 && nodes
[i
].colors
> 0)
1331 regs
.unitsToId(nodes
[i
].f
, nodes
[i
].reg
, lval
->reg
.size
);
1337 GCRA::allocateRegisters(ArrayList
& insns
)
1341 INFO_DBG(prog
->dbgFlags
, REG_ALLOC
,
1342 "allocateRegisters to %u instructions\n", insns
.getSize());
1344 nodeCount
= func
->allLValues
.getSize();
1345 nodes
= new RIG_Node
[nodeCount
];
1348 for (unsigned int i
= 0; i
< nodeCount
; ++i
) {
1349 LValue
*lval
= reinterpret_cast<LValue
*>(func
->allLValues
.get(i
));
1351 nodes
[i
].init(regs
, lval
);
1352 RIG
.insert(&nodes
[i
]);
1356 // coalesce first, we use only 1 RIG node for a group of joined values
1357 ret
= coalesce(insns
);
1361 if (func
->getProgram()->dbgFlags
& NV50_IR_DEBUG_REG_ALLOC
)
1362 func
->printLiveIntervals();
1365 calculateSpillWeights();
1368 ret
= selectRegisters();
1370 INFO_DBG(prog
->dbgFlags
, REG_ALLOC
,
1371 "selectRegisters failed, inserting spill code ...\n");
1372 regs
.reset(FILE_GPR
, true);
1373 spill
.run(mustSpill
);
1374 if (prog
->dbgFlags
& NV50_IR_DEBUG_REG_ALLOC
)
1377 prog
->maxGPR
= std::max(prog
->maxGPR
, regs
.getMaxAssigned(FILE_GPR
));
1386 GCRA::cleanup(const bool success
)
1390 for (ArrayList::Iterator it
= func
->allLValues
.iterator();
1391 !it
.end(); it
.next()) {
1392 LValue
*lval
= reinterpret_cast<LValue
*>(it
.get());
1394 lval
->livei
.clear();
1399 if (lval
->join
== lval
)
1403 lval
->reg
.data
.id
= lval
->join
->reg
.data
.id
;
1405 for (Value::DefIterator d
= lval
->defs
.begin(); d
!= lval
->defs
.end();
1407 lval
->join
->defs
.remove(*d
);
1413 resolveSplitsAndMerges();
1414 splits
.clear(); // avoid duplicate entries on next coalesce pass
1422 SpillCodeInserter::assignSlot(const Interval
&livei
, const unsigned int size
)
1425 int32_t offsetBase
= stackSize
;
1427 std::list
<SpillSlot
>::iterator pos
= slots
.end(), it
= slots
.begin();
1429 if (offsetBase
% size
)
1430 offsetBase
+= size
- (offsetBase
% size
);
1434 for (offset
= offsetBase
; offset
< stackSize
; offset
+= size
) {
1435 const int32_t entryEnd
= offset
+ size
;
1436 while (it
!= slots
.end() && it
->offset
< offset
)
1438 if (it
== slots
.end()) // no slots left
1440 std::list
<SpillSlot
>::iterator bgn
= it
;
1442 while (it
!= slots
.end() && it
->offset
< entryEnd
) {
1444 if (it
->occup
.overlaps(livei
))
1448 if (it
== slots
.end() || it
->offset
>= entryEnd
) {
1450 for (; bgn
!= slots
.end() && bgn
->offset
< entryEnd
; ++bgn
) {
1451 bgn
->occup
.insert(livei
);
1452 if (bgn
->size() == size
)
1453 slot
.sym
= bgn
->sym
;
1459 stackSize
= offset
+ size
;
1460 slot
.offset
= offset
;
1461 slot
.sym
= new_Symbol(func
->getProgram(), FILE_MEMORY_LOCAL
);
1462 if (!func
->stackPtr
)
1463 offset
+= func
->tlsBase
;
1464 slot
.sym
->setAddress(NULL
, offset
);
1465 slot
.sym
->reg
.size
= size
;
1466 slots
.insert(pos
, slot
)->occup
.insert(livei
);
1472 SpillCodeInserter::offsetSlot(Value
*base
, const LValue
*lval
)
1474 if (!lval
->compound
|| (lval
->compMask
& 0x1))
1476 Value
*slot
= cloneShallow(func
, base
);
1478 slot
->reg
.data
.offset
+= (ffs(lval
->compMask
) - 1) * lval
->reg
.size
;
1479 slot
->reg
.size
= lval
->reg
.size
;
1485 SpillCodeInserter::spill(Instruction
*defi
, Value
*slot
, LValue
*lval
)
1487 const DataType ty
= typeOfSize(lval
->reg
.size
);
1489 slot
= offsetSlot(slot
, lval
);
1492 if (slot
->reg
.file
== FILE_MEMORY_LOCAL
) {
1493 st
= new_Instruction(func
, OP_STORE
, ty
);
1494 st
->setSrc(0, slot
);
1495 st
->setSrc(1, lval
);
1498 st
= new_Instruction(func
, OP_CVT
, ty
);
1499 st
->setDef(0, slot
);
1500 st
->setSrc(0, lval
);
1502 defi
->bb
->insertAfter(defi
, st
);
1506 SpillCodeInserter::unspill(Instruction
*usei
, LValue
*lval
, Value
*slot
)
1508 const DataType ty
= typeOfSize(lval
->reg
.size
);
1510 slot
= offsetSlot(slot
, lval
);
1511 lval
= cloneShallow(func
, lval
);
1514 if (slot
->reg
.file
== FILE_MEMORY_LOCAL
) {
1516 ld
= new_Instruction(func
, OP_LOAD
, ty
);
1518 ld
= new_Instruction(func
, OP_CVT
, ty
);
1520 ld
->setDef(0, lval
);
1521 ld
->setSrc(0, slot
);
1523 usei
->bb
->insertBefore(usei
, ld
);
1528 // For each value that is to be spilled, go through all its definitions.
1529 // A value can have multiple definitions if it has been coalesced before.
1530 // For each definition, first go through all its uses and insert an unspill
1531 // instruction before it, then replace the use with the temporary register.
1532 // Unspill can be either a load from memory or simply a move to another
1534 // For "Pseudo" instructions (like PHI, SPLIT, MERGE) we can erase the use
1535 // if we have spilled to a memory location, or simply with the new register.
1536 // No load or conversion instruction should be needed.
1538 SpillCodeInserter::run(const std::list
<ValuePair
>& lst
)
1540 for (std::list
<ValuePair
>::const_iterator it
= lst
.begin(); it
!= lst
.end();
1542 LValue
*lval
= it
->first
->asLValue();
1543 Symbol
*mem
= it
->second
? it
->second
->asSym() : NULL
;
1545 for (Value::DefIterator d
= lval
->defs
.begin(); d
!= lval
->defs
.end();
1548 static_cast<Value
*>(mem
) : new_LValue(func
, FILE_GPR
);
1550 Instruction
*last
= NULL
;
1552 LValue
*dval
= (*d
)->get()->asLValue();
1553 Instruction
*defi
= (*d
)->getInsn();
1555 // Unspill at each use *before* inserting spill instructions,
1556 // we don't want to have the spill instructions in the use list here.
1557 while (!dval
->uses
.empty()) {
1558 ValueRef
*u
= dval
->uses
.front();
1559 Instruction
*usei
= u
->getInsn();
1561 if (usei
->isPseudo()) {
1562 tmp
= (slot
->reg
.file
== FILE_MEMORY_LOCAL
) ? NULL
: slot
;
1565 if (!last
|| usei
!= last
->next
) { // TODO: sort uses
1566 tmp
= unspill(usei
, dval
, slot
);
1573 if (defi
->isPseudo()) {
1574 d
= lval
->defs
.erase(d
);
1576 if (slot
->reg
.file
== FILE_MEMORY_LOCAL
)
1577 delete_Instruction(func
->getProgram(), defi
);
1579 defi
->setDef(0, slot
);
1581 spill(defi
, slot
, dval
);
1587 // TODO: We're not trying to reuse old slots in a potential next iteration.
1588 // We have to update the slots' livei intervals to be able to do that.
1589 stackBase
= stackSize
;
1597 for (IteratorRef it
= prog
->calls
.iteratorDFS(false);
1598 !it
->end(); it
->next()) {
1599 func
= Function::get(reinterpret_cast<Graph::Node
*>(it
->get()));
1601 func
->tlsBase
= prog
->tlsSize
;
1604 prog
->tlsSize
+= func
->tlsSize
;
1610 RegAlloc::execFunc()
1612 InsertConstraintsPass insertConstr
;
1613 PhiMovesPass insertPhiMoves
;
1614 ArgumentMovesPass insertArgMoves
;
1615 BuildIntervalsPass buildIntervals
;
1616 SpillCodeInserter
insertSpills(func
);
1618 GCRA
gcra(func
, insertSpills
);
1620 unsigned int i
, retries
;
1623 if (!func
->ins
.empty()) {
1624 // Insert a nop at the entry so inputs only used by the first instruction
1625 // don't count as having an empty live range.
1626 Instruction
*nop
= new_Instruction(func
, OP_NOP
, TYPE_NONE
);
1627 BasicBlock::get(func
->cfg
.getRoot())->insertHead(nop
);
1630 ret
= insertConstr
.exec(func
);
1634 ret
= insertPhiMoves
.run(func
);
1638 ret
= insertArgMoves
.run(func
);
1642 // TODO: need to fix up spill slot usage ranges to support > 1 retry
1643 for (retries
= 0; retries
< 3; ++retries
) {
1644 if (retries
&& (prog
->dbgFlags
& NV50_IR_DEBUG_REG_ALLOC
))
1645 INFO("Retry: %i\n", retries
);
1646 if (prog
->dbgFlags
& NV50_IR_DEBUG_REG_ALLOC
)
1649 // spilling to registers may add live ranges, need to rebuild everything
1651 for (sequence
= func
->cfg
.nextSequence(), i
= 0;
1652 ret
&& i
<= func
->loopNestingBound
;
1653 sequence
= func
->cfg
.nextSequence(), ++i
)
1654 ret
= buildLiveSets(BasicBlock::get(func
->cfg
.getRoot()));
1657 func
->orderInstructions(this->insns
);
1659 ret
= buildIntervals
.run(func
);
1662 ret
= gcra
.allocateRegisters(insns
);
1666 INFO_DBG(prog
->dbgFlags
, REG_ALLOC
, "RegAlloc done: %i\n", ret
);
1668 func
->tlsSize
= insertSpills
.getStackSize();
1673 // TODO: check if modifying Instruction::join here breaks anything
1675 GCRA::resolveSplitsAndMerges()
1677 for (std::list
<Instruction
*>::iterator it
= splits
.begin();
1680 Instruction
*split
= *it
;
1681 unsigned int reg
= regs
.idToBytes(split
->getSrc(0));
1682 for (int d
= 0; split
->defExists(d
); ++d
) {
1683 Value
*v
= split
->getDef(d
);
1684 v
->reg
.data
.id
= regs
.bytesToId(v
, reg
);
1691 for (std::list
<Instruction
*>::iterator it
= merges
.begin();
1694 Instruction
*merge
= *it
;
1695 unsigned int reg
= regs
.idToBytes(merge
->getDef(0));
1696 for (int s
= 0; merge
->srcExists(s
); ++s
) {
1697 Value
*v
= merge
->getSrc(s
);
1698 v
->reg
.data
.id
= regs
.bytesToId(v
, reg
);
1706 bool Program::registerAllocation()
1713 RegAlloc::InsertConstraintsPass::exec(Function
*ir
)
1717 bool ret
= run(ir
, true, true);
1719 ret
= insertConstraintMoves();
1723 // TODO: make part of texture insn
1725 RegAlloc::InsertConstraintsPass::textureMask(TexInstruction
*tex
)
1731 for (d
= 0, k
= 0, c
= 0; c
< 4; ++c
) {
1732 if (!(tex
->tex
.mask
& (1 << c
)))
1734 if (tex
->getDef(k
)->refCount()) {
1736 def
[d
++] = tex
->getDef(k
);
1740 tex
->tex
.mask
= mask
;
1742 for (c
= 0; c
< d
; ++c
)
1743 tex
->setDef(c
, def
[c
]);
1745 tex
->setDef(c
, NULL
);
1749 RegAlloc::InsertConstraintsPass::detectConflict(Instruction
*cst
, int s
)
1751 Value
*v
= cst
->getSrc(s
);
1753 // current register allocation can't handle it if a value participates in
1754 // multiple constraints
1755 for (Value::UseIterator it
= v
->uses
.begin(); it
!= v
->uses
.end(); ++it
) {
1756 if (cst
!= (*it
)->getInsn())
1760 // can start at s + 1 because detectConflict is called on all sources
1761 for (int c
= s
+ 1; cst
->srcExists(c
); ++c
)
1762 if (v
== cst
->getSrc(c
))
1765 Instruction
*defi
= v
->getInsn();
1767 return (!defi
|| defi
->constrainedDefs());
1771 RegAlloc::InsertConstraintsPass::addConstraint(Instruction
*i
, int s
, int n
)
1776 // first, look for an existing identical constraint op
1777 for (std::list
<Instruction
*>::iterator it
= constrList
.begin();
1778 it
!= constrList
.end();
1781 if (!i
->bb
->dominatedBy(cst
->bb
))
1783 for (d
= 0; d
< n
; ++d
)
1784 if (cst
->getSrc(d
) != i
->getSrc(d
+ s
))
1787 for (d
= 0; d
< n
; ++d
, ++s
)
1788 i
->setSrc(s
, cst
->getDef(d
));
1792 cst
= new_Instruction(func
, OP_CONSTRAINT
, i
->dType
);
1794 for (d
= 0; d
< n
; ++s
, ++d
) {
1795 cst
->setDef(d
, new_LValue(func
, FILE_GPR
));
1796 cst
->setSrc(d
, i
->getSrc(s
));
1797 i
->setSrc(s
, cst
->getDef(d
));
1799 i
->bb
->insertBefore(i
, cst
);
1801 constrList
.push_back(cst
);
1804 // Add a dummy use of the pointer source of >= 8 byte loads after the load
1805 // to prevent it from being assigned a register which overlapping the load's
1806 // destination, which would produce random corruptions.
1808 RegAlloc::InsertConstraintsPass::addHazard(Instruction
*i
, const ValueRef
*src
)
1810 Instruction
*hzd
= new_Instruction(func
, OP_NOP
, TYPE_NONE
);
1811 hzd
->setSrc(0, src
->get());
1812 i
->bb
->insertAfter(i
, hzd
);
1816 // b32 { %r0 %r1 %r2 %r3 } -> b128 %r0q
1818 RegAlloc::InsertConstraintsPass::condenseDefs(Instruction
*insn
)
1822 for (n
= 0; insn
->defExists(n
) && insn
->def(n
).getFile() == FILE_GPR
; ++n
)
1823 size
+= insn
->getDef(n
)->reg
.size
;
1826 LValue
*lval
= new_LValue(func
, FILE_GPR
);
1827 lval
->reg
.size
= size
;
1829 Instruction
*split
= new_Instruction(func
, OP_SPLIT
, typeOfSize(size
));
1830 split
->setSrc(0, lval
);
1831 for (int d
= 0; d
< n
; ++d
) {
1832 split
->setDef(d
, insn
->getDef(d
));
1833 insn
->setDef(d
, NULL
);
1835 insn
->setDef(0, lval
);
1837 for (int k
= 1, d
= n
; insn
->defExists(d
); ++d
, ++k
) {
1838 insn
->setDef(k
, insn
->getDef(d
));
1839 insn
->setDef(d
, NULL
);
1841 // carry over predicate if any (mainly for OP_UNION uses)
1842 split
->setPredicate(insn
->cc
, insn
->getPredicate());
1844 insn
->bb
->insertAfter(insn
, split
);
1845 constrList
.push_back(split
);
1848 RegAlloc::InsertConstraintsPass::condenseSrcs(Instruction
*insn
,
1849 const int a
, const int b
)
1854 for (int s
= a
; s
<= b
; ++s
)
1855 size
+= insn
->getSrc(s
)->reg
.size
;
1858 LValue
*lval
= new_LValue(func
, FILE_GPR
);
1859 lval
->reg
.size
= size
;
1862 insn
->takeExtraSources(0, save
);
1864 Instruction
*merge
= new_Instruction(func
, OP_MERGE
, typeOfSize(size
));
1865 merge
->setDef(0, lval
);
1866 for (int s
= a
, i
= 0; s
<= b
; ++s
, ++i
) {
1867 merge
->setSrc(i
, insn
->getSrc(s
));
1868 insn
->setSrc(s
, NULL
);
1870 insn
->setSrc(a
, lval
);
1872 for (int k
= a
+ 1, s
= b
+ 1; insn
->srcExists(s
); ++s
, ++k
) {
1873 insn
->setSrc(k
, insn
->getSrc(s
));
1874 insn
->setSrc(s
, NULL
);
1876 insn
->bb
->insertBefore(insn
, merge
);
1878 insn
->putExtraSources(0, save
);
1880 constrList
.push_back(merge
);
1884 RegAlloc::InsertConstraintsPass::texConstraintNVE0(TexInstruction
*tex
)
1886 if (isTextureOp(tex
->op
))
1890 if (tex
->op
== OP_SUSTB
|| tex
->op
== OP_SUSTP
) {
1891 condenseSrcs(tex
, 3, (3 + typeSizeof(tex
->dType
) / 4) - 1);
1893 if (isTextureOp(tex
->op
)) {
1894 int n
= tex
->srcCount(0xff, true);
1896 condenseSrcs(tex
, 0, 3);
1897 if (n
> 5) // NOTE: first call modified positions already
1898 condenseSrcs(tex
, 4 - (4 - 1), n
- 1 - (4 - 1));
1901 condenseSrcs(tex
, 0, n
- 1);
1907 RegAlloc::InsertConstraintsPass::texConstraintNVC0(TexInstruction
*tex
)
1913 if (tex
->op
== OP_TXQ
) {
1914 s
= tex
->srcCount(0xff);
1917 s
= tex
->tex
.target
.getArgCount() - tex
->tex
.target
.isMS();
1918 if (!tex
->tex
.target
.isArray() &&
1919 (tex
->tex
.rIndirectSrc
>= 0 || tex
->tex
.sIndirectSrc
>= 0))
1921 if (tex
->op
== OP_TXD
&& tex
->tex
.useOffsets
)
1923 n
= tex
->srcCount(0xff) - s
;
1928 condenseSrcs(tex
, 0, s
- 1);
1929 if (n
> 1) // NOTE: first call modified positions already
1930 condenseSrcs(tex
, 1, n
);
1936 RegAlloc::InsertConstraintsPass::texConstraintNV50(TexInstruction
*tex
)
1938 Value
*pred
= tex
->getPredicate();
1940 tex
->setPredicate(tex
->cc
, NULL
);
1944 assert(tex
->defExists(0) && tex
->srcExists(0));
1945 // make src and def count match
1947 for (c
= 0; tex
->srcExists(c
) || tex
->defExists(c
); ++c
) {
1948 if (!tex
->srcExists(c
))
1949 tex
->setSrc(c
, new_LValue(func
, tex
->getSrc(0)->asLValue()));
1950 if (!tex
->defExists(c
))
1951 tex
->setDef(c
, new_LValue(func
, tex
->getDef(0)->asLValue()));
1954 tex
->setPredicate(tex
->cc
, pred
);
1956 condenseSrcs(tex
, 0, c
- 1);
1959 // Insert constraint markers for instructions whose multiple sources must be
1960 // located in consecutive registers.
1962 RegAlloc::InsertConstraintsPass::visit(BasicBlock
*bb
)
1964 TexInstruction
*tex
;
1968 targ
= bb
->getProgram()->getTarget();
1970 for (Instruction
*i
= bb
->getEntry(); i
; i
= next
) {
1973 if ((tex
= i
->asTex())) {
1974 switch (targ
->getChipset() & ~0xf) {
1979 texConstraintNV50(tex
);
1983 texConstraintNVC0(tex
);
1988 texConstraintNVE0(tex
);
1994 if (i
->op
== OP_EXPORT
|| i
->op
== OP_STORE
) {
1995 for (size
= typeSizeof(i
->dType
), s
= 1; size
> 0; ++s
) {
1996 assert(i
->srcExists(s
));
1997 size
-= i
->getSrc(s
)->reg
.size
;
1999 condenseSrcs(i
, 1, s
- 1);
2001 if (i
->op
== OP_LOAD
|| i
->op
== OP_VFETCH
) {
2003 if (i
->src(0).isIndirect(0) && typeSizeof(i
->dType
) >= 8)
2004 addHazard(i
, i
->src(0).getIndirect(0));
2006 if (i
->op
== OP_UNION
||
2007 i
->op
== OP_MERGE
||
2008 i
->op
== OP_SPLIT
) {
2009 constrList
.push_back(i
);
2015 // Insert extra moves so that, if multiple register constraints on a value are
2016 // in conflict, these conflicts can be resolved.
2018 RegAlloc::InsertConstraintsPass::insertConstraintMoves()
2020 for (std::list
<Instruction
*>::iterator it
= constrList
.begin();
2021 it
!= constrList
.end();
2023 Instruction
*cst
= *it
;
2026 if (cst
->op
== OP_SPLIT
&& 0) {
2027 // spilling splits is annoying, just make sure they're separate
2028 for (int d
= 0; cst
->defExists(d
); ++d
) {
2029 if (!cst
->getDef(d
)->refCount())
2031 LValue
*lval
= new_LValue(func
, cst
->def(d
).getFile());
2032 const uint8_t size
= cst
->def(d
).getSize();
2033 lval
->reg
.size
= size
;
2035 mov
= new_Instruction(func
, OP_MOV
, typeOfSize(size
));
2036 mov
->setSrc(0, lval
);
2037 mov
->setDef(0, cst
->getDef(d
));
2038 cst
->setDef(d
, mov
->getSrc(0));
2039 cst
->bb
->insertAfter(cst
, mov
);
2041 cst
->getSrc(0)->asLValue()->noSpill
= 1;
2042 mov
->getSrc(0)->asLValue()->noSpill
= 1;
2045 if (cst
->op
== OP_MERGE
|| cst
->op
== OP_UNION
) {
2046 for (int s
= 0; cst
->srcExists(s
); ++s
) {
2047 const uint8_t size
= cst
->src(s
).getSize();
2049 if (!cst
->getSrc(s
)->defs
.size()) {
2050 mov
= new_Instruction(func
, OP_NOP
, typeOfSize(size
));
2051 mov
->setDef(0, cst
->getSrc(s
));
2052 cst
->bb
->insertBefore(cst
, mov
);
2055 assert(cst
->getSrc(s
)->defs
.size() == 1); // still SSA
2057 Instruction
*defi
= cst
->getSrc(s
)->defs
.front()->getInsn();
2058 // catch some cases where don't really need MOVs
2059 if (cst
->getSrc(s
)->refCount() == 1 && !defi
->constrainedDefs())
2062 LValue
*lval
= new_LValue(func
, cst
->src(s
).getFile());
2063 lval
->reg
.size
= size
;
2065 mov
= new_Instruction(func
, OP_MOV
, typeOfSize(size
));
2066 mov
->setDef(0, lval
);
2067 mov
->setSrc(0, cst
->getSrc(s
));
2068 cst
->setSrc(s
, mov
->getDef(0));
2069 cst
->bb
->insertBefore(cst
, mov
);
2071 cst
->getDef(0)->asLValue()->noSpill
= 1; // doesn't help
2073 if (cst
->op
== OP_UNION
)
2074 mov
->setPredicate(defi
->cc
, defi
->getPredicate());
2082 } // namespace nv50_ir