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
.begin())->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));
1006 if (!(mask
& JOIN_MASK_TEX
))
1008 for (c
= 0; insn
->srcExists(c
) && c
!= insn
->predSrc
; ++c
)
1009 coalesceValues(insn
->getDef(c
), insn
->getSrc(c
), true);
1019 GCRA::RIG_Node::addInterference(RIG_Node
*node
)
1021 this->degree
+= relDegree
[node
->colors
][colors
];
1022 node
->degree
+= relDegree
[colors
][node
->colors
];
1024 this->attach(node
, Graph::Edge::CROSS
);
1028 GCRA::RIG_Node::addRegPreference(RIG_Node
*node
)
1030 prefRegs
.push_back(node
);
1033 GCRA::GCRA(Function
*fn
, SpillCodeInserter
& spill
) :
1035 regs(fn
->getProgram()->getTarget()),
1038 prog
= func
->getProgram();
1040 // initialize relative degrees array - i takes away from j
1041 for (int i
= 1; i
<= 16; ++i
)
1042 for (int j
= 1; j
<= 16; ++j
)
1043 relDegree
[i
][j
] = j
* ((i
+ j
- 1) / j
);
1053 GCRA::checkList(std::list
<RIG_Node
*>& lst
)
1055 GCRA::RIG_Node
*prev
= NULL
;
1057 for (std::list
<RIG_Node
*>::iterator it
= lst
.begin();
1060 assert((*it
)->getValue()->join
== (*it
)->getValue());
1062 assert(prev
->livei
.begin() <= (*it
)->livei
.begin());
1068 GCRA::insertOrderedTail(std::list
<RIG_Node
*>& list
, RIG_Node
*node
)
1070 if (node
->livei
.isEmpty())
1072 // only the intervals of joined values don't necessarily arrive in order
1073 std::list
<RIG_Node
*>::iterator prev
, it
;
1074 for (it
= list
.end(); it
!= list
.begin(); it
= prev
) {
1077 if ((*prev
)->livei
.begin() <= node
->livei
.begin())
1080 list
.insert(it
, node
);
1084 GCRA::buildRIG(ArrayList
& insns
)
1086 std::list
<RIG_Node
*> values
, active
;
1088 for (std::deque
<ValueDef
>::iterator it
= func
->ins
.begin();
1089 it
!= func
->ins
.end(); ++it
)
1090 insertOrderedTail(values
, getNode(it
->get()->asLValue()));
1092 for (int i
= 0; i
< insns
.getSize(); ++i
) {
1093 Instruction
*insn
= reinterpret_cast<Instruction
*>(insns
.get(i
));
1094 for (int d
= 0; insn
->defExists(d
); ++d
)
1095 if (insn
->getDef(d
)->rep() == insn
->getDef(d
))
1096 insertOrderedTail(values
, getNode(insn
->getDef(d
)->asLValue()));
1100 while (!values
.empty()) {
1101 RIG_Node
*cur
= values
.front();
1103 for (std::list
<RIG_Node
*>::iterator it
= active
.begin();
1104 it
!= active
.end();) {
1105 RIG_Node
*node
= *it
;
1107 if (node
->livei
.end() <= cur
->livei
.begin()) {
1108 it
= active
.erase(it
);
1110 if (node
->f
== cur
->f
&& node
->livei
.overlaps(cur
->livei
))
1111 cur
->addInterference(node
);
1116 active
.push_back(cur
);
1121 GCRA::calculateSpillWeights()
1123 for (unsigned int i
= 0; i
< nodeCount
; ++i
) {
1124 RIG_Node
*const n
= &nodes
[i
];
1125 if (!nodes
[i
].colors
|| nodes
[i
].livei
.isEmpty())
1127 if (nodes
[i
].reg
>= 0) {
1129 regs
.occupy(n
->f
, n
->reg
, n
->colors
);
1132 LValue
*val
= nodes
[i
].getValue();
1134 if (!val
->noSpill
) {
1136 for (Value::DefIterator it
= val
->defs
.begin();
1137 it
!= val
->defs
.end();
1139 rc
+= (*it
)->get()->refCount();
1142 (float)rc
* (float)rc
/ (float)nodes
[i
].livei
.extent();
1145 if (nodes
[i
].degree
< nodes
[i
].degreeLimit
) {
1147 if (val
->reg
.size
> 4)
1149 DLLIST_ADDHEAD(&lo
[l
], &nodes
[i
]);
1151 DLLIST_ADDHEAD(&hi
, &nodes
[i
]);
1154 if (prog
->dbgFlags
& NV50_IR_DEBUG_REG_ALLOC
)
1159 GCRA::simplifyEdge(RIG_Node
*a
, RIG_Node
*b
)
1161 bool move
= b
->degree
>= b
->degreeLimit
;
1163 INFO_DBG(prog
->dbgFlags
, REG_ALLOC
,
1164 "edge: (%%%i, deg %u/%u) >-< (%%%i, deg %u/%u)\n",
1165 a
->getValue()->id
, a
->degree
, a
->degreeLimit
,
1166 b
->getValue()->id
, b
->degree
, b
->degreeLimit
);
1168 b
->degree
-= relDegree
[a
->colors
][b
->colors
];
1170 move
= move
&& b
->degree
< b
->degreeLimit
;
1171 if (move
&& !DLLIST_EMPTY(b
)) {
1172 int l
= (b
->getValue()->reg
.size
> 4) ? 1 : 0;
1174 DLLIST_ADDTAIL(&lo
[l
], b
);
1179 GCRA::simplifyNode(RIG_Node
*node
)
1181 for (Graph::EdgeIterator ei
= node
->outgoing(); !ei
.end(); ei
.next())
1182 simplifyEdge(node
, RIG_Node::get(ei
));
1184 for (Graph::EdgeIterator ei
= node
->incident(); !ei
.end(); ei
.next())
1185 simplifyEdge(node
, RIG_Node::get(ei
));
1188 stack
.push(node
->getValue()->id
);
1190 INFO_DBG(prog
->dbgFlags
, REG_ALLOC
, "SIMPLIFY: pushed %%%i%s\n",
1191 node
->getValue()->id
,
1192 (node
->degree
< node
->degreeLimit
) ? "" : "(spill)");
1199 if (!DLLIST_EMPTY(&lo
[0])) {
1201 simplifyNode(lo
[0].next
);
1202 } while (!DLLIST_EMPTY(&lo
[0]));
1204 if (!DLLIST_EMPTY(&lo
[1])) {
1205 simplifyNode(lo
[1].next
);
1207 if (!DLLIST_EMPTY(&hi
)) {
1208 RIG_Node
*best
= hi
.next
;
1209 float bestScore
= best
->weight
/ (float)best
->degree
;
1211 for (RIG_Node
*it
= best
->next
; it
!= &hi
; it
= it
->next
) {
1212 float score
= it
->weight
/ (float)it
->degree
;
1213 if (score
< bestScore
) {
1218 if (isinf(bestScore
)) {
1219 ERROR("no viable spill candidates left\n");
1230 GCRA::checkInterference(const RIG_Node
*node
, Graph::EdgeIterator
& ei
)
1232 const RIG_Node
*intf
= RIG_Node::get(ei
);
1236 const LValue
*vA
= node
->getValue();
1237 const LValue
*vB
= intf
->getValue();
1239 const uint8_t intfMask
= ((1 << intf
->colors
) - 1) << (intf
->reg
& 7);
1241 if (vA
->compound
| vB
->compound
) {
1242 // NOTE: this only works for >aligned< register tuples !
1243 for (Value::DefCIterator D
= vA
->defs
.begin(); D
!= vA
->defs
.end(); ++D
) {
1244 for (Value::DefCIterator d
= vB
->defs
.begin(); d
!= vB
->defs
.end(); ++d
) {
1245 const LValue
*vD
= (*D
)->get()->asLValue();
1246 const LValue
*vd
= (*d
)->get()->asLValue();
1248 if (!vD
->livei
.overlaps(vd
->livei
)) {
1249 INFO_DBG(prog
->dbgFlags
, REG_ALLOC
, "(%%%i) X (%%%i): no overlap\n",
1254 uint8_t mask
= vD
->compound
? vD
->compMask
: ~0;
1256 assert(vB
->compound
);
1257 mask
&= vd
->compMask
& vB
->compMask
;
1262 INFO_DBG(prog
->dbgFlags
, REG_ALLOC
,
1263 "(%%%i)%02x X (%%%i)%02x & %02x: $r%i.%02x\n",
1265 vD
->compound
? vD
->compMask
: 0xff,
1267 vd
->compound
? vd
->compMask
: intfMask
,
1268 vB
->compMask
, intf
->reg
& ~7, mask
);
1270 regs
.occupyMask(node
->f
, intf
->reg
& ~7, mask
);
1274 INFO_DBG(prog
->dbgFlags
, REG_ALLOC
,
1275 "(%%%i) X (%%%i): $r%i + %u\n",
1276 vA
->id
, vB
->id
, intf
->reg
, intf
->colors
);
1277 regs
.occupy(node
->f
, intf
->reg
, intf
->colors
);
1282 GCRA::selectRegisters()
1284 INFO_DBG(prog
->dbgFlags
, REG_ALLOC
, "\nSELECT phase\n");
1286 while (!stack
.empty()) {
1287 RIG_Node
*node
= &nodes
[stack
.top()];
1290 regs
.reset(node
->f
);
1292 INFO_DBG(prog
->dbgFlags
, REG_ALLOC
, "\nNODE[%%%i, %u colors]\n",
1293 node
->getValue()->id
, node
->colors
);
1295 for (Graph::EdgeIterator ei
= node
->outgoing(); !ei
.end(); ei
.next())
1296 checkInterference(node
, ei
);
1297 for (Graph::EdgeIterator ei
= node
->incident(); !ei
.end(); ei
.next())
1298 checkInterference(node
, ei
);
1300 if (!node
->prefRegs
.empty()) {
1301 for (std::list
<RIG_Node
*>::const_iterator it
= node
->prefRegs
.begin();
1302 it
!= node
->prefRegs
.end();
1304 if ((*it
)->reg
>= 0 &&
1305 regs
.testOccupy(node
->f
, (*it
)->reg
, node
->colors
)) {
1306 node
->reg
= (*it
)->reg
;
1313 LValue
*lval
= node
->getValue();
1314 if (prog
->dbgFlags
& NV50_IR_DEBUG_REG_ALLOC
)
1316 bool ret
= regs
.assign(node
->reg
, node
->f
, node
->colors
);
1318 INFO_DBG(prog
->dbgFlags
, REG_ALLOC
, "assigned reg %i\n", node
->reg
);
1319 lval
->compMask
= node
->getCompMask();
1321 INFO_DBG(prog
->dbgFlags
, REG_ALLOC
, "must spill: %%%i (size %u)\n",
1322 lval
->id
, lval
->reg
.size
);
1323 Symbol
*slot
= NULL
;
1324 if (lval
->reg
.file
== FILE_GPR
)
1325 slot
= spill
.assignSlot(node
->livei
, lval
->reg
.size
);
1326 mustSpill
.push_back(ValuePair(lval
, slot
));
1329 if (!mustSpill
.empty())
1331 for (unsigned int i
= 0; i
< nodeCount
; ++i
) {
1332 LValue
*lval
= nodes
[i
].getValue();
1333 if (nodes
[i
].reg
>= 0 && nodes
[i
].colors
> 0)
1335 regs
.unitsToId(nodes
[i
].f
, nodes
[i
].reg
, lval
->reg
.size
);
1341 GCRA::allocateRegisters(ArrayList
& insns
)
1345 INFO_DBG(prog
->dbgFlags
, REG_ALLOC
,
1346 "allocateRegisters to %u instructions\n", insns
.getSize());
1348 nodeCount
= func
->allLValues
.getSize();
1349 nodes
= new RIG_Node
[nodeCount
];
1352 for (unsigned int i
= 0; i
< nodeCount
; ++i
) {
1353 LValue
*lval
= reinterpret_cast<LValue
*>(func
->allLValues
.get(i
));
1355 nodes
[i
].init(regs
, lval
);
1356 RIG
.insert(&nodes
[i
]);
1360 // coalesce first, we use only 1 RIG node for a group of joined values
1361 ret
= coalesce(insns
);
1365 if (func
->getProgram()->dbgFlags
& NV50_IR_DEBUG_REG_ALLOC
)
1366 func
->printLiveIntervals();
1369 calculateSpillWeights();
1372 ret
= selectRegisters();
1374 INFO_DBG(prog
->dbgFlags
, REG_ALLOC
,
1375 "selectRegisters failed, inserting spill code ...\n");
1376 regs
.reset(FILE_GPR
, true);
1377 spill
.run(mustSpill
);
1378 if (prog
->dbgFlags
& NV50_IR_DEBUG_REG_ALLOC
)
1381 prog
->maxGPR
= std::max(prog
->maxGPR
, regs
.getMaxAssigned(FILE_GPR
));
1390 GCRA::cleanup(const bool success
)
1394 for (ArrayList::Iterator it
= func
->allLValues
.iterator();
1395 !it
.end(); it
.next()) {
1396 LValue
*lval
= reinterpret_cast<LValue
*>(it
.get());
1398 lval
->livei
.clear();
1403 if (lval
->join
== lval
)
1407 lval
->reg
.data
.id
= lval
->join
->reg
.data
.id
;
1409 for (Value::DefIterator d
= lval
->defs
.begin(); d
!= lval
->defs
.end();
1411 lval
->join
->defs
.remove(*d
);
1417 resolveSplitsAndMerges();
1418 splits
.clear(); // avoid duplicate entries on next coalesce pass
1426 SpillCodeInserter::assignSlot(const Interval
&livei
, const unsigned int size
)
1429 int32_t offsetBase
= stackSize
;
1431 std::list
<SpillSlot
>::iterator pos
= slots
.end(), it
= slots
.begin();
1433 if (offsetBase
% size
)
1434 offsetBase
+= size
- (offsetBase
% size
);
1438 for (offset
= offsetBase
; offset
< stackSize
; offset
+= size
) {
1439 const int32_t entryEnd
= offset
+ size
;
1440 while (it
!= slots
.end() && it
->offset
< offset
)
1442 if (it
== slots
.end()) // no slots left
1444 std::list
<SpillSlot
>::iterator bgn
= it
;
1446 while (it
!= slots
.end() && it
->offset
< entryEnd
) {
1448 if (it
->occup
.overlaps(livei
))
1452 if (it
== slots
.end() || it
->offset
>= entryEnd
) {
1454 for (; bgn
!= slots
.end() && bgn
->offset
< entryEnd
; ++bgn
) {
1455 bgn
->occup
.insert(livei
);
1456 if (bgn
->size() == size
)
1457 slot
.sym
= bgn
->sym
;
1463 stackSize
= offset
+ size
;
1464 slot
.offset
= offset
;
1465 slot
.sym
= new_Symbol(func
->getProgram(), FILE_MEMORY_LOCAL
);
1466 if (!func
->stackPtr
)
1467 offset
+= func
->tlsBase
;
1468 slot
.sym
->setAddress(NULL
, offset
);
1469 slot
.sym
->reg
.size
= size
;
1470 slots
.insert(pos
, slot
)->occup
.insert(livei
);
1476 SpillCodeInserter::offsetSlot(Value
*base
, const LValue
*lval
)
1478 if (!lval
->compound
|| (lval
->compMask
& 0x1))
1480 Value
*slot
= cloneShallow(func
, base
);
1482 slot
->reg
.data
.offset
+= (ffs(lval
->compMask
) - 1) * lval
->reg
.size
;
1483 slot
->reg
.size
= lval
->reg
.size
;
1489 SpillCodeInserter::spill(Instruction
*defi
, Value
*slot
, LValue
*lval
)
1491 const DataType ty
= typeOfSize(lval
->reg
.size
);
1493 slot
= offsetSlot(slot
, lval
);
1496 if (slot
->reg
.file
== FILE_MEMORY_LOCAL
) {
1497 st
= new_Instruction(func
, OP_STORE
, ty
);
1498 st
->setSrc(0, slot
);
1499 st
->setSrc(1, lval
);
1502 st
= new_Instruction(func
, OP_CVT
, ty
);
1503 st
->setDef(0, slot
);
1504 st
->setSrc(0, lval
);
1506 defi
->bb
->insertAfter(defi
, st
);
1510 SpillCodeInserter::unspill(Instruction
*usei
, LValue
*lval
, Value
*slot
)
1512 const DataType ty
= typeOfSize(lval
->reg
.size
);
1514 slot
= offsetSlot(slot
, lval
);
1515 lval
= cloneShallow(func
, lval
);
1518 if (slot
->reg
.file
== FILE_MEMORY_LOCAL
) {
1520 ld
= new_Instruction(func
, OP_LOAD
, ty
);
1522 ld
= new_Instruction(func
, OP_CVT
, ty
);
1524 ld
->setDef(0, lval
);
1525 ld
->setSrc(0, slot
);
1527 usei
->bb
->insertBefore(usei
, ld
);
1532 // For each value that is to be spilled, go through all its definitions.
1533 // A value can have multiple definitions if it has been coalesced before.
1534 // For each definition, first go through all its uses and insert an unspill
1535 // instruction before it, then replace the use with the temporary register.
1536 // Unspill can be either a load from memory or simply a move to another
1538 // For "Pseudo" instructions (like PHI, SPLIT, MERGE) we can erase the use
1539 // if we have spilled to a memory location, or simply with the new register.
1540 // No load or conversion instruction should be needed.
1542 SpillCodeInserter::run(const std::list
<ValuePair
>& lst
)
1544 for (std::list
<ValuePair
>::const_iterator it
= lst
.begin(); it
!= lst
.end();
1546 LValue
*lval
= it
->first
->asLValue();
1547 Symbol
*mem
= it
->second
? it
->second
->asSym() : NULL
;
1549 for (Value::DefIterator d
= lval
->defs
.begin(); d
!= lval
->defs
.end();
1552 static_cast<Value
*>(mem
) : new_LValue(func
, FILE_GPR
);
1554 Instruction
*last
= NULL
;
1556 LValue
*dval
= (*d
)->get()->asLValue();
1557 Instruction
*defi
= (*d
)->getInsn();
1559 // Unspill at each use *before* inserting spill instructions,
1560 // we don't want to have the spill instructions in the use list here.
1561 while (!dval
->uses
.empty()) {
1562 ValueRef
*u
= *dval
->uses
.begin();
1563 Instruction
*usei
= u
->getInsn();
1565 if (usei
->isPseudo()) {
1566 tmp
= (slot
->reg
.file
== FILE_MEMORY_LOCAL
) ? NULL
: slot
;
1569 if (!last
|| usei
!= last
->next
) { // TODO: sort uses
1570 tmp
= unspill(usei
, dval
, slot
);
1577 if (defi
->isPseudo()) {
1578 d
= lval
->defs
.erase(d
);
1580 if (slot
->reg
.file
== FILE_MEMORY_LOCAL
)
1581 delete_Instruction(func
->getProgram(), defi
);
1583 defi
->setDef(0, slot
);
1585 spill(defi
, slot
, dval
);
1591 // TODO: We're not trying to reuse old slots in a potential next iteration.
1592 // We have to update the slots' livei intervals to be able to do that.
1593 stackBase
= stackSize
;
1601 for (IteratorRef it
= prog
->calls
.iteratorDFS(false);
1602 !it
->end(); it
->next()) {
1603 func
= Function::get(reinterpret_cast<Graph::Node
*>(it
->get()));
1605 func
->tlsBase
= prog
->tlsSize
;
1608 prog
->tlsSize
+= func
->tlsSize
;
1614 RegAlloc::execFunc()
1616 InsertConstraintsPass insertConstr
;
1617 PhiMovesPass insertPhiMoves
;
1618 ArgumentMovesPass insertArgMoves
;
1619 BuildIntervalsPass buildIntervals
;
1620 SpillCodeInserter
insertSpills(func
);
1622 GCRA
gcra(func
, insertSpills
);
1624 unsigned int i
, retries
;
1627 if (!func
->ins
.empty()) {
1628 // Insert a nop at the entry so inputs only used by the first instruction
1629 // don't count as having an empty live range.
1630 Instruction
*nop
= new_Instruction(func
, OP_NOP
, TYPE_NONE
);
1631 BasicBlock::get(func
->cfg
.getRoot())->insertHead(nop
);
1634 ret
= insertConstr
.exec(func
);
1638 ret
= insertPhiMoves
.run(func
);
1642 ret
= insertArgMoves
.run(func
);
1646 // TODO: need to fix up spill slot usage ranges to support > 1 retry
1647 for (retries
= 0; retries
< 3; ++retries
) {
1648 if (retries
&& (prog
->dbgFlags
& NV50_IR_DEBUG_REG_ALLOC
))
1649 INFO("Retry: %i\n", retries
);
1650 if (prog
->dbgFlags
& NV50_IR_DEBUG_REG_ALLOC
)
1653 // spilling to registers may add live ranges, need to rebuild everything
1655 for (sequence
= func
->cfg
.nextSequence(), i
= 0;
1656 ret
&& i
<= func
->loopNestingBound
;
1657 sequence
= func
->cfg
.nextSequence(), ++i
)
1658 ret
= buildLiveSets(BasicBlock::get(func
->cfg
.getRoot()));
1661 func
->orderInstructions(this->insns
);
1663 ret
= buildIntervals
.run(func
);
1666 ret
= gcra
.allocateRegisters(insns
);
1670 INFO_DBG(prog
->dbgFlags
, REG_ALLOC
, "RegAlloc done: %i\n", ret
);
1672 func
->tlsSize
= insertSpills
.getStackSize();
1677 // TODO: check if modifying Instruction::join here breaks anything
1679 GCRA::resolveSplitsAndMerges()
1681 for (std::list
<Instruction
*>::iterator it
= splits
.begin();
1684 Instruction
*split
= *it
;
1685 unsigned int reg
= regs
.idToBytes(split
->getSrc(0));
1686 for (int d
= 0; split
->defExists(d
); ++d
) {
1687 Value
*v
= split
->getDef(d
);
1688 v
->reg
.data
.id
= regs
.bytesToId(v
, reg
);
1695 for (std::list
<Instruction
*>::iterator it
= merges
.begin();
1698 Instruction
*merge
= *it
;
1699 unsigned int reg
= regs
.idToBytes(merge
->getDef(0));
1700 for (int s
= 0; merge
->srcExists(s
); ++s
) {
1701 Value
*v
= merge
->getSrc(s
);
1702 v
->reg
.data
.id
= regs
.bytesToId(v
, reg
);
1710 bool Program::registerAllocation()
1717 RegAlloc::InsertConstraintsPass::exec(Function
*ir
)
1721 bool ret
= run(ir
, true, true);
1723 ret
= insertConstraintMoves();
1727 // TODO: make part of texture insn
1729 RegAlloc::InsertConstraintsPass::textureMask(TexInstruction
*tex
)
1735 for (d
= 0, k
= 0, c
= 0; c
< 4; ++c
) {
1736 if (!(tex
->tex
.mask
& (1 << c
)))
1738 if (tex
->getDef(k
)->refCount()) {
1740 def
[d
++] = tex
->getDef(k
);
1744 tex
->tex
.mask
= mask
;
1746 for (c
= 0; c
< d
; ++c
)
1747 tex
->setDef(c
, def
[c
]);
1749 tex
->setDef(c
, NULL
);
1753 RegAlloc::InsertConstraintsPass::detectConflict(Instruction
*cst
, int s
)
1755 Value
*v
= cst
->getSrc(s
);
1757 // current register allocation can't handle it if a value participates in
1758 // multiple constraints
1759 for (Value::UseIterator it
= v
->uses
.begin(); it
!= v
->uses
.end(); ++it
) {
1760 if (cst
!= (*it
)->getInsn())
1764 // can start at s + 1 because detectConflict is called on all sources
1765 for (int c
= s
+ 1; cst
->srcExists(c
); ++c
)
1766 if (v
== cst
->getSrc(c
))
1769 Instruction
*defi
= v
->getInsn();
1771 return (!defi
|| defi
->constrainedDefs());
1775 RegAlloc::InsertConstraintsPass::addConstraint(Instruction
*i
, int s
, int n
)
1780 // first, look for an existing identical constraint op
1781 for (std::list
<Instruction
*>::iterator it
= constrList
.begin();
1782 it
!= constrList
.end();
1785 if (!i
->bb
->dominatedBy(cst
->bb
))
1787 for (d
= 0; d
< n
; ++d
)
1788 if (cst
->getSrc(d
) != i
->getSrc(d
+ s
))
1791 for (d
= 0; d
< n
; ++d
, ++s
)
1792 i
->setSrc(s
, cst
->getDef(d
));
1796 cst
= new_Instruction(func
, OP_CONSTRAINT
, i
->dType
);
1798 for (d
= 0; d
< n
; ++s
, ++d
) {
1799 cst
->setDef(d
, new_LValue(func
, FILE_GPR
));
1800 cst
->setSrc(d
, i
->getSrc(s
));
1801 i
->setSrc(s
, cst
->getDef(d
));
1803 i
->bb
->insertBefore(i
, cst
);
1805 constrList
.push_back(cst
);
1808 // Add a dummy use of the pointer source of >= 8 byte loads after the load
1809 // to prevent it from being assigned a register which overlapping the load's
1810 // destination, which would produce random corruptions.
1812 RegAlloc::InsertConstraintsPass::addHazard(Instruction
*i
, const ValueRef
*src
)
1814 Instruction
*hzd
= new_Instruction(func
, OP_NOP
, TYPE_NONE
);
1815 hzd
->setSrc(0, src
->get());
1816 i
->bb
->insertAfter(i
, hzd
);
1820 // b32 { %r0 %r1 %r2 %r3 } -> b128 %r0q
1822 RegAlloc::InsertConstraintsPass::condenseDefs(Instruction
*insn
)
1826 for (n
= 0; insn
->defExists(n
) && insn
->def(n
).getFile() == FILE_GPR
; ++n
)
1827 size
+= insn
->getDef(n
)->reg
.size
;
1830 LValue
*lval
= new_LValue(func
, FILE_GPR
);
1831 lval
->reg
.size
= size
;
1833 Instruction
*split
= new_Instruction(func
, OP_SPLIT
, typeOfSize(size
));
1834 split
->setSrc(0, lval
);
1835 for (int d
= 0; d
< n
; ++d
) {
1836 split
->setDef(d
, insn
->getDef(d
));
1837 insn
->setDef(d
, NULL
);
1839 insn
->setDef(0, lval
);
1841 for (int k
= 1, d
= n
; insn
->defExists(d
); ++d
, ++k
) {
1842 insn
->setDef(k
, insn
->getDef(d
));
1843 insn
->setDef(d
, NULL
);
1845 // carry over predicate if any (mainly for OP_UNION uses)
1846 split
->setPredicate(insn
->cc
, insn
->getPredicate());
1848 insn
->bb
->insertAfter(insn
, split
);
1849 constrList
.push_back(split
);
1852 RegAlloc::InsertConstraintsPass::condenseSrcs(Instruction
*insn
,
1853 const int a
, const int b
)
1858 for (int s
= a
; s
<= b
; ++s
)
1859 size
+= insn
->getSrc(s
)->reg
.size
;
1862 LValue
*lval
= new_LValue(func
, FILE_GPR
);
1863 lval
->reg
.size
= size
;
1866 insn
->takeExtraSources(0, save
);
1868 Instruction
*merge
= new_Instruction(func
, OP_MERGE
, typeOfSize(size
));
1869 merge
->setDef(0, lval
);
1870 for (int s
= a
, i
= 0; s
<= b
; ++s
, ++i
) {
1871 merge
->setSrc(i
, insn
->getSrc(s
));
1872 insn
->setSrc(s
, NULL
);
1874 insn
->setSrc(a
, lval
);
1876 for (int k
= a
+ 1, s
= b
+ 1; insn
->srcExists(s
); ++s
, ++k
) {
1877 insn
->setSrc(k
, insn
->getSrc(s
));
1878 insn
->setSrc(s
, NULL
);
1880 insn
->bb
->insertBefore(insn
, merge
);
1882 insn
->putExtraSources(0, save
);
1884 constrList
.push_back(merge
);
1888 RegAlloc::InsertConstraintsPass::texConstraintGM107(TexInstruction
*tex
)
1892 if (isTextureOp(tex
->op
))
1896 if (tex
->op
== OP_SUSTB
|| tex
->op
== OP_SUSTP
) {
1897 condenseSrcs(tex
, 3, (3 + typeSizeof(tex
->dType
) / 4) - 1);
1899 if (isTextureOp(tex
->op
)) {
1900 if (tex
->op
!= OP_TXQ
) {
1901 s
= tex
->tex
.target
.getArgCount() - tex
->tex
.target
.isMS();
1902 n
= tex
->srcCount(0xff) - s
;
1904 s
= tex
->srcCount(0xff);
1909 condenseSrcs(tex
, 0, s
- 1);
1910 if (n
> 1) // NOTE: first call modified positions already
1911 condenseSrcs(tex
, 1, n
);
1916 RegAlloc::InsertConstraintsPass::texConstraintNVE0(TexInstruction
*tex
)
1918 if (isTextureOp(tex
->op
))
1922 if (tex
->op
== OP_SUSTB
|| tex
->op
== OP_SUSTP
) {
1923 condenseSrcs(tex
, 3, (3 + typeSizeof(tex
->dType
) / 4) - 1);
1925 if (isTextureOp(tex
->op
)) {
1926 int n
= tex
->srcCount(0xff, true);
1928 condenseSrcs(tex
, 0, 3);
1929 if (n
> 5) // NOTE: first call modified positions already
1930 condenseSrcs(tex
, 4 - (4 - 1), n
- 1 - (4 - 1));
1933 condenseSrcs(tex
, 0, n
- 1);
1939 RegAlloc::InsertConstraintsPass::texConstraintNVC0(TexInstruction
*tex
)
1945 if (tex
->op
== OP_TXQ
) {
1946 s
= tex
->srcCount(0xff);
1949 s
= tex
->tex
.target
.getArgCount() - tex
->tex
.target
.isMS();
1950 if (!tex
->tex
.target
.isArray() &&
1951 (tex
->tex
.rIndirectSrc
>= 0 || tex
->tex
.sIndirectSrc
>= 0))
1953 if (tex
->op
== OP_TXD
&& tex
->tex
.useOffsets
)
1955 n
= tex
->srcCount(0xff) - s
;
1960 condenseSrcs(tex
, 0, s
- 1);
1961 if (n
> 1) // NOTE: first call modified positions already
1962 condenseSrcs(tex
, 1, n
);
1968 RegAlloc::InsertConstraintsPass::texConstraintNV50(TexInstruction
*tex
)
1970 Value
*pred
= tex
->getPredicate();
1972 tex
->setPredicate(tex
->cc
, NULL
);
1976 assert(tex
->defExists(0) && tex
->srcExists(0));
1977 // make src and def count match
1979 for (c
= 0; tex
->srcExists(c
) || tex
->defExists(c
); ++c
) {
1980 if (!tex
->srcExists(c
))
1981 tex
->setSrc(c
, new_LValue(func
, tex
->getSrc(0)->asLValue()));
1982 if (!tex
->defExists(c
))
1983 tex
->setDef(c
, new_LValue(func
, tex
->getDef(0)->asLValue()));
1986 tex
->setPredicate(tex
->cc
, pred
);
1988 condenseSrcs(tex
, 0, c
- 1);
1991 // Insert constraint markers for instructions whose multiple sources must be
1992 // located in consecutive registers.
1994 RegAlloc::InsertConstraintsPass::visit(BasicBlock
*bb
)
1996 TexInstruction
*tex
;
2000 targ
= bb
->getProgram()->getTarget();
2002 for (Instruction
*i
= bb
->getEntry(); i
; i
= next
) {
2005 if ((tex
= i
->asTex())) {
2006 switch (targ
->getChipset() & ~0xf) {
2011 texConstraintNV50(tex
);
2015 texConstraintNVC0(tex
);
2020 texConstraintNVE0(tex
);
2023 texConstraintGM107(tex
);
2029 if (i
->op
== OP_EXPORT
|| i
->op
== OP_STORE
) {
2030 for (size
= typeSizeof(i
->dType
), s
= 1; size
> 0; ++s
) {
2031 assert(i
->srcExists(s
));
2032 size
-= i
->getSrc(s
)->reg
.size
;
2034 condenseSrcs(i
, 1, s
- 1);
2036 if (i
->op
== OP_LOAD
|| i
->op
== OP_VFETCH
) {
2038 if (i
->src(0).isIndirect(0) && typeSizeof(i
->dType
) >= 8)
2039 addHazard(i
, i
->src(0).getIndirect(0));
2041 if (i
->op
== OP_UNION
||
2042 i
->op
== OP_MERGE
||
2043 i
->op
== OP_SPLIT
) {
2044 constrList
.push_back(i
);
2050 // Insert extra moves so that, if multiple register constraints on a value are
2051 // in conflict, these conflicts can be resolved.
2053 RegAlloc::InsertConstraintsPass::insertConstraintMoves()
2055 for (std::list
<Instruction
*>::iterator it
= constrList
.begin();
2056 it
!= constrList
.end();
2058 Instruction
*cst
= *it
;
2061 if (cst
->op
== OP_SPLIT
&& 0) {
2062 // spilling splits is annoying, just make sure they're separate
2063 for (int d
= 0; cst
->defExists(d
); ++d
) {
2064 if (!cst
->getDef(d
)->refCount())
2066 LValue
*lval
= new_LValue(func
, cst
->def(d
).getFile());
2067 const uint8_t size
= cst
->def(d
).getSize();
2068 lval
->reg
.size
= size
;
2070 mov
= new_Instruction(func
, OP_MOV
, typeOfSize(size
));
2071 mov
->setSrc(0, lval
);
2072 mov
->setDef(0, cst
->getDef(d
));
2073 cst
->setDef(d
, mov
->getSrc(0));
2074 cst
->bb
->insertAfter(cst
, mov
);
2076 cst
->getSrc(0)->asLValue()->noSpill
= 1;
2077 mov
->getSrc(0)->asLValue()->noSpill
= 1;
2080 if (cst
->op
== OP_MERGE
|| cst
->op
== OP_UNION
) {
2081 for (int s
= 0; cst
->srcExists(s
); ++s
) {
2082 const uint8_t size
= cst
->src(s
).getSize();
2084 if (!cst
->getSrc(s
)->defs
.size()) {
2085 mov
= new_Instruction(func
, OP_NOP
, typeOfSize(size
));
2086 mov
->setDef(0, cst
->getSrc(s
));
2087 cst
->bb
->insertBefore(cst
, mov
);
2090 assert(cst
->getSrc(s
)->defs
.size() == 1); // still SSA
2092 Instruction
*defi
= cst
->getSrc(s
)->defs
.front()->getInsn();
2093 // catch some cases where don't really need MOVs
2094 if (cst
->getSrc(s
)->refCount() == 1 && !defi
->constrainedDefs())
2097 LValue
*lval
= new_LValue(func
, cst
->src(s
).getFile());
2098 lval
->reg
.size
= size
;
2100 mov
= new_Instruction(func
, OP_MOV
, typeOfSize(size
));
2101 mov
->setDef(0, lval
);
2102 mov
->setSrc(0, cst
->getSrc(s
));
2103 cst
->setSrc(s
, mov
->getDef(0));
2104 cst
->bb
->insertBefore(cst
, mov
);
2106 cst
->getDef(0)->asLValue()->noSpill
= 1; // doesn't help
2108 if (cst
->op
== OP_UNION
)
2109 mov
->setPredicate(defi
->cc
, defi
->getPredicate());
2117 } // namespace nv50_ir