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
*);
259 void texConstraintGM107(TexInstruction
*);
261 std::list
<Instruction
*> constrList
;
266 bool buildLiveSets(BasicBlock
*);
272 // instructions in control flow / chronological order
275 int sequence
; // for manual passes through CFG
278 typedef std::pair
<Value
*, Value
*> ValuePair
;
280 class SpillCodeInserter
283 SpillCodeInserter(Function
*fn
) : func(fn
), stackSize(0), stackBase(0) { }
285 bool run(const std::list
<ValuePair
>&);
287 Symbol
*assignSlot(const Interval
&, const unsigned int size
);
288 Value
*offsetSlot(Value
*, const LValue
*);
289 inline int32_t getStackSize() const { return stackSize
; }
297 std::list
<Value
*> residents
; // needed to recalculate occup
300 inline uint8_t size() const { return sym
->reg
.size
; }
302 std::list
<SpillSlot
> slots
;
306 LValue
*unspill(Instruction
*usei
, LValue
*, Value
*slot
);
307 void spill(Instruction
*defi
, Value
*slot
, LValue
*);
311 RegAlloc::BuildIntervalsPass::addLiveRange(Value
*val
,
312 const BasicBlock
*bb
,
315 Instruction
*insn
= val
->getUniqueInsn();
318 insn
= bb
->getFirst();
320 assert(bb
->getFirst()->serial
<= bb
->getExit()->serial
);
321 assert(bb
->getExit()->serial
+ 1 >= end
);
323 int begin
= insn
->serial
;
324 if (begin
< bb
->getEntry()->serial
|| begin
> bb
->getExit()->serial
)
325 begin
= bb
->getEntry()->serial
;
327 INFO_DBG(prog
->dbgFlags
, REG_ALLOC
, "%%%i <- live range [%i(%i), %i)\n",
328 val
->id
, begin
, insn
->serial
, end
);
330 if (begin
!= end
) // empty ranges are only added as hazards for fixed regs
331 val
->livei
.extend(begin
, end
);
335 RegAlloc::PhiMovesPass::needNewElseBlock(BasicBlock
*b
, BasicBlock
*p
)
337 if (b
->cfg
.incidentCount() <= 1)
341 for (Graph::EdgeIterator ei
= p
->cfg
.outgoing(); !ei
.end(); ei
.next())
342 if (ei
.getType() == Graph::Edge::TREE
||
343 ei
.getType() == Graph::Edge::FORWARD
)
348 // For each operand of each PHI in b, generate a new value by inserting a MOV
349 // at the end of the block it is coming from and replace the operand with its
350 // result. This eliminates liveness conflicts and enables us to let values be
351 // copied to the right register if such a conflict exists nonetheless.
353 // These MOVs are also crucial in making sure the live intervals of phi srces
354 // are extended until the end of the loop, since they are not included in the
357 RegAlloc::PhiMovesPass::visit(BasicBlock
*bb
)
359 Instruction
*phi
, *mov
;
362 std::stack
<BasicBlock
*> stack
;
364 for (Graph::EdgeIterator ei
= bb
->cfg
.incident(); !ei
.end(); ei
.next()) {
365 pb
= BasicBlock::get(ei
.getNode());
367 if (needNewElseBlock(bb
, pb
))
370 while (!stack
.empty()) {
372 pn
= new BasicBlock(func
);
375 pb
->cfg
.detach(&bb
->cfg
);
376 pb
->cfg
.attach(&pn
->cfg
, Graph::Edge::TREE
);
377 pn
->cfg
.attach(&bb
->cfg
, Graph::Edge::FORWARD
);
379 assert(pb
->getExit()->op
!= OP_CALL
);
380 if (pb
->getExit()->asFlow()->target
.bb
== bb
)
381 pb
->getExit()->asFlow()->target
.bb
= pn
;
384 // insert MOVs (phi->src(j) should stem from j-th in-BB)
386 for (Graph::EdgeIterator ei
= bb
->cfg
.incident(); !ei
.end(); ei
.next()) {
387 pb
= BasicBlock::get(ei
.getNode());
388 if (!pb
->isTerminated())
389 pb
->insertTail(new_FlowInstruction(func
, OP_BRA
, bb
));
391 for (phi
= bb
->getPhi(); phi
&& phi
->op
== OP_PHI
; phi
= phi
->next
) {
392 mov
= new_Instruction(func
, OP_MOV
, TYPE_U32
);
394 mov
->setSrc(0, phi
->getSrc(j
));
395 mov
->setDef(0, new_LValue(func
, phi
->getDef(0)->asLValue()));
396 phi
->setSrc(j
, mov
->getDef(0));
398 pb
->insertBefore(pb
->getExit(), mov
);
407 RegAlloc::ArgumentMovesPass::visit(BasicBlock
*bb
)
409 // Bind function call inputs/outputs to the same physical register
410 // the callee uses, inserting moves as appropriate for the case a
412 for (Instruction
*i
= bb
->getEntry(); i
; i
= i
->next
) {
413 FlowInstruction
*cal
= i
->asFlow();
414 // TODO: Handle indirect calls.
415 // Right now they should only be generated for builtins.
416 if (!cal
|| cal
->op
!= OP_CALL
|| cal
->builtin
|| cal
->indirect
)
418 RegisterSet
clobberSet(prog
->getTarget());
420 // Bind input values.
421 for (int s
= cal
->indirect
? 1 : 0; cal
->srcExists(s
); ++s
) {
422 const int t
= cal
->indirect
? (s
- 1) : s
;
423 LValue
*tmp
= new_LValue(func
, cal
->getSrc(s
)->asLValue());
424 tmp
->reg
.data
.id
= cal
->target
.fn
->ins
[t
].rep()->reg
.data
.id
;
427 new_Instruction(func
, OP_MOV
, typeOfSize(tmp
->reg
.size
));
429 mov
->setSrc(0, cal
->getSrc(s
));
432 bb
->insertBefore(cal
, mov
);
435 // Bind output values.
436 for (int d
= 0; cal
->defExists(d
); ++d
) {
437 LValue
*tmp
= new_LValue(func
, cal
->getDef(d
)->asLValue());
438 tmp
->reg
.data
.id
= cal
->target
.fn
->outs
[d
].rep()->reg
.data
.id
;
441 new_Instruction(func
, OP_MOV
, typeOfSize(tmp
->reg
.size
));
443 mov
->setDef(0, cal
->getDef(d
));
446 bb
->insertAfter(cal
, mov
);
447 clobberSet
.occupy(tmp
);
450 // Bind clobbered values.
451 for (std::deque
<Value
*>::iterator it
= cal
->target
.fn
->clobbers
.begin();
452 it
!= cal
->target
.fn
->clobbers
.end();
454 if (clobberSet
.testOccupy(*it
)) {
455 Value
*tmp
= new_LValue(func
, (*it
)->asLValue());
456 tmp
->reg
.data
.id
= (*it
)->reg
.data
.id
;
457 cal
->setDef(cal
->defCount(), tmp
);
462 // Update the clobber set of the function.
463 if (BasicBlock::get(func
->cfgExit
) == bb
) {
464 func
->buildDefSets();
465 for (unsigned int i
= 0; i
< bb
->defSet
.getSize(); ++i
)
466 if (bb
->defSet
.test(i
))
467 func
->clobbers
.push_back(func
->getLValue(i
));
473 // Build the set of live-in variables of bb.
475 RegAlloc::buildLiveSets(BasicBlock
*bb
)
477 Function
*f
= bb
->getFunction();
482 INFO_DBG(prog
->dbgFlags
, REG_ALLOC
, "buildLiveSets(BB:%i)\n", bb
->getId());
484 bb
->liveSet
.allocate(func
->allLValues
.getSize(), false);
487 for (Graph::EdgeIterator ei
= bb
->cfg
.outgoing(); !ei
.end(); ei
.next()) {
488 bn
= BasicBlock::get(ei
.getNode());
491 if (bn
->cfg
.visit(sequence
))
492 if (!buildLiveSets(bn
))
494 if (n
++ || bb
->liveSet
.marker
)
495 bb
->liveSet
|= bn
->liveSet
;
497 bb
->liveSet
= bn
->liveSet
;
499 if (!n
&& !bb
->liveSet
.marker
)
501 bb
->liveSet
.marker
= true;
503 if (prog
->dbgFlags
& NV50_IR_DEBUG_REG_ALLOC
) {
504 INFO("BB:%i live set of out blocks:\n", bb
->getId());
508 // if (!bb->getEntry())
511 if (bb
== BasicBlock::get(f
->cfgExit
)) {
512 for (std::deque
<ValueRef
>::iterator it
= f
->outs
.begin();
513 it
!= f
->outs
.end(); ++it
) {
514 assert(it
->get()->asLValue());
515 bb
->liveSet
.set(it
->get()->id
);
519 for (i
= bb
->getExit(); i
&& i
!= bb
->getEntry()->prev
; i
= i
->prev
) {
520 for (d
= 0; i
->defExists(d
); ++d
)
521 bb
->liveSet
.clr(i
->getDef(d
)->id
);
522 for (s
= 0; i
->srcExists(s
); ++s
)
523 if (i
->getSrc(s
)->asLValue())
524 bb
->liveSet
.set(i
->getSrc(s
)->id
);
526 for (i
= bb
->getPhi(); i
&& i
->op
== OP_PHI
; i
= i
->next
)
527 bb
->liveSet
.clr(i
->getDef(0)->id
);
529 if (prog
->dbgFlags
& NV50_IR_DEBUG_REG_ALLOC
) {
530 INFO("BB:%i live set after propagation:\n", bb
->getId());
538 RegAlloc::BuildIntervalsPass::collectLiveValues(BasicBlock
*bb
)
540 BasicBlock
*bbA
= NULL
, *bbB
= NULL
;
542 if (bb
->cfg
.outgoingCount()) {
543 // trickery to save a loop of OR'ing liveSets
544 // aliasing works fine with BitSet::setOr
545 for (Graph::EdgeIterator ei
= bb
->cfg
.outgoing(); !ei
.end(); ei
.next()) {
546 if (ei
.getType() == Graph::Edge::DUMMY
)
549 bb
->liveSet
.setOr(&bbA
->liveSet
, &bbB
->liveSet
);
554 bbB
= BasicBlock::get(ei
.getNode());
556 bb
->liveSet
.setOr(&bbB
->liveSet
, bbA
? &bbA
->liveSet
: NULL
);
558 if (bb
->cfg
.incidentCount()) {
564 RegAlloc::BuildIntervalsPass::visit(BasicBlock
*bb
)
566 collectLiveValues(bb
);
568 INFO_DBG(prog
->dbgFlags
, REG_ALLOC
, "BuildIntervals(BB:%i)\n", bb
->getId());
570 // go through out blocks and delete phi sources that do not originate from
571 // the current block from the live set
572 for (Graph::EdgeIterator ei
= bb
->cfg
.outgoing(); !ei
.end(); ei
.next()) {
573 BasicBlock
*out
= BasicBlock::get(ei
.getNode());
575 for (Instruction
*i
= out
->getPhi(); i
&& i
->op
== OP_PHI
; i
= i
->next
) {
576 bb
->liveSet
.clr(i
->getDef(0)->id
);
578 for (int s
= 0; i
->srcExists(s
); ++s
) {
579 assert(i
->src(s
).getInsn());
580 if (i
->getSrc(s
)->getUniqueInsn()->bb
== bb
) // XXX: reachableBy ?
581 bb
->liveSet
.set(i
->getSrc(s
)->id
);
583 bb
->liveSet
.clr(i
->getSrc(s
)->id
);
588 // remaining live-outs are live until end
590 for (unsigned int j
= 0; j
< bb
->liveSet
.getSize(); ++j
)
591 if (bb
->liveSet
.test(j
))
592 addLiveRange(func
->getLValue(j
), bb
, bb
->getExit()->serial
+ 1);
595 for (Instruction
*i
= bb
->getExit(); i
&& i
->op
!= OP_PHI
; i
= i
->prev
) {
596 for (int d
= 0; i
->defExists(d
); ++d
) {
597 bb
->liveSet
.clr(i
->getDef(d
)->id
);
598 if (i
->getDef(d
)->reg
.data
.id
>= 0) // add hazard for fixed regs
599 i
->getDef(d
)->livei
.extend(i
->serial
, i
->serial
);
602 for (int s
= 0; i
->srcExists(s
); ++s
) {
603 if (!i
->getSrc(s
)->asLValue())
605 if (!bb
->liveSet
.test(i
->getSrc(s
)->id
)) {
606 bb
->liveSet
.set(i
->getSrc(s
)->id
);
607 addLiveRange(i
->getSrc(s
), bb
, i
->serial
);
612 if (bb
== BasicBlock::get(func
->cfg
.getRoot())) {
613 for (std::deque
<ValueDef
>::iterator it
= func
->ins
.begin();
614 it
!= func
->ins
.end(); ++it
) {
615 if (it
->get()->reg
.data
.id
>= 0) // add hazard for fixed regs
616 it
->get()->livei
.extend(0, 1);
624 #define JOIN_MASK_PHI (1 << 0)
625 #define JOIN_MASK_UNION (1 << 1)
626 #define JOIN_MASK_MOV (1 << 2)
627 #define JOIN_MASK_TEX (1 << 3)
632 GCRA(Function
*, SpillCodeInserter
&);
635 bool allocateRegisters(ArrayList
& insns
);
637 void printNodeInfo() const;
640 class RIG_Node
: public Graph::Node
645 void init(const RegisterSet
&, LValue
*);
647 void addInterference(RIG_Node
*);
648 void addRegPreference(RIG_Node
*);
650 inline LValue
*getValue() const
652 return reinterpret_cast<LValue
*>(data
);
654 inline void setValue(LValue
*lval
) { data
= lval
; }
656 inline uint8_t getCompMask() const
658 return ((1 << colors
) - 1) << (reg
& 7);
661 static inline RIG_Node
*get(const Graph::EdgeIterator
& ei
)
663 return static_cast<RIG_Node
*>(ei
.getNode());
668 uint16_t degreeLimit
; // if deg < degLimit, node is trivially colourable
676 // list pointers for simplify() phase
680 // union of the live intervals of all coalesced values (we want to retain
681 // the separate intervals for testing interference of compound values)
684 std::list
<RIG_Node
*> prefRegs
;
688 inline RIG_Node
*getNode(const LValue
*v
) const { return &nodes
[v
->id
]; }
690 void buildRIG(ArrayList
&);
691 bool coalesce(ArrayList
&);
692 bool doCoalesce(ArrayList
&, unsigned int mask
);
693 void calculateSpillWeights();
695 bool selectRegisters();
696 void cleanup(const bool success
);
698 void simplifyEdge(RIG_Node
*, RIG_Node
*);
699 void simplifyNode(RIG_Node
*);
701 bool coalesceValues(Value
*, Value
*, bool force
);
702 void resolveSplitsAndMerges();
703 void makeCompound(Instruction
*, bool isSplit
);
705 inline void checkInterference(const RIG_Node
*, Graph::EdgeIterator
&);
707 inline void insertOrderedTail(std::list
<RIG_Node
*>&, RIG_Node
*);
708 void checkList(std::list
<RIG_Node
*>&);
711 std::stack
<uint32_t> stack
;
713 // list headers for simplify() phase
719 unsigned int nodeCount
;
724 static uint8_t relDegree
[17][17];
728 // need to fixup register id for participants of OP_MERGE/SPLIT
729 std::list
<Instruction
*> merges
;
730 std::list
<Instruction
*> splits
;
732 SpillCodeInserter
& spill
;
733 std::list
<ValuePair
> mustSpill
;
736 uint8_t GCRA::relDegree
[17][17];
738 GCRA::RIG_Node::RIG_Node() : Node(NULL
), next(this), prev(this)
744 GCRA::printNodeInfo() const
746 for (unsigned int i
= 0; i
< nodeCount
; ++i
) {
747 if (!nodes
[i
].colors
)
749 INFO("RIG_Node[%%%i]($[%u]%i): %u colors, weight %f, deg %u/%u\n X",
751 nodes
[i
].f
,nodes
[i
].reg
,nodes
[i
].colors
,
753 nodes
[i
].degree
, nodes
[i
].degreeLimit
);
755 for (Graph::EdgeIterator ei
= nodes
[i
].outgoing(); !ei
.end(); ei
.next())
756 INFO(" %%%i", RIG_Node::get(ei
)->getValue()->id
);
757 for (Graph::EdgeIterator ei
= nodes
[i
].incident(); !ei
.end(); ei
.next())
758 INFO(" %%%i", RIG_Node::get(ei
)->getValue()->id
);
764 GCRA::RIG_Node::init(const RegisterSet
& regs
, LValue
*lval
)
767 if (lval
->reg
.data
.id
>= 0)
768 lval
->noSpill
= lval
->fixedReg
= 1;
770 colors
= regs
.units(lval
->reg
.file
, lval
->reg
.size
);
773 if (lval
->reg
.data
.id
>= 0)
774 reg
= regs
.idToUnits(lval
);
776 weight
= std::numeric_limits
<float>::infinity();
778 degreeLimit
= regs
.getFileSize(f
, lval
->reg
.size
);
779 degreeLimit
-= relDegree
[1][colors
] - 1;
781 livei
.insert(lval
->livei
);
785 GCRA::coalesceValues(Value
*dst
, Value
*src
, bool force
)
787 LValue
*rep
= dst
->join
->asLValue();
788 LValue
*val
= src
->join
->asLValue();
790 if (!force
&& val
->reg
.data
.id
>= 0) {
791 rep
= src
->join
->asLValue();
792 val
= dst
->join
->asLValue();
794 RIG_Node
*nRep
= &nodes
[rep
->id
];
795 RIG_Node
*nVal
= &nodes
[val
->id
];
797 if (src
->reg
.file
!= dst
->reg
.file
) {
800 WARN("forced coalescing of values in different files !\n");
802 if (!force
&& dst
->reg
.size
!= src
->reg
.size
)
805 if ((rep
->reg
.data
.id
>= 0) && (rep
->reg
.data
.id
!= val
->reg
.data
.id
)) {
807 if (val
->reg
.data
.id
>= 0)
808 WARN("forced coalescing of values in different fixed regs !\n");
810 if (val
->reg
.data
.id
>= 0)
812 // make sure that there is no overlap with the fixed register of rep
813 for (ArrayList::Iterator it
= func
->allLValues
.iterator();
814 !it
.end(); it
.next()) {
815 Value
*reg
= reinterpret_cast<Value
*>(it
.get())->asLValue();
817 if (reg
->interfers(rep
) && reg
->livei
.overlaps(nVal
->livei
))
823 if (!force
&& nRep
->livei
.overlaps(nVal
->livei
))
826 INFO_DBG(prog
->dbgFlags
, REG_ALLOC
, "joining %%%i($%i) <- %%%i\n",
827 rep
->id
, rep
->reg
.data
.id
, val
->id
);
829 // set join pointer of all values joined with val
830 for (Value::DefIterator def
= val
->defs
.begin(); def
!= val
->defs
.end();
832 (*def
)->get()->join
= rep
;
833 assert(rep
->join
== rep
&& val
->join
== rep
);
835 // add val's definitions to rep and extend the live interval of its RIG node
836 rep
->defs
.insert(rep
->defs
.end(), val
->defs
.begin(), val
->defs
.end());
837 nRep
->livei
.unify(nVal
->livei
);
842 GCRA::coalesce(ArrayList
& insns
)
844 bool ret
= doCoalesce(insns
, JOIN_MASK_PHI
);
847 switch (func
->getProgram()->getTarget()->getChipset() & ~0xf) {
852 ret
= doCoalesce(insns
, JOIN_MASK_UNION
| JOIN_MASK_TEX
);
860 ret
= doCoalesce(insns
, JOIN_MASK_UNION
);
867 return doCoalesce(insns
, JOIN_MASK_MOV
);
870 static inline uint8_t makeCompMask(int compSize
, int base
, int size
)
872 uint8_t m
= ((1 << size
) - 1) << base
;
884 assert(compSize
<= 8);
889 // Used when coalescing moves. The non-compound value will become one, e.g.:
890 // mov b32 $r0 $r2 / merge b64 $r0d { $r0 $r1 }
891 // split b64 { $r0 $r1 } $r0d / mov b64 $r0d f64 $r2d
892 static inline void copyCompound(Value
*dst
, Value
*src
)
894 LValue
*ldst
= dst
->asLValue();
895 LValue
*lsrc
= src
->asLValue();
897 if (ldst
->compound
&& !lsrc
->compound
) {
903 ldst
->compound
= lsrc
->compound
;
904 ldst
->compMask
= lsrc
->compMask
;
908 GCRA::makeCompound(Instruction
*insn
, bool split
)
910 LValue
*rep
= (split
? insn
->getSrc(0) : insn
->getDef(0))->asLValue();
912 if (prog
->dbgFlags
& NV50_IR_DEBUG_REG_ALLOC
) {
913 INFO("makeCompound(split = %i): ", split
);
917 const unsigned int size
= getNode(rep
)->colors
;
918 unsigned int base
= 0;
921 rep
->compMask
= 0xff;
924 for (int c
= 0; split
? insn
->defExists(c
) : insn
->srcExists(c
); ++c
) {
925 LValue
*val
= (split
? insn
->getDef(c
) : insn
->getSrc(c
))->asLValue();
929 val
->compMask
= 0xff;
930 val
->compMask
&= makeCompMask(size
, base
, getNode(val
)->colors
);
931 assert(val
->compMask
);
933 INFO_DBG(prog
->dbgFlags
, REG_ALLOC
, "compound: %%%i:%02x <- %%%i:%02x\n",
934 rep
->id
, rep
->compMask
, val
->id
, val
->compMask
);
936 base
+= getNode(val
)->colors
;
938 assert(base
== size
);
942 GCRA::doCoalesce(ArrayList
& insns
, unsigned int mask
)
946 for (n
= 0; n
< insns
.getSize(); ++n
) {
948 Instruction
*insn
= reinterpret_cast<Instruction
*>(insns
.get(n
));
952 if (!(mask
& JOIN_MASK_PHI
))
954 for (c
= 0; insn
->srcExists(c
); ++c
)
955 if (!coalesceValues(insn
->getDef(0), insn
->getSrc(c
), false)) {
957 ERROR("failed to coalesce phi operands\n");
963 if (!(mask
& JOIN_MASK_UNION
))
965 for (c
= 0; insn
->srcExists(c
); ++c
)
966 coalesceValues(insn
->getDef(0), insn
->getSrc(c
), true);
967 if (insn
->op
== OP_MERGE
) {
968 merges
.push_back(insn
);
969 if (insn
->srcExists(1))
970 makeCompound(insn
, false);
974 if (!(mask
& JOIN_MASK_UNION
))
976 splits
.push_back(insn
);
977 for (c
= 0; insn
->defExists(c
); ++c
)
978 coalesceValues(insn
->getSrc(0), insn
->getDef(c
), true);
979 makeCompound(insn
, true);
982 if (!(mask
& JOIN_MASK_MOV
))
985 if (!insn
->getDef(0)->uses
.empty())
986 i
= insn
->getDef(0)->uses
.front()->getInsn();
987 // if this is a contraint-move there will only be a single use
988 if (i
&& i
->op
== OP_MERGE
) // do we really still need this ?
990 i
= insn
->getSrc(0)->getUniqueInsn();
991 if (i
&& !i
->constrainedDefs()) {
992 if (coalesceValues(insn
->getDef(0), insn
->getSrc(0), false))
993 copyCompound(insn
->getSrc(0), insn
->getDef(0));
1004 if (!(mask
& JOIN_MASK_TEX
))
1006 for (c
= 0; insn
->srcExists(c
) && c
!= insn
->predSrc
; ++c
)
1007 coalesceValues(insn
->getDef(c
), insn
->getSrc(c
), true);
1017 GCRA::RIG_Node::addInterference(RIG_Node
*node
)
1019 this->degree
+= relDegree
[node
->colors
][colors
];
1020 node
->degree
+= relDegree
[colors
][node
->colors
];
1022 this->attach(node
, Graph::Edge::CROSS
);
1026 GCRA::RIG_Node::addRegPreference(RIG_Node
*node
)
1028 prefRegs
.push_back(node
);
1031 GCRA::GCRA(Function
*fn
, SpillCodeInserter
& spill
) :
1033 regs(fn
->getProgram()->getTarget()),
1036 prog
= func
->getProgram();
1038 // initialize relative degrees array - i takes away from j
1039 for (int i
= 1; i
<= 16; ++i
)
1040 for (int j
= 1; j
<= 16; ++j
)
1041 relDegree
[i
][j
] = j
* ((i
+ j
- 1) / j
);
1051 GCRA::checkList(std::list
<RIG_Node
*>& lst
)
1053 GCRA::RIG_Node
*prev
= NULL
;
1055 for (std::list
<RIG_Node
*>::iterator it
= lst
.begin();
1058 assert((*it
)->getValue()->join
== (*it
)->getValue());
1060 assert(prev
->livei
.begin() <= (*it
)->livei
.begin());
1066 GCRA::insertOrderedTail(std::list
<RIG_Node
*>& list
, RIG_Node
*node
)
1068 if (node
->livei
.isEmpty())
1070 // only the intervals of joined values don't necessarily arrive in order
1071 std::list
<RIG_Node
*>::iterator prev
, it
;
1072 for (it
= list
.end(); it
!= list
.begin(); it
= prev
) {
1075 if ((*prev
)->livei
.begin() <= node
->livei
.begin())
1078 list
.insert(it
, node
);
1082 GCRA::buildRIG(ArrayList
& insns
)
1084 std::list
<RIG_Node
*> values
, active
;
1086 for (std::deque
<ValueDef
>::iterator it
= func
->ins
.begin();
1087 it
!= func
->ins
.end(); ++it
)
1088 insertOrderedTail(values
, getNode(it
->get()->asLValue()));
1090 for (int i
= 0; i
< insns
.getSize(); ++i
) {
1091 Instruction
*insn
= reinterpret_cast<Instruction
*>(insns
.get(i
));
1092 for (int d
= 0; insn
->defExists(d
); ++d
)
1093 if (insn
->getDef(d
)->rep() == insn
->getDef(d
))
1094 insertOrderedTail(values
, getNode(insn
->getDef(d
)->asLValue()));
1098 while (!values
.empty()) {
1099 RIG_Node
*cur
= values
.front();
1101 for (std::list
<RIG_Node
*>::iterator it
= active
.begin();
1102 it
!= active
.end();) {
1103 RIG_Node
*node
= *it
;
1105 if (node
->livei
.end() <= cur
->livei
.begin()) {
1106 it
= active
.erase(it
);
1108 if (node
->f
== cur
->f
&& node
->livei
.overlaps(cur
->livei
))
1109 cur
->addInterference(node
);
1114 active
.push_back(cur
);
1119 GCRA::calculateSpillWeights()
1121 for (unsigned int i
= 0; i
< nodeCount
; ++i
) {
1122 RIG_Node
*const n
= &nodes
[i
];
1123 if (!nodes
[i
].colors
|| nodes
[i
].livei
.isEmpty())
1125 if (nodes
[i
].reg
>= 0) {
1127 regs
.occupy(n
->f
, n
->reg
, n
->colors
);
1130 LValue
*val
= nodes
[i
].getValue();
1132 if (!val
->noSpill
) {
1134 for (Value::DefIterator it
= val
->defs
.begin();
1135 it
!= val
->defs
.end();
1137 rc
+= (*it
)->get()->refCount();
1140 (float)rc
* (float)rc
/ (float)nodes
[i
].livei
.extent();
1143 if (nodes
[i
].degree
< nodes
[i
].degreeLimit
) {
1145 if (val
->reg
.size
> 4)
1147 DLLIST_ADDHEAD(&lo
[l
], &nodes
[i
]);
1149 DLLIST_ADDHEAD(&hi
, &nodes
[i
]);
1152 if (prog
->dbgFlags
& NV50_IR_DEBUG_REG_ALLOC
)
1157 GCRA::simplifyEdge(RIG_Node
*a
, RIG_Node
*b
)
1159 bool move
= b
->degree
>= b
->degreeLimit
;
1161 INFO_DBG(prog
->dbgFlags
, REG_ALLOC
,
1162 "edge: (%%%i, deg %u/%u) >-< (%%%i, deg %u/%u)\n",
1163 a
->getValue()->id
, a
->degree
, a
->degreeLimit
,
1164 b
->getValue()->id
, b
->degree
, b
->degreeLimit
);
1166 b
->degree
-= relDegree
[a
->colors
][b
->colors
];
1168 move
= move
&& b
->degree
< b
->degreeLimit
;
1169 if (move
&& !DLLIST_EMPTY(b
)) {
1170 int l
= (b
->getValue()->reg
.size
> 4) ? 1 : 0;
1172 DLLIST_ADDTAIL(&lo
[l
], b
);
1177 GCRA::simplifyNode(RIG_Node
*node
)
1179 for (Graph::EdgeIterator ei
= node
->outgoing(); !ei
.end(); ei
.next())
1180 simplifyEdge(node
, RIG_Node::get(ei
));
1182 for (Graph::EdgeIterator ei
= node
->incident(); !ei
.end(); ei
.next())
1183 simplifyEdge(node
, RIG_Node::get(ei
));
1186 stack
.push(node
->getValue()->id
);
1188 INFO_DBG(prog
->dbgFlags
, REG_ALLOC
, "SIMPLIFY: pushed %%%i%s\n",
1189 node
->getValue()->id
,
1190 (node
->degree
< node
->degreeLimit
) ? "" : "(spill)");
1197 if (!DLLIST_EMPTY(&lo
[0])) {
1199 simplifyNode(lo
[0].next
);
1200 } while (!DLLIST_EMPTY(&lo
[0]));
1202 if (!DLLIST_EMPTY(&lo
[1])) {
1203 simplifyNode(lo
[1].next
);
1205 if (!DLLIST_EMPTY(&hi
)) {
1206 RIG_Node
*best
= hi
.next
;
1207 float bestScore
= best
->weight
/ (float)best
->degree
;
1209 for (RIG_Node
*it
= best
->next
; it
!= &hi
; it
= it
->next
) {
1210 float score
= it
->weight
/ (float)it
->degree
;
1211 if (score
< bestScore
) {
1216 if (isinf(bestScore
)) {
1217 ERROR("no viable spill candidates left\n");
1228 GCRA::checkInterference(const RIG_Node
*node
, Graph::EdgeIterator
& ei
)
1230 const RIG_Node
*intf
= RIG_Node::get(ei
);
1234 const LValue
*vA
= node
->getValue();
1235 const LValue
*vB
= intf
->getValue();
1237 const uint8_t intfMask
= ((1 << intf
->colors
) - 1) << (intf
->reg
& 7);
1239 if (vA
->compound
| vB
->compound
) {
1240 // NOTE: this only works for >aligned< register tuples !
1241 for (Value::DefCIterator D
= vA
->defs
.begin(); D
!= vA
->defs
.end(); ++D
) {
1242 for (Value::DefCIterator d
= vB
->defs
.begin(); d
!= vB
->defs
.end(); ++d
) {
1243 const LValue
*vD
= (*D
)->get()->asLValue();
1244 const LValue
*vd
= (*d
)->get()->asLValue();
1246 if (!vD
->livei
.overlaps(vd
->livei
)) {
1247 INFO_DBG(prog
->dbgFlags
, REG_ALLOC
, "(%%%i) X (%%%i): no overlap\n",
1252 uint8_t mask
= vD
->compound
? vD
->compMask
: ~0;
1254 assert(vB
->compound
);
1255 mask
&= vd
->compMask
& vB
->compMask
;
1260 INFO_DBG(prog
->dbgFlags
, REG_ALLOC
,
1261 "(%%%i)%02x X (%%%i)%02x & %02x: $r%i.%02x\n",
1263 vD
->compound
? vD
->compMask
: 0xff,
1265 vd
->compound
? vd
->compMask
: intfMask
,
1266 vB
->compMask
, intf
->reg
& ~7, mask
);
1268 regs
.occupyMask(node
->f
, intf
->reg
& ~7, mask
);
1272 INFO_DBG(prog
->dbgFlags
, REG_ALLOC
,
1273 "(%%%i) X (%%%i): $r%i + %u\n",
1274 vA
->id
, vB
->id
, intf
->reg
, intf
->colors
);
1275 regs
.occupy(node
->f
, intf
->reg
, intf
->colors
);
1280 GCRA::selectRegisters()
1282 INFO_DBG(prog
->dbgFlags
, REG_ALLOC
, "\nSELECT phase\n");
1284 while (!stack
.empty()) {
1285 RIG_Node
*node
= &nodes
[stack
.top()];
1288 regs
.reset(node
->f
);
1290 INFO_DBG(prog
->dbgFlags
, REG_ALLOC
, "\nNODE[%%%i, %u colors]\n",
1291 node
->getValue()->id
, node
->colors
);
1293 for (Graph::EdgeIterator ei
= node
->outgoing(); !ei
.end(); ei
.next())
1294 checkInterference(node
, ei
);
1295 for (Graph::EdgeIterator ei
= node
->incident(); !ei
.end(); ei
.next())
1296 checkInterference(node
, ei
);
1298 if (!node
->prefRegs
.empty()) {
1299 for (std::list
<RIG_Node
*>::const_iterator it
= node
->prefRegs
.begin();
1300 it
!= node
->prefRegs
.end();
1302 if ((*it
)->reg
>= 0 &&
1303 regs
.testOccupy(node
->f
, (*it
)->reg
, node
->colors
)) {
1304 node
->reg
= (*it
)->reg
;
1311 LValue
*lval
= node
->getValue();
1312 if (prog
->dbgFlags
& NV50_IR_DEBUG_REG_ALLOC
)
1314 bool ret
= regs
.assign(node
->reg
, node
->f
, node
->colors
);
1316 INFO_DBG(prog
->dbgFlags
, REG_ALLOC
, "assigned reg %i\n", node
->reg
);
1317 lval
->compMask
= node
->getCompMask();
1319 INFO_DBG(prog
->dbgFlags
, REG_ALLOC
, "must spill: %%%i (size %u)\n",
1320 lval
->id
, lval
->reg
.size
);
1321 Symbol
*slot
= NULL
;
1322 if (lval
->reg
.file
== FILE_GPR
)
1323 slot
= spill
.assignSlot(node
->livei
, lval
->reg
.size
);
1324 mustSpill
.push_back(ValuePair(lval
, slot
));
1327 if (!mustSpill
.empty())
1329 for (unsigned int i
= 0; i
< nodeCount
; ++i
) {
1330 LValue
*lval
= nodes
[i
].getValue();
1331 if (nodes
[i
].reg
>= 0 && nodes
[i
].colors
> 0)
1333 regs
.unitsToId(nodes
[i
].f
, nodes
[i
].reg
, lval
->reg
.size
);
1339 GCRA::allocateRegisters(ArrayList
& insns
)
1343 INFO_DBG(prog
->dbgFlags
, REG_ALLOC
,
1344 "allocateRegisters to %u instructions\n", insns
.getSize());
1346 nodeCount
= func
->allLValues
.getSize();
1347 nodes
= new RIG_Node
[nodeCount
];
1350 for (unsigned int i
= 0; i
< nodeCount
; ++i
) {
1351 LValue
*lval
= reinterpret_cast<LValue
*>(func
->allLValues
.get(i
));
1353 nodes
[i
].init(regs
, lval
);
1354 RIG
.insert(&nodes
[i
]);
1358 // coalesce first, we use only 1 RIG node for a group of joined values
1359 ret
= coalesce(insns
);
1363 if (func
->getProgram()->dbgFlags
& NV50_IR_DEBUG_REG_ALLOC
)
1364 func
->printLiveIntervals();
1367 calculateSpillWeights();
1370 ret
= selectRegisters();
1372 INFO_DBG(prog
->dbgFlags
, REG_ALLOC
,
1373 "selectRegisters failed, inserting spill code ...\n");
1374 regs
.reset(FILE_GPR
, true);
1375 spill
.run(mustSpill
);
1376 if (prog
->dbgFlags
& NV50_IR_DEBUG_REG_ALLOC
)
1379 prog
->maxGPR
= std::max(prog
->maxGPR
, regs
.getMaxAssigned(FILE_GPR
));
1388 GCRA::cleanup(const bool success
)
1392 for (ArrayList::Iterator it
= func
->allLValues
.iterator();
1393 !it
.end(); it
.next()) {
1394 LValue
*lval
= reinterpret_cast<LValue
*>(it
.get());
1396 lval
->livei
.clear();
1401 if (lval
->join
== lval
)
1405 lval
->reg
.data
.id
= lval
->join
->reg
.data
.id
;
1407 for (Value::DefIterator d
= lval
->defs
.begin(); d
!= lval
->defs
.end();
1409 lval
->join
->defs
.remove(*d
);
1415 resolveSplitsAndMerges();
1416 splits
.clear(); // avoid duplicate entries on next coalesce pass
1424 SpillCodeInserter::assignSlot(const Interval
&livei
, const unsigned int size
)
1427 int32_t offsetBase
= stackSize
;
1429 std::list
<SpillSlot
>::iterator pos
= slots
.end(), it
= slots
.begin();
1431 if (offsetBase
% size
)
1432 offsetBase
+= size
- (offsetBase
% size
);
1436 for (offset
= offsetBase
; offset
< stackSize
; offset
+= size
) {
1437 const int32_t entryEnd
= offset
+ size
;
1438 while (it
!= slots
.end() && it
->offset
< offset
)
1440 if (it
== slots
.end()) // no slots left
1442 std::list
<SpillSlot
>::iterator bgn
= it
;
1444 while (it
!= slots
.end() && it
->offset
< entryEnd
) {
1446 if (it
->occup
.overlaps(livei
))
1450 if (it
== slots
.end() || it
->offset
>= entryEnd
) {
1452 for (; bgn
!= slots
.end() && bgn
->offset
< entryEnd
; ++bgn
) {
1453 bgn
->occup
.insert(livei
);
1454 if (bgn
->size() == size
)
1455 slot
.sym
= bgn
->sym
;
1461 stackSize
= offset
+ size
;
1462 slot
.offset
= offset
;
1463 slot
.sym
= new_Symbol(func
->getProgram(), FILE_MEMORY_LOCAL
);
1464 if (!func
->stackPtr
)
1465 offset
+= func
->tlsBase
;
1466 slot
.sym
->setAddress(NULL
, offset
);
1467 slot
.sym
->reg
.size
= size
;
1468 slots
.insert(pos
, slot
)->occup
.insert(livei
);
1474 SpillCodeInserter::offsetSlot(Value
*base
, const LValue
*lval
)
1476 if (!lval
->compound
|| (lval
->compMask
& 0x1))
1478 Value
*slot
= cloneShallow(func
, base
);
1480 slot
->reg
.data
.offset
+= (ffs(lval
->compMask
) - 1) * lval
->reg
.size
;
1481 slot
->reg
.size
= lval
->reg
.size
;
1487 SpillCodeInserter::spill(Instruction
*defi
, Value
*slot
, LValue
*lval
)
1489 const DataType ty
= typeOfSize(lval
->reg
.size
);
1491 slot
= offsetSlot(slot
, lval
);
1494 if (slot
->reg
.file
== FILE_MEMORY_LOCAL
) {
1495 st
= new_Instruction(func
, OP_STORE
, ty
);
1496 st
->setSrc(0, slot
);
1497 st
->setSrc(1, lval
);
1500 st
= new_Instruction(func
, OP_CVT
, ty
);
1501 st
->setDef(0, slot
);
1502 st
->setSrc(0, lval
);
1504 defi
->bb
->insertAfter(defi
, st
);
1508 SpillCodeInserter::unspill(Instruction
*usei
, LValue
*lval
, Value
*slot
)
1510 const DataType ty
= typeOfSize(lval
->reg
.size
);
1512 slot
= offsetSlot(slot
, lval
);
1513 lval
= cloneShallow(func
, lval
);
1516 if (slot
->reg
.file
== FILE_MEMORY_LOCAL
) {
1518 ld
= new_Instruction(func
, OP_LOAD
, ty
);
1520 ld
= new_Instruction(func
, OP_CVT
, ty
);
1522 ld
->setDef(0, lval
);
1523 ld
->setSrc(0, slot
);
1525 usei
->bb
->insertBefore(usei
, ld
);
1530 // For each value that is to be spilled, go through all its definitions.
1531 // A value can have multiple definitions if it has been coalesced before.
1532 // For each definition, first go through all its uses and insert an unspill
1533 // instruction before it, then replace the use with the temporary register.
1534 // Unspill can be either a load from memory or simply a move to another
1536 // For "Pseudo" instructions (like PHI, SPLIT, MERGE) we can erase the use
1537 // if we have spilled to a memory location, or simply with the new register.
1538 // No load or conversion instruction should be needed.
1540 SpillCodeInserter::run(const std::list
<ValuePair
>& lst
)
1542 for (std::list
<ValuePair
>::const_iterator it
= lst
.begin(); it
!= lst
.end();
1544 LValue
*lval
= it
->first
->asLValue();
1545 Symbol
*mem
= it
->second
? it
->second
->asSym() : NULL
;
1547 for (Value::DefIterator d
= lval
->defs
.begin(); d
!= lval
->defs
.end();
1550 static_cast<Value
*>(mem
) : new_LValue(func
, FILE_GPR
);
1552 Instruction
*last
= NULL
;
1554 LValue
*dval
= (*d
)->get()->asLValue();
1555 Instruction
*defi
= (*d
)->getInsn();
1557 // Unspill at each use *before* inserting spill instructions,
1558 // we don't want to have the spill instructions in the use list here.
1559 while (!dval
->uses
.empty()) {
1560 ValueRef
*u
= dval
->uses
.front();
1561 Instruction
*usei
= u
->getInsn();
1563 if (usei
->isPseudo()) {
1564 tmp
= (slot
->reg
.file
== FILE_MEMORY_LOCAL
) ? NULL
: slot
;
1567 if (!last
|| usei
!= last
->next
) { // TODO: sort uses
1568 tmp
= unspill(usei
, dval
, slot
);
1575 if (defi
->isPseudo()) {
1576 d
= lval
->defs
.erase(d
);
1578 if (slot
->reg
.file
== FILE_MEMORY_LOCAL
)
1579 delete_Instruction(func
->getProgram(), defi
);
1581 defi
->setDef(0, slot
);
1583 spill(defi
, slot
, dval
);
1589 // TODO: We're not trying to reuse old slots in a potential next iteration.
1590 // We have to update the slots' livei intervals to be able to do that.
1591 stackBase
= stackSize
;
1599 for (IteratorRef it
= prog
->calls
.iteratorDFS(false);
1600 !it
->end(); it
->next()) {
1601 func
= Function::get(reinterpret_cast<Graph::Node
*>(it
->get()));
1603 func
->tlsBase
= prog
->tlsSize
;
1606 prog
->tlsSize
+= func
->tlsSize
;
1612 RegAlloc::execFunc()
1614 InsertConstraintsPass insertConstr
;
1615 PhiMovesPass insertPhiMoves
;
1616 ArgumentMovesPass insertArgMoves
;
1617 BuildIntervalsPass buildIntervals
;
1618 SpillCodeInserter
insertSpills(func
);
1620 GCRA
gcra(func
, insertSpills
);
1622 unsigned int i
, retries
;
1625 if (!func
->ins
.empty()) {
1626 // Insert a nop at the entry so inputs only used by the first instruction
1627 // don't count as having an empty live range.
1628 Instruction
*nop
= new_Instruction(func
, OP_NOP
, TYPE_NONE
);
1629 BasicBlock::get(func
->cfg
.getRoot())->insertHead(nop
);
1632 ret
= insertConstr
.exec(func
);
1636 ret
= insertPhiMoves
.run(func
);
1640 ret
= insertArgMoves
.run(func
);
1644 // TODO: need to fix up spill slot usage ranges to support > 1 retry
1645 for (retries
= 0; retries
< 3; ++retries
) {
1646 if (retries
&& (prog
->dbgFlags
& NV50_IR_DEBUG_REG_ALLOC
))
1647 INFO("Retry: %i\n", retries
);
1648 if (prog
->dbgFlags
& NV50_IR_DEBUG_REG_ALLOC
)
1651 // spilling to registers may add live ranges, need to rebuild everything
1653 for (sequence
= func
->cfg
.nextSequence(), i
= 0;
1654 ret
&& i
<= func
->loopNestingBound
;
1655 sequence
= func
->cfg
.nextSequence(), ++i
)
1656 ret
= buildLiveSets(BasicBlock::get(func
->cfg
.getRoot()));
1659 func
->orderInstructions(this->insns
);
1661 ret
= buildIntervals
.run(func
);
1664 ret
= gcra
.allocateRegisters(insns
);
1668 INFO_DBG(prog
->dbgFlags
, REG_ALLOC
, "RegAlloc done: %i\n", ret
);
1670 func
->tlsSize
= insertSpills
.getStackSize();
1675 // TODO: check if modifying Instruction::join here breaks anything
1677 GCRA::resolveSplitsAndMerges()
1679 for (std::list
<Instruction
*>::iterator it
= splits
.begin();
1682 Instruction
*split
= *it
;
1683 unsigned int reg
= regs
.idToBytes(split
->getSrc(0));
1684 for (int d
= 0; split
->defExists(d
); ++d
) {
1685 Value
*v
= split
->getDef(d
);
1686 v
->reg
.data
.id
= regs
.bytesToId(v
, reg
);
1693 for (std::list
<Instruction
*>::iterator it
= merges
.begin();
1696 Instruction
*merge
= *it
;
1697 unsigned int reg
= regs
.idToBytes(merge
->getDef(0));
1698 for (int s
= 0; merge
->srcExists(s
); ++s
) {
1699 Value
*v
= merge
->getSrc(s
);
1700 v
->reg
.data
.id
= regs
.bytesToId(v
, reg
);
1708 bool Program::registerAllocation()
1715 RegAlloc::InsertConstraintsPass::exec(Function
*ir
)
1719 bool ret
= run(ir
, true, true);
1721 ret
= insertConstraintMoves();
1725 // TODO: make part of texture insn
1727 RegAlloc::InsertConstraintsPass::textureMask(TexInstruction
*tex
)
1733 for (d
= 0, k
= 0, c
= 0; c
< 4; ++c
) {
1734 if (!(tex
->tex
.mask
& (1 << c
)))
1736 if (tex
->getDef(k
)->refCount()) {
1738 def
[d
++] = tex
->getDef(k
);
1742 tex
->tex
.mask
= mask
;
1744 for (c
= 0; c
< d
; ++c
)
1745 tex
->setDef(c
, def
[c
]);
1747 tex
->setDef(c
, NULL
);
1751 RegAlloc::InsertConstraintsPass::detectConflict(Instruction
*cst
, int s
)
1753 Value
*v
= cst
->getSrc(s
);
1755 // current register allocation can't handle it if a value participates in
1756 // multiple constraints
1757 for (Value::UseIterator it
= v
->uses
.begin(); it
!= v
->uses
.end(); ++it
) {
1758 if (cst
!= (*it
)->getInsn())
1762 // can start at s + 1 because detectConflict is called on all sources
1763 for (int c
= s
+ 1; cst
->srcExists(c
); ++c
)
1764 if (v
== cst
->getSrc(c
))
1767 Instruction
*defi
= v
->getInsn();
1769 return (!defi
|| defi
->constrainedDefs());
1773 RegAlloc::InsertConstraintsPass::addConstraint(Instruction
*i
, int s
, int n
)
1778 // first, look for an existing identical constraint op
1779 for (std::list
<Instruction
*>::iterator it
= constrList
.begin();
1780 it
!= constrList
.end();
1783 if (!i
->bb
->dominatedBy(cst
->bb
))
1785 for (d
= 0; d
< n
; ++d
)
1786 if (cst
->getSrc(d
) != i
->getSrc(d
+ s
))
1789 for (d
= 0; d
< n
; ++d
, ++s
)
1790 i
->setSrc(s
, cst
->getDef(d
));
1794 cst
= new_Instruction(func
, OP_CONSTRAINT
, i
->dType
);
1796 for (d
= 0; d
< n
; ++s
, ++d
) {
1797 cst
->setDef(d
, new_LValue(func
, FILE_GPR
));
1798 cst
->setSrc(d
, i
->getSrc(s
));
1799 i
->setSrc(s
, cst
->getDef(d
));
1801 i
->bb
->insertBefore(i
, cst
);
1803 constrList
.push_back(cst
);
1806 // Add a dummy use of the pointer source of >= 8 byte loads after the load
1807 // to prevent it from being assigned a register which overlapping the load's
1808 // destination, which would produce random corruptions.
1810 RegAlloc::InsertConstraintsPass::addHazard(Instruction
*i
, const ValueRef
*src
)
1812 Instruction
*hzd
= new_Instruction(func
, OP_NOP
, TYPE_NONE
);
1813 hzd
->setSrc(0, src
->get());
1814 i
->bb
->insertAfter(i
, hzd
);
1818 // b32 { %r0 %r1 %r2 %r3 } -> b128 %r0q
1820 RegAlloc::InsertConstraintsPass::condenseDefs(Instruction
*insn
)
1824 for (n
= 0; insn
->defExists(n
) && insn
->def(n
).getFile() == FILE_GPR
; ++n
)
1825 size
+= insn
->getDef(n
)->reg
.size
;
1828 LValue
*lval
= new_LValue(func
, FILE_GPR
);
1829 lval
->reg
.size
= size
;
1831 Instruction
*split
= new_Instruction(func
, OP_SPLIT
, typeOfSize(size
));
1832 split
->setSrc(0, lval
);
1833 for (int d
= 0; d
< n
; ++d
) {
1834 split
->setDef(d
, insn
->getDef(d
));
1835 insn
->setDef(d
, NULL
);
1837 insn
->setDef(0, lval
);
1839 for (int k
= 1, d
= n
; insn
->defExists(d
); ++d
, ++k
) {
1840 insn
->setDef(k
, insn
->getDef(d
));
1841 insn
->setDef(d
, NULL
);
1843 // carry over predicate if any (mainly for OP_UNION uses)
1844 split
->setPredicate(insn
->cc
, insn
->getPredicate());
1846 insn
->bb
->insertAfter(insn
, split
);
1847 constrList
.push_back(split
);
1850 RegAlloc::InsertConstraintsPass::condenseSrcs(Instruction
*insn
,
1851 const int a
, const int b
)
1856 for (int s
= a
; s
<= b
; ++s
)
1857 size
+= insn
->getSrc(s
)->reg
.size
;
1860 LValue
*lval
= new_LValue(func
, FILE_GPR
);
1861 lval
->reg
.size
= size
;
1864 insn
->takeExtraSources(0, save
);
1866 Instruction
*merge
= new_Instruction(func
, OP_MERGE
, typeOfSize(size
));
1867 merge
->setDef(0, lval
);
1868 for (int s
= a
, i
= 0; s
<= b
; ++s
, ++i
) {
1869 merge
->setSrc(i
, insn
->getSrc(s
));
1870 insn
->setSrc(s
, NULL
);
1872 insn
->setSrc(a
, lval
);
1874 for (int k
= a
+ 1, s
= b
+ 1; insn
->srcExists(s
); ++s
, ++k
) {
1875 insn
->setSrc(k
, insn
->getSrc(s
));
1876 insn
->setSrc(s
, NULL
);
1878 insn
->bb
->insertBefore(insn
, merge
);
1880 insn
->putExtraSources(0, save
);
1882 constrList
.push_back(merge
);
1886 RegAlloc::InsertConstraintsPass::texConstraintGM107(TexInstruction
*tex
)
1890 if (isTextureOp(tex
->op
))
1894 if (tex
->op
== OP_SUSTB
|| tex
->op
== OP_SUSTP
) {
1895 condenseSrcs(tex
, 3, (3 + typeSizeof(tex
->dType
) / 4) - 1);
1897 if (isTextureOp(tex
->op
)) {
1898 if (tex
->op
!= OP_TXQ
) {
1899 s
= tex
->tex
.target
.getArgCount() - tex
->tex
.target
.isMS();
1900 n
= tex
->srcCount(0xff) - s
;
1902 s
= tex
->srcCount(0xff);
1907 condenseSrcs(tex
, 0, s
- 1);
1908 if (n
> 1) // NOTE: first call modified positions already
1909 condenseSrcs(tex
, 1, n
);
1914 RegAlloc::InsertConstraintsPass::texConstraintNVE0(TexInstruction
*tex
)
1916 if (isTextureOp(tex
->op
))
1920 if (tex
->op
== OP_SUSTB
|| tex
->op
== OP_SUSTP
) {
1921 condenseSrcs(tex
, 3, (3 + typeSizeof(tex
->dType
) / 4) - 1);
1923 if (isTextureOp(tex
->op
)) {
1924 int n
= tex
->srcCount(0xff, true);
1926 condenseSrcs(tex
, 0, 3);
1927 if (n
> 5) // NOTE: first call modified positions already
1928 condenseSrcs(tex
, 4 - (4 - 1), n
- 1 - (4 - 1));
1931 condenseSrcs(tex
, 0, n
- 1);
1937 RegAlloc::InsertConstraintsPass::texConstraintNVC0(TexInstruction
*tex
)
1943 if (tex
->op
== OP_TXQ
) {
1944 s
= tex
->srcCount(0xff);
1947 s
= tex
->tex
.target
.getArgCount() - tex
->tex
.target
.isMS();
1948 if (!tex
->tex
.target
.isArray() &&
1949 (tex
->tex
.rIndirectSrc
>= 0 || tex
->tex
.sIndirectSrc
>= 0))
1951 if (tex
->op
== OP_TXD
&& tex
->tex
.useOffsets
)
1953 n
= tex
->srcCount(0xff) - s
;
1958 condenseSrcs(tex
, 0, s
- 1);
1959 if (n
> 1) // NOTE: first call modified positions already
1960 condenseSrcs(tex
, 1, n
);
1966 RegAlloc::InsertConstraintsPass::texConstraintNV50(TexInstruction
*tex
)
1968 Value
*pred
= tex
->getPredicate();
1970 tex
->setPredicate(tex
->cc
, NULL
);
1974 assert(tex
->defExists(0) && tex
->srcExists(0));
1975 // make src and def count match
1977 for (c
= 0; tex
->srcExists(c
) || tex
->defExists(c
); ++c
) {
1978 if (!tex
->srcExists(c
))
1979 tex
->setSrc(c
, new_LValue(func
, tex
->getSrc(0)->asLValue()));
1980 if (!tex
->defExists(c
))
1981 tex
->setDef(c
, new_LValue(func
, tex
->getDef(0)->asLValue()));
1984 tex
->setPredicate(tex
->cc
, pred
);
1986 condenseSrcs(tex
, 0, c
- 1);
1989 // Insert constraint markers for instructions whose multiple sources must be
1990 // located in consecutive registers.
1992 RegAlloc::InsertConstraintsPass::visit(BasicBlock
*bb
)
1994 TexInstruction
*tex
;
1998 targ
= bb
->getProgram()->getTarget();
2000 for (Instruction
*i
= bb
->getEntry(); i
; i
= next
) {
2003 if ((tex
= i
->asTex())) {
2004 switch (targ
->getChipset() & ~0xf) {
2009 texConstraintNV50(tex
);
2013 texConstraintNVC0(tex
);
2018 texConstraintNVE0(tex
);
2021 texConstraintGM107(tex
);
2027 if (i
->op
== OP_EXPORT
|| i
->op
== OP_STORE
) {
2028 for (size
= typeSizeof(i
->dType
), s
= 1; size
> 0; ++s
) {
2029 assert(i
->srcExists(s
));
2030 size
-= i
->getSrc(s
)->reg
.size
;
2032 condenseSrcs(i
, 1, s
- 1);
2034 if (i
->op
== OP_LOAD
|| i
->op
== OP_VFETCH
) {
2036 if (i
->src(0).isIndirect(0) && typeSizeof(i
->dType
) >= 8)
2037 addHazard(i
, i
->src(0).getIndirect(0));
2039 if (i
->op
== OP_UNION
||
2040 i
->op
== OP_MERGE
||
2041 i
->op
== OP_SPLIT
) {
2042 constrList
.push_back(i
);
2048 // Insert extra moves so that, if multiple register constraints on a value are
2049 // in conflict, these conflicts can be resolved.
2051 RegAlloc::InsertConstraintsPass::insertConstraintMoves()
2053 for (std::list
<Instruction
*>::iterator it
= constrList
.begin();
2054 it
!= constrList
.end();
2056 Instruction
*cst
= *it
;
2059 if (cst
->op
== OP_SPLIT
&& 0) {
2060 // spilling splits is annoying, just make sure they're separate
2061 for (int d
= 0; cst
->defExists(d
); ++d
) {
2062 if (!cst
->getDef(d
)->refCount())
2064 LValue
*lval
= new_LValue(func
, cst
->def(d
).getFile());
2065 const uint8_t size
= cst
->def(d
).getSize();
2066 lval
->reg
.size
= size
;
2068 mov
= new_Instruction(func
, OP_MOV
, typeOfSize(size
));
2069 mov
->setSrc(0, lval
);
2070 mov
->setDef(0, cst
->getDef(d
));
2071 cst
->setDef(d
, mov
->getSrc(0));
2072 cst
->bb
->insertAfter(cst
, mov
);
2074 cst
->getSrc(0)->asLValue()->noSpill
= 1;
2075 mov
->getSrc(0)->asLValue()->noSpill
= 1;
2078 if (cst
->op
== OP_MERGE
|| cst
->op
== OP_UNION
) {
2079 for (int s
= 0; cst
->srcExists(s
); ++s
) {
2080 const uint8_t size
= cst
->src(s
).getSize();
2082 if (!cst
->getSrc(s
)->defs
.size()) {
2083 mov
= new_Instruction(func
, OP_NOP
, typeOfSize(size
));
2084 mov
->setDef(0, cst
->getSrc(s
));
2085 cst
->bb
->insertBefore(cst
, mov
);
2088 assert(cst
->getSrc(s
)->defs
.size() == 1); // still SSA
2090 Instruction
*defi
= cst
->getSrc(s
)->defs
.front()->getInsn();
2091 // catch some cases where don't really need MOVs
2092 if (cst
->getSrc(s
)->refCount() == 1 && !defi
->constrainedDefs())
2095 LValue
*lval
= new_LValue(func
, cst
->src(s
).getFile());
2096 lval
->reg
.size
= size
;
2098 mov
= new_Instruction(func
, OP_MOV
, typeOfSize(size
));
2099 mov
->setDef(0, lval
);
2100 mov
->setSrc(0, cst
->getSrc(s
));
2101 cst
->setSrc(s
, mov
->getDef(0));
2102 cst
->bb
->insertBefore(cst
, mov
);
2104 cst
->getDef(0)->asLValue()->noSpill
= 1; // doesn't help
2106 if (cst
->op
== OP_UNION
)
2107 mov
->setPredicate(defi
->cc
, defi
->getPredicate());
2115 } // namespace nv50_ir