2 * Copyright 2011 Christoph Bumiller
4 * Permission is hereby granted, free of charge, to any person obtaining a
5 * copy of this software and associated documentation files (the "Software"),
6 * to deal in the Software without restriction, including without limitation
7 * the rights to use, copy, modify, merge, publish, distribute, sublicense,
8 * and/or sell copies of the Software, and to permit persons to whom the
9 * Software is furnished to do so, subject to the following conditions:
11 * The above copyright notice and this permission notice shall be included in
12 * all copies or substantial portions of the Software.
14 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
15 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
16 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
17 * THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR
18 * OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE,
19 * ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
20 * OTHER DEALINGS IN THE SOFTWARE.
23 #include "codegen/nv50_ir.h"
24 #include "codegen/nv50_ir_target.h"
31 #define MAX_REGISTER_FILE_SIZE 256
36 RegisterSet(const Target
*);
38 void init(const Target
*);
39 void reset(DataFile
, bool resetMax
= false);
41 void periodicMask(DataFile f
, uint32_t lock
, uint32_t unlock
);
42 void intersect(DataFile f
, const RegisterSet
*);
44 bool assign(int32_t& reg
, DataFile f
, unsigned int size
);
45 void release(DataFile f
, int32_t reg
, unsigned int size
);
46 void occupy(DataFile f
, int32_t reg
, unsigned int size
);
47 void occupy(const Value
*);
48 void occupyMask(DataFile f
, int32_t reg
, uint8_t mask
);
49 bool isOccupied(DataFile f
, int32_t reg
, unsigned int size
) const;
50 bool testOccupy(const Value
*);
51 bool testOccupy(DataFile f
, int32_t reg
, unsigned int size
);
53 inline int getMaxAssigned(DataFile f
) const { return fill
[f
]; }
55 inline unsigned int getFileSize(DataFile f
, uint8_t regSize
) const
57 if (restrictedGPR16Range
&& f
== FILE_GPR
&& regSize
== 2)
58 return (last
[f
] + 1) / 2;
62 inline unsigned int units(DataFile f
, unsigned int size
) const
64 return size
>> unit
[f
];
66 // for regs of size >= 4, id is counted in 4-byte words (like nv50/c0 binary)
67 inline unsigned int idToBytes(const Value
*v
) const
69 return v
->reg
.data
.id
* MIN2(v
->reg
.size
, 4);
71 inline unsigned int idToUnits(const Value
*v
) const
73 return units(v
->reg
.file
, idToBytes(v
));
75 inline int bytesToId(Value
*v
, unsigned int bytes
) const
78 return units(v
->reg
.file
, bytes
);
81 inline int unitsToId(DataFile f
, int u
, uint8_t size
) const
85 return (size
< 4) ? u
: ((u
<< unit
[f
]) / 4);
91 BitSet bits
[LAST_REGISTER_FILE
+ 1];
93 int unit
[LAST_REGISTER_FILE
+ 1]; // log2 of allocation granularity
95 int last
[LAST_REGISTER_FILE
+ 1];
96 int fill
[LAST_REGISTER_FILE
+ 1];
98 const bool restrictedGPR16Range
;
102 RegisterSet::reset(DataFile f
, bool resetMax
)
110 RegisterSet::init(const Target
*targ
)
112 for (unsigned int rf
= 0; rf
<= FILE_ADDRESS
; ++rf
) {
113 DataFile f
= static_cast<DataFile
>(rf
);
114 last
[rf
] = targ
->getFileSize(f
) - 1;
115 unit
[rf
] = targ
->getFileUnit(f
);
117 assert(last
[rf
] < MAX_REGISTER_FILE_SIZE
);
118 bits
[rf
].allocate(last
[rf
] + 1, true);
122 RegisterSet::RegisterSet(const Target
*targ
)
123 : restrictedGPR16Range(targ
->getChipset() < 0xc0)
126 for (unsigned int i
= 0; i
<= LAST_REGISTER_FILE
; ++i
)
127 reset(static_cast<DataFile
>(i
));
131 RegisterSet::periodicMask(DataFile f
, uint32_t lock
, uint32_t unlock
)
133 bits
[f
].periodicMask32(lock
, unlock
);
137 RegisterSet::intersect(DataFile f
, const RegisterSet
*set
)
139 bits
[f
] |= set
->bits
[f
];
143 RegisterSet::print() const
146 bits
[FILE_GPR
].print();
151 RegisterSet::assign(int32_t& reg
, DataFile f
, unsigned int size
)
153 reg
= bits
[f
].findFreeRange(size
);
156 fill
[f
] = MAX2(fill
[f
], (int32_t)(reg
+ size
- 1));
161 RegisterSet::isOccupied(DataFile f
, int32_t reg
, unsigned int size
) const
163 return bits
[f
].testRange(reg
, size
);
167 RegisterSet::occupy(const Value
*v
)
169 occupy(v
->reg
.file
, idToUnits(v
), v
->reg
.size
>> unit
[v
->reg
.file
]);
173 RegisterSet::occupyMask(DataFile f
, int32_t reg
, uint8_t mask
)
175 bits
[f
].setMask(reg
& ~31, static_cast<uint32_t>(mask
) << (reg
% 32));
179 RegisterSet::occupy(DataFile f
, int32_t reg
, unsigned int size
)
181 bits
[f
].setRange(reg
, size
);
183 INFO_DBG(0, REG_ALLOC
, "reg occupy: %u[%i] %u\n", f
, reg
, size
);
185 fill
[f
] = MAX2(fill
[f
], (int32_t)(reg
+ size
- 1));
189 RegisterSet::testOccupy(const Value
*v
)
191 return testOccupy(v
->reg
.file
,
192 idToUnits(v
), v
->reg
.size
>> unit
[v
->reg
.file
]);
196 RegisterSet::testOccupy(DataFile f
, int32_t reg
, unsigned int size
)
198 if (isOccupied(f
, reg
, size
))
200 occupy(f
, reg
, size
);
205 RegisterSet::release(DataFile f
, int32_t reg
, unsigned int size
)
207 bits
[f
].clrRange(reg
, size
);
209 INFO_DBG(0, REG_ALLOC
, "reg release: %u[%i] %u\n", f
, reg
, size
);
215 RegAlloc(Program
*program
) : prog(program
), sequence(0) { }
221 class PhiMovesPass
: public Pass
{
223 virtual bool visit(BasicBlock
*);
224 inline bool needNewElseBlock(BasicBlock
*b
, BasicBlock
*p
);
227 class ArgumentMovesPass
: public Pass
{
229 virtual bool visit(BasicBlock
*);
232 class BuildIntervalsPass
: public Pass
{
234 virtual bool visit(BasicBlock
*);
235 void collectLiveValues(BasicBlock
*);
236 void addLiveRange(Value
*, const BasicBlock
*, int end
);
239 class InsertConstraintsPass
: public Pass
{
241 bool exec(Function
*func
);
243 virtual bool visit(BasicBlock
*);
245 bool insertConstraintMoves();
247 void condenseDefs(Instruction
*);
248 void condenseSrcs(Instruction
*, const int first
, const int last
);
250 void addHazard(Instruction
*i
, const ValueRef
*src
);
251 void textureMask(TexInstruction
*);
252 void addConstraint(Instruction
*, int s
, int n
);
253 bool detectConflict(Instruction
*, int s
);
255 // target specific functions, TODO: put in subclass or Target
256 void texConstraintNV50(TexInstruction
*);
257 void texConstraintNVC0(TexInstruction
*);
258 void texConstraintNVE0(TexInstruction
*);
260 std::list
<Instruction
*> constrList
;
265 bool buildLiveSets(BasicBlock
*);
271 // instructions in control flow / chronological order
274 int sequence
; // for manual passes through CFG
277 typedef std::pair
<Value
*, Value
*> ValuePair
;
279 class SpillCodeInserter
282 SpillCodeInserter(Function
*fn
) : func(fn
), stackSize(0), stackBase(0) { }
284 bool run(const std::list
<ValuePair
>&);
286 Symbol
*assignSlot(const Interval
&, const unsigned int size
);
287 inline int32_t getStackSize() const { return stackSize
; }
295 std::list
<Value
*> residents
; // needed to recalculate occup
298 inline uint8_t size() const { return sym
->reg
.size
; }
300 std::list
<SpillSlot
> slots
;
304 LValue
*unspill(Instruction
*usei
, LValue
*, Value
*slot
);
305 void spill(Instruction
*defi
, Value
*slot
, LValue
*);
309 RegAlloc::BuildIntervalsPass::addLiveRange(Value
*val
,
310 const BasicBlock
*bb
,
313 Instruction
*insn
= val
->getUniqueInsn();
316 insn
= bb
->getFirst();
318 assert(bb
->getFirst()->serial
<= bb
->getExit()->serial
);
319 assert(bb
->getExit()->serial
+ 1 >= end
);
321 int begin
= insn
->serial
;
322 if (begin
< bb
->getEntry()->serial
|| begin
> bb
->getExit()->serial
)
323 begin
= bb
->getEntry()->serial
;
325 INFO_DBG(prog
->dbgFlags
, REG_ALLOC
, "%%%i <- live range [%i(%i), %i)\n",
326 val
->id
, begin
, insn
->serial
, end
);
328 if (begin
!= end
) // empty ranges are only added as hazards for fixed regs
329 val
->livei
.extend(begin
, end
);
333 RegAlloc::PhiMovesPass::needNewElseBlock(BasicBlock
*b
, BasicBlock
*p
)
335 if (b
->cfg
.incidentCount() <= 1)
339 for (Graph::EdgeIterator ei
= p
->cfg
.outgoing(); !ei
.end(); ei
.next())
340 if (ei
.getType() == Graph::Edge::TREE
||
341 ei
.getType() == Graph::Edge::FORWARD
)
346 // For each operand of each PHI in b, generate a new value by inserting a MOV
347 // at the end of the block it is coming from and replace the operand with its
348 // result. This eliminates liveness conflicts and enables us to let values be
349 // copied to the right register if such a conflict exists nonetheless.
351 // These MOVs are also crucial in making sure the live intervals of phi srces
352 // are extended until the end of the loop, since they are not included in the
355 RegAlloc::PhiMovesPass::visit(BasicBlock
*bb
)
357 Instruction
*phi
, *mov
;
360 std::stack
<BasicBlock
*> stack
;
362 for (Graph::EdgeIterator ei
= bb
->cfg
.incident(); !ei
.end(); ei
.next()) {
363 pb
= BasicBlock::get(ei
.getNode());
365 if (needNewElseBlock(bb
, pb
))
368 while (!stack
.empty()) {
370 pn
= new BasicBlock(func
);
373 pb
->cfg
.detach(&bb
->cfg
);
374 pb
->cfg
.attach(&pn
->cfg
, Graph::Edge::TREE
);
375 pn
->cfg
.attach(&bb
->cfg
, Graph::Edge::FORWARD
);
377 assert(pb
->getExit()->op
!= OP_CALL
);
378 if (pb
->getExit()->asFlow()->target
.bb
== bb
)
379 pb
->getExit()->asFlow()->target
.bb
= pn
;
382 // insert MOVs (phi->src(j) should stem from j-th in-BB)
384 for (Graph::EdgeIterator ei
= bb
->cfg
.incident(); !ei
.end(); ei
.next()) {
385 pb
= BasicBlock::get(ei
.getNode());
386 if (!pb
->isTerminated())
387 pb
->insertTail(new_FlowInstruction(func
, OP_BRA
, bb
));
389 for (phi
= bb
->getPhi(); phi
&& phi
->op
== OP_PHI
; phi
= phi
->next
) {
390 mov
= new_Instruction(func
, OP_MOV
, TYPE_U32
);
392 mov
->setSrc(0, phi
->getSrc(j
));
393 mov
->setDef(0, new_LValue(func
, phi
->getDef(0)->asLValue()));
394 phi
->setSrc(j
, mov
->getDef(0));
396 pb
->insertBefore(pb
->getExit(), mov
);
405 RegAlloc::ArgumentMovesPass::visit(BasicBlock
*bb
)
407 // Bind function call inputs/outputs to the same physical register
408 // the callee uses, inserting moves as appropriate for the case a
410 for (Instruction
*i
= bb
->getEntry(); i
; i
= i
->next
) {
411 FlowInstruction
*cal
= i
->asFlow();
412 // TODO: Handle indirect calls.
413 // Right now they should only be generated for builtins.
414 if (!cal
|| cal
->op
!= OP_CALL
|| cal
->builtin
|| cal
->indirect
)
416 RegisterSet
clobberSet(prog
->getTarget());
418 // Bind input values.
419 for (int s
= cal
->indirect
? 1 : 0; cal
->srcExists(s
); ++s
) {
420 const int t
= cal
->indirect
? (s
- 1) : s
;
421 LValue
*tmp
= new_LValue(func
, cal
->getSrc(s
)->asLValue());
422 tmp
->reg
.data
.id
= cal
->target
.fn
->ins
[t
].rep()->reg
.data
.id
;
425 new_Instruction(func
, OP_MOV
, typeOfSize(tmp
->reg
.size
));
427 mov
->setSrc(0, cal
->getSrc(s
));
430 bb
->insertBefore(cal
, mov
);
433 // Bind output values.
434 for (int d
= 0; cal
->defExists(d
); ++d
) {
435 LValue
*tmp
= new_LValue(func
, cal
->getDef(d
)->asLValue());
436 tmp
->reg
.data
.id
= cal
->target
.fn
->outs
[d
].rep()->reg
.data
.id
;
439 new_Instruction(func
, OP_MOV
, typeOfSize(tmp
->reg
.size
));
441 mov
->setDef(0, cal
->getDef(d
));
444 bb
->insertAfter(cal
, mov
);
445 clobberSet
.occupy(tmp
);
448 // Bind clobbered values.
449 for (std::deque
<Value
*>::iterator it
= cal
->target
.fn
->clobbers
.begin();
450 it
!= cal
->target
.fn
->clobbers
.end();
452 if (clobberSet
.testOccupy(*it
)) {
453 Value
*tmp
= new_LValue(func
, (*it
)->asLValue());
454 tmp
->reg
.data
.id
= (*it
)->reg
.data
.id
;
455 cal
->setDef(cal
->defCount(), tmp
);
460 // Update the clobber set of the function.
461 if (BasicBlock::get(func
->cfgExit
) == bb
) {
462 func
->buildDefSets();
463 for (unsigned int i
= 0; i
< bb
->defSet
.getSize(); ++i
)
464 if (bb
->defSet
.test(i
))
465 func
->clobbers
.push_back(func
->getLValue(i
));
471 // Build the set of live-in variables of bb.
473 RegAlloc::buildLiveSets(BasicBlock
*bb
)
475 Function
*f
= bb
->getFunction();
480 INFO_DBG(prog
->dbgFlags
, REG_ALLOC
, "buildLiveSets(BB:%i)\n", bb
->getId());
482 bb
->liveSet
.allocate(func
->allLValues
.getSize(), false);
485 for (Graph::EdgeIterator ei
= bb
->cfg
.outgoing(); !ei
.end(); ei
.next()) {
486 bn
= BasicBlock::get(ei
.getNode());
489 if (bn
->cfg
.visit(sequence
))
490 if (!buildLiveSets(bn
))
492 if (n
++ || bb
->liveSet
.marker
)
493 bb
->liveSet
|= bn
->liveSet
;
495 bb
->liveSet
= bn
->liveSet
;
497 if (!n
&& !bb
->liveSet
.marker
)
499 bb
->liveSet
.marker
= true;
501 if (prog
->dbgFlags
& NV50_IR_DEBUG_REG_ALLOC
) {
502 INFO("BB:%i live set of out blocks:\n", bb
->getId());
506 // if (!bb->getEntry())
509 if (bb
== BasicBlock::get(f
->cfgExit
)) {
510 for (std::deque
<ValueRef
>::iterator it
= f
->outs
.begin();
511 it
!= f
->outs
.end(); ++it
) {
512 assert(it
->get()->asLValue());
513 bb
->liveSet
.set(it
->get()->id
);
517 for (i
= bb
->getExit(); i
&& i
!= bb
->getEntry()->prev
; i
= i
->prev
) {
518 for (d
= 0; i
->defExists(d
); ++d
)
519 bb
->liveSet
.clr(i
->getDef(d
)->id
);
520 for (s
= 0; i
->srcExists(s
); ++s
)
521 if (i
->getSrc(s
)->asLValue())
522 bb
->liveSet
.set(i
->getSrc(s
)->id
);
524 for (i
= bb
->getPhi(); i
&& i
->op
== OP_PHI
; i
= i
->next
)
525 bb
->liveSet
.clr(i
->getDef(0)->id
);
527 if (prog
->dbgFlags
& NV50_IR_DEBUG_REG_ALLOC
) {
528 INFO("BB:%i live set after propagation:\n", bb
->getId());
536 RegAlloc::BuildIntervalsPass::collectLiveValues(BasicBlock
*bb
)
538 BasicBlock
*bbA
= NULL
, *bbB
= NULL
;
540 if (bb
->cfg
.outgoingCount()) {
541 // trickery to save a loop of OR'ing liveSets
542 // aliasing works fine with BitSet::setOr
543 for (Graph::EdgeIterator ei
= bb
->cfg
.outgoing(); !ei
.end(); ei
.next()) {
544 if (ei
.getType() == Graph::Edge::DUMMY
)
547 bb
->liveSet
.setOr(&bbA
->liveSet
, &bbB
->liveSet
);
552 bbB
= BasicBlock::get(ei
.getNode());
554 bb
->liveSet
.setOr(&bbB
->liveSet
, bbA
? &bbA
->liveSet
: NULL
);
556 if (bb
->cfg
.incidentCount()) {
562 RegAlloc::BuildIntervalsPass::visit(BasicBlock
*bb
)
564 collectLiveValues(bb
);
566 INFO_DBG(prog
->dbgFlags
, REG_ALLOC
, "BuildIntervals(BB:%i)\n", bb
->getId());
568 // go through out blocks and delete phi sources that do not originate from
569 // the current block from the live set
570 for (Graph::EdgeIterator ei
= bb
->cfg
.outgoing(); !ei
.end(); ei
.next()) {
571 BasicBlock
*out
= BasicBlock::get(ei
.getNode());
573 for (Instruction
*i
= out
->getPhi(); i
&& i
->op
== OP_PHI
; i
= i
->next
) {
574 bb
->liveSet
.clr(i
->getDef(0)->id
);
576 for (int s
= 0; i
->srcExists(s
); ++s
) {
577 assert(i
->src(s
).getInsn());
578 if (i
->getSrc(s
)->getUniqueInsn()->bb
== bb
) // XXX: reachableBy ?
579 bb
->liveSet
.set(i
->getSrc(s
)->id
);
581 bb
->liveSet
.clr(i
->getSrc(s
)->id
);
586 // remaining live-outs are live until end
588 for (unsigned int j
= 0; j
< bb
->liveSet
.getSize(); ++j
)
589 if (bb
->liveSet
.test(j
))
590 addLiveRange(func
->getLValue(j
), bb
, bb
->getExit()->serial
+ 1);
593 for (Instruction
*i
= bb
->getExit(); i
&& i
->op
!= OP_PHI
; i
= i
->prev
) {
594 for (int d
= 0; i
->defExists(d
); ++d
) {
595 bb
->liveSet
.clr(i
->getDef(d
)->id
);
596 if (i
->getDef(d
)->reg
.data
.id
>= 0) // add hazard for fixed regs
597 i
->getDef(d
)->livei
.extend(i
->serial
, i
->serial
);
600 for (int s
= 0; i
->srcExists(s
); ++s
) {
601 if (!i
->getSrc(s
)->asLValue())
603 if (!bb
->liveSet
.test(i
->getSrc(s
)->id
)) {
604 bb
->liveSet
.set(i
->getSrc(s
)->id
);
605 addLiveRange(i
->getSrc(s
), bb
, i
->serial
);
610 if (bb
== BasicBlock::get(func
->cfg
.getRoot())) {
611 for (std::deque
<ValueDef
>::iterator it
= func
->ins
.begin();
612 it
!= func
->ins
.end(); ++it
) {
613 if (it
->get()->reg
.data
.id
>= 0) // add hazard for fixed regs
614 it
->get()->livei
.extend(0, 1);
622 #define JOIN_MASK_PHI (1 << 0)
623 #define JOIN_MASK_UNION (1 << 1)
624 #define JOIN_MASK_MOV (1 << 2)
625 #define JOIN_MASK_TEX (1 << 3)
630 GCRA(Function
*, SpillCodeInserter
&);
633 bool allocateRegisters(ArrayList
& insns
);
635 void printNodeInfo() const;
638 class RIG_Node
: public Graph::Node
643 void init(const RegisterSet
&, LValue
*);
645 void addInterference(RIG_Node
*);
646 void addRegPreference(RIG_Node
*);
648 inline LValue
*getValue() const
650 return reinterpret_cast<LValue
*>(data
);
652 inline void setValue(LValue
*lval
) { data
= lval
; }
654 inline uint8_t getCompMask() const
656 return ((1 << colors
) - 1) << (reg
& 7);
659 static inline RIG_Node
*get(const Graph::EdgeIterator
& ei
)
661 return static_cast<RIG_Node
*>(ei
.getNode());
666 uint16_t degreeLimit
; // if deg < degLimit, node is trivially colourable
674 // list pointers for simplify() phase
678 // union of the live intervals of all coalesced values (we want to retain
679 // the separate intervals for testing interference of compound values)
682 std::list
<RIG_Node
*> prefRegs
;
686 inline RIG_Node
*getNode(const LValue
*v
) const { return &nodes
[v
->id
]; }
688 void buildRIG(ArrayList
&);
689 bool coalesce(ArrayList
&);
690 bool doCoalesce(ArrayList
&, unsigned int mask
);
691 void calculateSpillWeights();
693 bool selectRegisters();
694 void cleanup(const bool success
);
696 void simplifyEdge(RIG_Node
*, RIG_Node
*);
697 void simplifyNode(RIG_Node
*);
699 bool coalesceValues(Value
*, Value
*, bool force
);
700 void resolveSplitsAndMerges();
701 void makeCompound(Instruction
*, bool isSplit
);
703 inline void checkInterference(const RIG_Node
*, Graph::EdgeIterator
&);
705 inline void insertOrderedTail(std::list
<RIG_Node
*>&, RIG_Node
*);
706 void checkList(std::list
<RIG_Node
*>&);
709 std::stack
<uint32_t> stack
;
711 // list headers for simplify() phase
717 unsigned int nodeCount
;
722 static uint8_t relDegree
[17][17];
726 // need to fixup register id for participants of OP_MERGE/SPLIT
727 std::list
<Instruction
*> merges
;
728 std::list
<Instruction
*> splits
;
730 SpillCodeInserter
& spill
;
731 std::list
<ValuePair
> mustSpill
;
734 uint8_t GCRA::relDegree
[17][17];
736 GCRA::RIG_Node::RIG_Node() : Node(NULL
), next(this), prev(this)
742 GCRA::printNodeInfo() const
744 for (unsigned int i
= 0; i
< nodeCount
; ++i
) {
745 if (!nodes
[i
].colors
)
747 INFO("RIG_Node[%%%i]($[%u]%i): %u colors, weight %f, deg %u/%u\n X",
749 nodes
[i
].f
,nodes
[i
].reg
,nodes
[i
].colors
,
751 nodes
[i
].degree
, nodes
[i
].degreeLimit
);
753 for (Graph::EdgeIterator ei
= nodes
[i
].outgoing(); !ei
.end(); ei
.next())
754 INFO(" %%%i", RIG_Node::get(ei
)->getValue()->id
);
755 for (Graph::EdgeIterator ei
= nodes
[i
].incident(); !ei
.end(); ei
.next())
756 INFO(" %%%i", RIG_Node::get(ei
)->getValue()->id
);
762 GCRA::RIG_Node::init(const RegisterSet
& regs
, LValue
*lval
)
765 if (lval
->reg
.data
.id
>= 0)
766 lval
->noSpill
= lval
->fixedReg
= 1;
768 colors
= regs
.units(lval
->reg
.file
, lval
->reg
.size
);
771 if (lval
->reg
.data
.id
>= 0)
772 reg
= regs
.idToUnits(lval
);
774 weight
= std::numeric_limits
<float>::infinity();
776 degreeLimit
= regs
.getFileSize(f
, lval
->reg
.size
);
778 livei
.insert(lval
->livei
);
782 GCRA::coalesceValues(Value
*dst
, Value
*src
, bool force
)
784 LValue
*rep
= dst
->join
->asLValue();
785 LValue
*val
= src
->join
->asLValue();
787 if (!force
&& val
->reg
.data
.id
>= 0) {
788 rep
= src
->join
->asLValue();
789 val
= dst
->join
->asLValue();
791 RIG_Node
*nRep
= &nodes
[rep
->id
];
792 RIG_Node
*nVal
= &nodes
[val
->id
];
794 if (src
->reg
.file
!= dst
->reg
.file
) {
797 WARN("forced coalescing of values in different files !\n");
799 if (!force
&& dst
->reg
.size
!= src
->reg
.size
)
802 if ((rep
->reg
.data
.id
>= 0) && (rep
->reg
.data
.id
!= val
->reg
.data
.id
)) {
804 if (val
->reg
.data
.id
>= 0)
805 WARN("forced coalescing of values in different fixed regs !\n");
807 if (val
->reg
.data
.id
>= 0)
809 // make sure that there is no overlap with the fixed register of rep
810 for (ArrayList::Iterator it
= func
->allLValues
.iterator();
811 !it
.end(); it
.next()) {
812 Value
*reg
= reinterpret_cast<Value
*>(it
.get())->asLValue();
814 if (reg
->interfers(rep
) && reg
->livei
.overlaps(nVal
->livei
))
820 if (!force
&& nRep
->livei
.overlaps(nVal
->livei
))
823 INFO_DBG(prog
->dbgFlags
, REG_ALLOC
, "joining %%%i($%i) <- %%%i\n",
824 rep
->id
, rep
->reg
.data
.id
, val
->id
);
826 // set join pointer of all values joined with val
827 for (Value::DefIterator def
= val
->defs
.begin(); def
!= val
->defs
.end();
829 (*def
)->get()->join
= rep
;
830 assert(rep
->join
== rep
&& val
->join
== rep
);
832 // add val's definitions to rep and extend the live interval of its RIG node
833 rep
->defs
.insert(rep
->defs
.end(), val
->defs
.begin(), val
->defs
.end());
834 nRep
->livei
.unify(nVal
->livei
);
839 GCRA::coalesce(ArrayList
& insns
)
841 bool ret
= doCoalesce(insns
, JOIN_MASK_PHI
);
844 switch (func
->getProgram()->getTarget()->getChipset() & ~0xf) {
849 ret
= doCoalesce(insns
, JOIN_MASK_UNION
| JOIN_MASK_TEX
);
854 ret
= doCoalesce(insns
, JOIN_MASK_UNION
);
861 return doCoalesce(insns
, JOIN_MASK_MOV
);
864 static inline uint8_t makeCompMask(int compSize
, int base
, int size
)
866 uint8_t m
= ((1 << size
) - 1) << base
;
878 assert(compSize
<= 8);
883 // Used when coalescing moves. The non-compound value will become one, e.g.:
884 // mov b32 $r0 $r2 / merge b64 $r0d { $r0 $r1 }
885 // split b64 { $r0 $r1 } $r0d / mov b64 $r0d f64 $r2d
886 static inline void copyCompound(Value
*dst
, Value
*src
)
888 LValue
*ldst
= dst
->asLValue();
889 LValue
*lsrc
= src
->asLValue();
891 if (ldst
->compound
&& !lsrc
->compound
) {
897 ldst
->compound
= lsrc
->compound
;
898 ldst
->compMask
= lsrc
->compMask
;
902 GCRA::makeCompound(Instruction
*insn
, bool split
)
904 LValue
*rep
= (split
? insn
->getSrc(0) : insn
->getDef(0))->asLValue();
906 if (prog
->dbgFlags
& NV50_IR_DEBUG_REG_ALLOC
) {
907 INFO("makeCompound(split = %i): ", split
);
911 const unsigned int size
= getNode(rep
)->colors
;
912 unsigned int base
= 0;
915 rep
->compMask
= 0xff;
918 for (int c
= 0; split
? insn
->defExists(c
) : insn
->srcExists(c
); ++c
) {
919 LValue
*val
= (split
? insn
->getDef(c
) : insn
->getSrc(c
))->asLValue();
923 val
->compMask
= 0xff;
924 val
->compMask
&= makeCompMask(size
, base
, getNode(val
)->colors
);
925 assert(val
->compMask
);
927 INFO_DBG(prog
->dbgFlags
, REG_ALLOC
, "compound: %%%i:%02x <- %%%i:%02x\n",
928 rep
->id
, rep
->compMask
, val
->id
, val
->compMask
);
930 base
+= getNode(val
)->colors
;
932 assert(base
== size
);
936 GCRA::doCoalesce(ArrayList
& insns
, unsigned int mask
)
940 for (n
= 0; n
< insns
.getSize(); ++n
) {
942 Instruction
*insn
= reinterpret_cast<Instruction
*>(insns
.get(n
));
946 if (!(mask
& JOIN_MASK_PHI
))
948 for (c
= 0; insn
->srcExists(c
); ++c
)
949 if (!coalesceValues(insn
->getDef(0), insn
->getSrc(c
), false)) {
951 ERROR("failed to coalesce phi operands\n");
957 if (!(mask
& JOIN_MASK_UNION
))
959 for (c
= 0; insn
->srcExists(c
); ++c
)
960 coalesceValues(insn
->getDef(0), insn
->getSrc(c
), true);
961 if (insn
->op
== OP_MERGE
) {
962 merges
.push_back(insn
);
963 if (insn
->srcExists(1))
964 makeCompound(insn
, false);
968 if (!(mask
& JOIN_MASK_UNION
))
970 splits
.push_back(insn
);
971 for (c
= 0; insn
->defExists(c
); ++c
)
972 coalesceValues(insn
->getSrc(0), insn
->getDef(c
), true);
973 makeCompound(insn
, true);
976 if (!(mask
& JOIN_MASK_MOV
))
979 if (!insn
->getDef(0)->uses
.empty())
980 i
= insn
->getDef(0)->uses
.front()->getInsn();
981 // if this is a contraint-move there will only be a single use
982 if (i
&& i
->op
== OP_MERGE
) // do we really still need this ?
984 i
= insn
->getSrc(0)->getUniqueInsn();
985 if (i
&& !i
->constrainedDefs()) {
986 if (coalesceValues(insn
->getDef(0), insn
->getSrc(0), false))
987 copyCompound(insn
->getSrc(0), insn
->getDef(0));
998 if (!(mask
& JOIN_MASK_TEX
))
1000 for (c
= 0; insn
->srcExists(c
) && c
!= insn
->predSrc
; ++c
)
1001 coalesceValues(insn
->getDef(c
), insn
->getSrc(c
), true);
1011 GCRA::RIG_Node::addInterference(RIG_Node
*node
)
1013 this->degree
+= relDegree
[node
->colors
][colors
];
1014 node
->degree
+= relDegree
[colors
][node
->colors
];
1016 this->attach(node
, Graph::Edge::CROSS
);
1020 GCRA::RIG_Node::addRegPreference(RIG_Node
*node
)
1022 prefRegs
.push_back(node
);
1025 GCRA::GCRA(Function
*fn
, SpillCodeInserter
& spill
) :
1027 regs(fn
->getProgram()->getTarget()),
1030 prog
= func
->getProgram();
1032 // initialize relative degrees array - i takes away from j
1033 for (int i
= 1; i
<= 16; ++i
)
1034 for (int j
= 1; j
<= 16; ++j
)
1035 relDegree
[i
][j
] = j
* ((i
+ j
- 1) / j
);
1045 GCRA::checkList(std::list
<RIG_Node
*>& lst
)
1047 GCRA::RIG_Node
*prev
= NULL
;
1049 for (std::list
<RIG_Node
*>::iterator it
= lst
.begin();
1052 assert((*it
)->getValue()->join
== (*it
)->getValue());
1054 assert(prev
->livei
.begin() <= (*it
)->livei
.begin());
1060 GCRA::insertOrderedTail(std::list
<RIG_Node
*>& list
, RIG_Node
*node
)
1062 if (node
->livei
.isEmpty())
1064 // only the intervals of joined values don't necessarily arrive in order
1065 std::list
<RIG_Node
*>::iterator prev
, it
;
1066 for (it
= list
.end(); it
!= list
.begin(); it
= prev
) {
1069 if ((*prev
)->livei
.begin() <= node
->livei
.begin())
1072 list
.insert(it
, node
);
1076 GCRA::buildRIG(ArrayList
& insns
)
1078 std::list
<RIG_Node
*> values
, active
;
1080 for (std::deque
<ValueDef
>::iterator it
= func
->ins
.begin();
1081 it
!= func
->ins
.end(); ++it
)
1082 insertOrderedTail(values
, getNode(it
->get()->asLValue()));
1084 for (int i
= 0; i
< insns
.getSize(); ++i
) {
1085 Instruction
*insn
= reinterpret_cast<Instruction
*>(insns
.get(i
));
1086 for (int d
= 0; insn
->defExists(d
); ++d
)
1087 if (insn
->getDef(d
)->rep() == insn
->getDef(d
))
1088 insertOrderedTail(values
, getNode(insn
->getDef(d
)->asLValue()));
1092 while (!values
.empty()) {
1093 RIG_Node
*cur
= values
.front();
1095 for (std::list
<RIG_Node
*>::iterator it
= active
.begin();
1096 it
!= active
.end();) {
1097 RIG_Node
*node
= *it
;
1099 if (node
->livei
.end() <= cur
->livei
.begin()) {
1100 it
= active
.erase(it
);
1102 if (node
->f
== cur
->f
&& node
->livei
.overlaps(cur
->livei
))
1103 cur
->addInterference(node
);
1108 active
.push_back(cur
);
1113 GCRA::calculateSpillWeights()
1115 for (unsigned int i
= 0; i
< nodeCount
; ++i
) {
1116 RIG_Node
*const n
= &nodes
[i
];
1117 if (!nodes
[i
].colors
|| nodes
[i
].livei
.isEmpty())
1119 if (nodes
[i
].reg
>= 0) {
1121 regs
.occupy(n
->f
, n
->reg
, n
->colors
);
1124 LValue
*val
= nodes
[i
].getValue();
1126 if (!val
->noSpill
) {
1128 for (Value::DefIterator it
= val
->defs
.begin();
1129 it
!= val
->defs
.end();
1131 rc
+= (*it
)->get()->refCount();
1134 (float)rc
* (float)rc
/ (float)nodes
[i
].livei
.extent();
1137 if (nodes
[i
].degree
< nodes
[i
].degreeLimit
) {
1139 if (val
->reg
.size
> 4)
1141 DLLIST_ADDHEAD(&lo
[l
], &nodes
[i
]);
1143 DLLIST_ADDHEAD(&hi
, &nodes
[i
]);
1146 if (prog
->dbgFlags
& NV50_IR_DEBUG_REG_ALLOC
)
1151 GCRA::simplifyEdge(RIG_Node
*a
, RIG_Node
*b
)
1153 bool move
= b
->degree
>= b
->degreeLimit
;
1155 INFO_DBG(prog
->dbgFlags
, REG_ALLOC
,
1156 "edge: (%%%i, deg %u/%u) >-< (%%%i, deg %u/%u)\n",
1157 a
->getValue()->id
, a
->degree
, a
->degreeLimit
,
1158 b
->getValue()->id
, b
->degree
, b
->degreeLimit
);
1160 b
->degree
-= relDegree
[a
->colors
][b
->colors
];
1162 move
= move
&& b
->degree
< b
->degreeLimit
;
1163 if (move
&& !DLLIST_EMPTY(b
)) {
1164 int l
= (b
->getValue()->reg
.size
> 4) ? 1 : 0;
1166 DLLIST_ADDTAIL(&lo
[l
], b
);
1171 GCRA::simplifyNode(RIG_Node
*node
)
1173 for (Graph::EdgeIterator ei
= node
->outgoing(); !ei
.end(); ei
.next())
1174 simplifyEdge(node
, RIG_Node::get(ei
));
1176 for (Graph::EdgeIterator ei
= node
->incident(); !ei
.end(); ei
.next())
1177 simplifyEdge(node
, RIG_Node::get(ei
));
1180 stack
.push(node
->getValue()->id
);
1182 INFO_DBG(prog
->dbgFlags
, REG_ALLOC
, "SIMPLIFY: pushed %%%i%s\n",
1183 node
->getValue()->id
,
1184 (node
->degree
< node
->degreeLimit
) ? "" : "(spill)");
1191 if (!DLLIST_EMPTY(&lo
[0])) {
1193 simplifyNode(lo
[0].next
);
1194 } while (!DLLIST_EMPTY(&lo
[0]));
1196 if (!DLLIST_EMPTY(&lo
[1])) {
1197 simplifyNode(lo
[1].next
);
1199 if (!DLLIST_EMPTY(&hi
)) {
1200 RIG_Node
*best
= hi
.next
;
1201 float bestScore
= best
->weight
/ (float)best
->degree
;
1203 for (RIG_Node
*it
= best
->next
; it
!= &hi
; it
= it
->next
) {
1204 float score
= it
->weight
/ (float)it
->degree
;
1205 if (score
< bestScore
) {
1210 if (isinf(bestScore
)) {
1211 ERROR("no viable spill candidates left\n");
1222 GCRA::checkInterference(const RIG_Node
*node
, Graph::EdgeIterator
& ei
)
1224 const RIG_Node
*intf
= RIG_Node::get(ei
);
1228 const LValue
*vA
= node
->getValue();
1229 const LValue
*vB
= intf
->getValue();
1231 const uint8_t intfMask
= ((1 << intf
->colors
) - 1) << (intf
->reg
& 7);
1233 if (vA
->compound
| vB
->compound
) {
1234 // NOTE: this only works for >aligned< register tuples !
1235 for (Value::DefCIterator D
= vA
->defs
.begin(); D
!= vA
->defs
.end(); ++D
) {
1236 for (Value::DefCIterator d
= vB
->defs
.begin(); d
!= vB
->defs
.end(); ++d
) {
1237 const LValue
*vD
= (*D
)->get()->asLValue();
1238 const LValue
*vd
= (*d
)->get()->asLValue();
1240 if (!vD
->livei
.overlaps(vd
->livei
)) {
1241 INFO_DBG(prog
->dbgFlags
, REG_ALLOC
, "(%%%i) X (%%%i): no overlap\n",
1246 uint8_t mask
= vD
->compound
? vD
->compMask
: ~0;
1248 assert(vB
->compound
);
1249 mask
&= vd
->compMask
& vB
->compMask
;
1254 INFO_DBG(prog
->dbgFlags
, REG_ALLOC
,
1255 "(%%%i)%02x X (%%%i)%02x & %02x: $r%i.%02x\n",
1257 vD
->compound
? vD
->compMask
: 0xff,
1259 vd
->compound
? vd
->compMask
: intfMask
,
1260 vB
->compMask
, intf
->reg
& ~7, mask
);
1262 regs
.occupyMask(node
->f
, intf
->reg
& ~7, mask
);
1266 INFO_DBG(prog
->dbgFlags
, REG_ALLOC
,
1267 "(%%%i) X (%%%i): $r%i + %u\n",
1268 vA
->id
, vB
->id
, intf
->reg
, intf
->colors
);
1269 regs
.occupy(node
->f
, intf
->reg
, intf
->colors
);
1274 GCRA::selectRegisters()
1276 INFO_DBG(prog
->dbgFlags
, REG_ALLOC
, "\nSELECT phase\n");
1278 while (!stack
.empty()) {
1279 RIG_Node
*node
= &nodes
[stack
.top()];
1282 regs
.reset(node
->f
);
1284 INFO_DBG(prog
->dbgFlags
, REG_ALLOC
, "\nNODE[%%%i, %u colors]\n",
1285 node
->getValue()->id
, node
->colors
);
1287 for (Graph::EdgeIterator ei
= node
->outgoing(); !ei
.end(); ei
.next())
1288 checkInterference(node
, ei
);
1289 for (Graph::EdgeIterator ei
= node
->incident(); !ei
.end(); ei
.next())
1290 checkInterference(node
, ei
);
1292 if (!node
->prefRegs
.empty()) {
1293 for (std::list
<RIG_Node
*>::const_iterator it
= node
->prefRegs
.begin();
1294 it
!= node
->prefRegs
.end();
1296 if ((*it
)->reg
>= 0 &&
1297 regs
.testOccupy(node
->f
, (*it
)->reg
, node
->colors
)) {
1298 node
->reg
= (*it
)->reg
;
1305 LValue
*lval
= node
->getValue();
1306 if (prog
->dbgFlags
& NV50_IR_DEBUG_REG_ALLOC
)
1308 bool ret
= regs
.assign(node
->reg
, node
->f
, node
->colors
);
1310 INFO_DBG(prog
->dbgFlags
, REG_ALLOC
, "assigned reg %i\n", node
->reg
);
1311 lval
->compMask
= node
->getCompMask();
1313 INFO_DBG(prog
->dbgFlags
, REG_ALLOC
, "must spill: %%%i (size %u)\n",
1314 lval
->id
, lval
->reg
.size
);
1315 Symbol
*slot
= NULL
;
1316 if (lval
->reg
.file
== FILE_GPR
)
1317 slot
= spill
.assignSlot(node
->livei
, lval
->reg
.size
);
1318 mustSpill
.push_back(ValuePair(lval
, slot
));
1321 if (!mustSpill
.empty())
1323 for (unsigned int i
= 0; i
< nodeCount
; ++i
) {
1324 LValue
*lval
= nodes
[i
].getValue();
1325 if (nodes
[i
].reg
>= 0 && nodes
[i
].colors
> 0)
1327 regs
.unitsToId(nodes
[i
].f
, nodes
[i
].reg
, lval
->reg
.size
);
1333 GCRA::allocateRegisters(ArrayList
& insns
)
1337 INFO_DBG(prog
->dbgFlags
, REG_ALLOC
,
1338 "allocateRegisters to %u instructions\n", insns
.getSize());
1340 nodeCount
= func
->allLValues
.getSize();
1341 nodes
= new RIG_Node
[nodeCount
];
1344 for (unsigned int i
= 0; i
< nodeCount
; ++i
) {
1345 LValue
*lval
= reinterpret_cast<LValue
*>(func
->allLValues
.get(i
));
1347 nodes
[i
].init(regs
, lval
);
1348 RIG
.insert(&nodes
[i
]);
1352 // coalesce first, we use only 1 RIG node for a group of joined values
1353 ret
= coalesce(insns
);
1357 if (func
->getProgram()->dbgFlags
& NV50_IR_DEBUG_REG_ALLOC
)
1358 func
->printLiveIntervals();
1361 calculateSpillWeights();
1364 ret
= selectRegisters();
1366 INFO_DBG(prog
->dbgFlags
, REG_ALLOC
,
1367 "selectRegisters failed, inserting spill code ...\n");
1368 regs
.reset(FILE_GPR
, true);
1369 spill
.run(mustSpill
);
1370 if (prog
->dbgFlags
& NV50_IR_DEBUG_REG_ALLOC
)
1373 prog
->maxGPR
= std::max(prog
->maxGPR
, regs
.getMaxAssigned(FILE_GPR
));
1382 GCRA::cleanup(const bool success
)
1386 for (ArrayList::Iterator it
= func
->allLValues
.iterator();
1387 !it
.end(); it
.next()) {
1388 LValue
*lval
= reinterpret_cast<LValue
*>(it
.get());
1390 lval
->livei
.clear();
1395 if (lval
->join
== lval
)
1399 lval
->reg
.data
.id
= lval
->join
->reg
.data
.id
;
1401 for (Value::DefIterator d
= lval
->defs
.begin(); d
!= lval
->defs
.end();
1403 lval
->join
->defs
.remove(*d
);
1409 resolveSplitsAndMerges();
1410 splits
.clear(); // avoid duplicate entries on next coalesce pass
1418 SpillCodeInserter::assignSlot(const Interval
&livei
, const unsigned int size
)
1421 int32_t offsetBase
= stackSize
;
1423 std::list
<SpillSlot
>::iterator pos
= slots
.end(), it
= slots
.begin();
1425 if (offsetBase
% size
)
1426 offsetBase
+= size
- (offsetBase
% size
);
1430 for (offset
= offsetBase
; offset
< stackSize
; offset
+= size
) {
1431 const int32_t entryEnd
= offset
+ size
;
1432 while (it
!= slots
.end() && it
->offset
< offset
)
1434 if (it
== slots
.end()) // no slots left
1436 std::list
<SpillSlot
>::iterator bgn
= it
;
1438 while (it
!= slots
.end() && it
->offset
< entryEnd
) {
1440 if (it
->occup
.overlaps(livei
))
1444 if (it
== slots
.end() || it
->offset
>= entryEnd
) {
1446 for (; bgn
!= slots
.end() && bgn
->offset
< entryEnd
; ++bgn
) {
1447 bgn
->occup
.insert(livei
);
1448 if (bgn
->size() == size
)
1449 slot
.sym
= bgn
->sym
;
1455 stackSize
= offset
+ size
;
1456 slot
.offset
= offset
;
1457 slot
.sym
= new_Symbol(func
->getProgram(), FILE_MEMORY_LOCAL
);
1458 if (!func
->stackPtr
)
1459 offset
+= func
->tlsBase
;
1460 slot
.sym
->setAddress(NULL
, offset
);
1461 slot
.sym
->reg
.size
= size
;
1462 slots
.insert(pos
, slot
)->occup
.insert(livei
);
1468 SpillCodeInserter::spill(Instruction
*defi
, Value
*slot
, LValue
*lval
)
1470 const DataType ty
= typeOfSize(slot
->reg
.size
);
1473 if (slot
->reg
.file
== FILE_MEMORY_LOCAL
) {
1474 st
= new_Instruction(func
, OP_STORE
, ty
);
1475 st
->setSrc(0, slot
);
1476 st
->setSrc(1, lval
);
1479 st
= new_Instruction(func
, OP_CVT
, ty
);
1480 st
->setDef(0, slot
);
1481 st
->setSrc(0, lval
);
1483 defi
->bb
->insertAfter(defi
, st
);
1487 SpillCodeInserter::unspill(Instruction
*usei
, LValue
*lval
, Value
*slot
)
1489 const DataType ty
= typeOfSize(slot
->reg
.size
);
1491 lval
= cloneShallow(func
, lval
);
1494 if (slot
->reg
.file
== FILE_MEMORY_LOCAL
) {
1496 ld
= new_Instruction(func
, OP_LOAD
, ty
);
1498 ld
= new_Instruction(func
, OP_CVT
, ty
);
1500 ld
->setDef(0, lval
);
1501 ld
->setSrc(0, slot
);
1503 usei
->bb
->insertBefore(usei
, ld
);
1508 SpillCodeInserter::run(const std::list
<ValuePair
>& lst
)
1510 for (std::list
<ValuePair
>::const_iterator it
= lst
.begin(); it
!= lst
.end();
1512 LValue
*lval
= it
->first
->asLValue();
1513 Symbol
*mem
= it
->second
? it
->second
->asSym() : NULL
;
1515 for (Value::DefIterator d
= lval
->defs
.begin(); d
!= lval
->defs
.end();
1518 static_cast<Value
*>(mem
) : new_LValue(func
, FILE_GPR
);
1520 Instruction
*last
= NULL
;
1522 LValue
*dval
= (*d
)->get()->asLValue();
1523 Instruction
*defi
= (*d
)->getInsn();
1525 // handle uses first or they'll contain the spill stores
1526 while (!dval
->uses
.empty()) {
1527 ValueRef
*u
= dval
->uses
.front();
1528 Instruction
*usei
= u
->getInsn();
1530 if (usei
->op
== OP_PHI
) {
1531 tmp
= (slot
->reg
.file
== FILE_MEMORY_LOCAL
) ? NULL
: slot
;
1534 if (!last
|| usei
!= last
->next
) { // TODO: sort uses
1535 tmp
= unspill(usei
, dval
, slot
);
1542 if (defi
->op
== OP_PHI
) {
1543 d
= lval
->defs
.erase(d
);
1545 if (slot
->reg
.file
== FILE_MEMORY_LOCAL
)
1546 delete_Instruction(func
->getProgram(), defi
);
1548 defi
->setDef(0, slot
);
1550 spill(defi
, slot
, dval
);
1556 // TODO: We're not trying to reuse old slots in a potential next iteration.
1557 // We have to update the slots' livei intervals to be able to do that.
1558 stackBase
= stackSize
;
1566 for (IteratorRef it
= prog
->calls
.iteratorDFS(false);
1567 !it
->end(); it
->next()) {
1568 func
= Function::get(reinterpret_cast<Graph::Node
*>(it
->get()));
1570 func
->tlsBase
= prog
->tlsSize
;
1573 prog
->tlsSize
+= func
->tlsSize
;
1579 RegAlloc::execFunc()
1581 InsertConstraintsPass insertConstr
;
1582 PhiMovesPass insertPhiMoves
;
1583 ArgumentMovesPass insertArgMoves
;
1584 BuildIntervalsPass buildIntervals
;
1585 SpillCodeInserter
insertSpills(func
);
1587 GCRA
gcra(func
, insertSpills
);
1589 unsigned int i
, retries
;
1592 if (!func
->ins
.empty()) {
1593 // Insert a nop at the entry so inputs only used by the first instruction
1594 // don't count as having an empty live range.
1595 Instruction
*nop
= new_Instruction(func
, OP_NOP
, TYPE_NONE
);
1596 BasicBlock::get(func
->cfg
.getRoot())->insertHead(nop
);
1599 ret
= insertConstr
.exec(func
);
1603 ret
= insertPhiMoves
.run(func
);
1607 ret
= insertArgMoves
.run(func
);
1611 // TODO: need to fix up spill slot usage ranges to support > 1 retry
1612 for (retries
= 0; retries
< 3; ++retries
) {
1613 if (retries
&& (prog
->dbgFlags
& NV50_IR_DEBUG_REG_ALLOC
))
1614 INFO("Retry: %i\n", retries
);
1615 if (prog
->dbgFlags
& NV50_IR_DEBUG_REG_ALLOC
)
1618 // spilling to registers may add live ranges, need to rebuild everything
1620 for (sequence
= func
->cfg
.nextSequence(), i
= 0;
1621 ret
&& i
<= func
->loopNestingBound
;
1622 sequence
= func
->cfg
.nextSequence(), ++i
)
1623 ret
= buildLiveSets(BasicBlock::get(func
->cfg
.getRoot()));
1626 func
->orderInstructions(this->insns
);
1628 ret
= buildIntervals
.run(func
);
1631 ret
= gcra
.allocateRegisters(insns
);
1635 INFO_DBG(prog
->dbgFlags
, REG_ALLOC
, "RegAlloc done: %i\n", ret
);
1637 func
->tlsSize
= insertSpills
.getStackSize();
1642 // TODO: check if modifying Instruction::join here breaks anything
1644 GCRA::resolveSplitsAndMerges()
1646 for (std::list
<Instruction
*>::iterator it
= splits
.begin();
1649 Instruction
*split
= *it
;
1650 unsigned int reg
= regs
.idToBytes(split
->getSrc(0));
1651 for (int d
= 0; split
->defExists(d
); ++d
) {
1652 Value
*v
= split
->getDef(d
);
1653 v
->reg
.data
.id
= regs
.bytesToId(v
, reg
);
1660 for (std::list
<Instruction
*>::iterator it
= merges
.begin();
1663 Instruction
*merge
= *it
;
1664 unsigned int reg
= regs
.idToBytes(merge
->getDef(0));
1665 for (int s
= 0; merge
->srcExists(s
); ++s
) {
1666 Value
*v
= merge
->getSrc(s
);
1667 v
->reg
.data
.id
= regs
.bytesToId(v
, reg
);
1675 bool Program::registerAllocation()
1682 RegAlloc::InsertConstraintsPass::exec(Function
*ir
)
1686 bool ret
= run(ir
, true, true);
1688 ret
= insertConstraintMoves();
1692 // TODO: make part of texture insn
1694 RegAlloc::InsertConstraintsPass::textureMask(TexInstruction
*tex
)
1700 for (d
= 0, k
= 0, c
= 0; c
< 4; ++c
) {
1701 if (!(tex
->tex
.mask
& (1 << c
)))
1703 if (tex
->getDef(k
)->refCount()) {
1705 def
[d
++] = tex
->getDef(k
);
1709 tex
->tex
.mask
= mask
;
1711 for (c
= 0; c
< d
; ++c
)
1712 tex
->setDef(c
, def
[c
]);
1714 tex
->setDef(c
, NULL
);
1718 RegAlloc::InsertConstraintsPass::detectConflict(Instruction
*cst
, int s
)
1720 Value
*v
= cst
->getSrc(s
);
1722 // current register allocation can't handle it if a value participates in
1723 // multiple constraints
1724 for (Value::UseIterator it
= v
->uses
.begin(); it
!= v
->uses
.end(); ++it
) {
1725 if (cst
!= (*it
)->getInsn())
1729 // can start at s + 1 because detectConflict is called on all sources
1730 for (int c
= s
+ 1; cst
->srcExists(c
); ++c
)
1731 if (v
== cst
->getSrc(c
))
1734 Instruction
*defi
= v
->getInsn();
1736 return (!defi
|| defi
->constrainedDefs());
1740 RegAlloc::InsertConstraintsPass::addConstraint(Instruction
*i
, int s
, int n
)
1745 // first, look for an existing identical constraint op
1746 for (std::list
<Instruction
*>::iterator it
= constrList
.begin();
1747 it
!= constrList
.end();
1750 if (!i
->bb
->dominatedBy(cst
->bb
))
1752 for (d
= 0; d
< n
; ++d
)
1753 if (cst
->getSrc(d
) != i
->getSrc(d
+ s
))
1756 for (d
= 0; d
< n
; ++d
, ++s
)
1757 i
->setSrc(s
, cst
->getDef(d
));
1761 cst
= new_Instruction(func
, OP_CONSTRAINT
, i
->dType
);
1763 for (d
= 0; d
< n
; ++s
, ++d
) {
1764 cst
->setDef(d
, new_LValue(func
, FILE_GPR
));
1765 cst
->setSrc(d
, i
->getSrc(s
));
1766 i
->setSrc(s
, cst
->getDef(d
));
1768 i
->bb
->insertBefore(i
, cst
);
1770 constrList
.push_back(cst
);
1773 // Add a dummy use of the pointer source of >= 8 byte loads after the load
1774 // to prevent it from being assigned a register which overlapping the load's
1775 // destination, which would produce random corruptions.
1777 RegAlloc::InsertConstraintsPass::addHazard(Instruction
*i
, const ValueRef
*src
)
1779 Instruction
*hzd
= new_Instruction(func
, OP_NOP
, TYPE_NONE
);
1780 hzd
->setSrc(0, src
->get());
1781 i
->bb
->insertAfter(i
, hzd
);
1785 // b32 { %r0 %r1 %r2 %r3 } -> b128 %r0q
1787 RegAlloc::InsertConstraintsPass::condenseDefs(Instruction
*insn
)
1791 for (n
= 0; insn
->defExists(n
) && insn
->def(n
).getFile() == FILE_GPR
; ++n
)
1792 size
+= insn
->getDef(n
)->reg
.size
;
1795 LValue
*lval
= new_LValue(func
, FILE_GPR
);
1796 lval
->reg
.size
= size
;
1798 Instruction
*split
= new_Instruction(func
, OP_SPLIT
, typeOfSize(size
));
1799 split
->setSrc(0, lval
);
1800 for (int d
= 0; d
< n
; ++d
) {
1801 split
->setDef(d
, insn
->getDef(d
));
1802 insn
->setDef(d
, NULL
);
1804 insn
->setDef(0, lval
);
1806 for (int k
= 1, d
= n
; insn
->defExists(d
); ++d
, ++k
) {
1807 insn
->setDef(k
, insn
->getDef(d
));
1808 insn
->setDef(d
, NULL
);
1810 // carry over predicate if any (mainly for OP_UNION uses)
1811 split
->setPredicate(insn
->cc
, insn
->getPredicate());
1813 insn
->bb
->insertAfter(insn
, split
);
1814 constrList
.push_back(split
);
1817 RegAlloc::InsertConstraintsPass::condenseSrcs(Instruction
*insn
,
1818 const int a
, const int b
)
1823 for (int s
= a
; s
<= b
; ++s
)
1824 size
+= insn
->getSrc(s
)->reg
.size
;
1827 LValue
*lval
= new_LValue(func
, FILE_GPR
);
1828 lval
->reg
.size
= size
;
1831 insn
->takeExtraSources(0, save
);
1833 Instruction
*merge
= new_Instruction(func
, OP_MERGE
, typeOfSize(size
));
1834 merge
->setDef(0, lval
);
1835 for (int s
= a
, i
= 0; s
<= b
; ++s
, ++i
) {
1836 merge
->setSrc(i
, insn
->getSrc(s
));
1837 insn
->setSrc(s
, NULL
);
1839 insn
->setSrc(a
, lval
);
1841 for (int k
= a
+ 1, s
= b
+ 1; insn
->srcExists(s
); ++s
, ++k
) {
1842 insn
->setSrc(k
, insn
->getSrc(s
));
1843 insn
->setSrc(s
, NULL
);
1845 insn
->bb
->insertBefore(insn
, merge
);
1847 insn
->putExtraSources(0, save
);
1849 constrList
.push_back(merge
);
1853 RegAlloc::InsertConstraintsPass::texConstraintNVE0(TexInstruction
*tex
)
1855 if (isTextureOp(tex
->op
))
1859 if (tex
->op
== OP_SUSTB
|| tex
->op
== OP_SUSTP
) {
1860 condenseSrcs(tex
, 3, (3 + typeSizeof(tex
->dType
) / 4) - 1);
1862 if (isTextureOp(tex
->op
)) {
1863 int n
= tex
->srcCount(0xff, true);
1865 condenseSrcs(tex
, 0, 3);
1866 if (n
> 5) // NOTE: first call modified positions already
1867 condenseSrcs(tex
, 4 - (4 - 1), n
- 1 - (4 - 1));
1870 condenseSrcs(tex
, 0, n
- 1);
1876 RegAlloc::InsertConstraintsPass::texConstraintNVC0(TexInstruction
*tex
)
1882 if (tex
->op
== OP_TXQ
) {
1883 s
= tex
->srcCount(0xff);
1886 s
= tex
->tex
.target
.getArgCount();
1887 if (!tex
->tex
.target
.isArray() &&
1888 (tex
->tex
.rIndirectSrc
>= 0 || tex
->tex
.sIndirectSrc
>= 0))
1890 if (tex
->op
== OP_TXD
&& tex
->tex
.useOffsets
)
1892 n
= tex
->srcCount(0xff) - s
;
1897 condenseSrcs(tex
, 0, s
- 1);
1898 if (n
> 1) // NOTE: first call modified positions already
1899 condenseSrcs(tex
, 1, n
);
1905 RegAlloc::InsertConstraintsPass::texConstraintNV50(TexInstruction
*tex
)
1907 Value
*pred
= tex
->getPredicate();
1909 tex
->setPredicate(tex
->cc
, NULL
);
1913 assert(tex
->defExists(0) && tex
->srcExists(0));
1914 // make src and def count match
1916 for (c
= 0; tex
->srcExists(c
) || tex
->defExists(c
); ++c
) {
1917 if (!tex
->srcExists(c
))
1918 tex
->setSrc(c
, new_LValue(func
, tex
->getSrc(0)->asLValue()));
1919 if (!tex
->defExists(c
))
1920 tex
->setDef(c
, new_LValue(func
, tex
->getDef(0)->asLValue()));
1923 tex
->setPredicate(tex
->cc
, pred
);
1925 condenseSrcs(tex
, 0, c
- 1);
1928 // Insert constraint markers for instructions whose multiple sources must be
1929 // located in consecutive registers.
1931 RegAlloc::InsertConstraintsPass::visit(BasicBlock
*bb
)
1933 TexInstruction
*tex
;
1937 targ
= bb
->getProgram()->getTarget();
1939 for (Instruction
*i
= bb
->getEntry(); i
; i
= next
) {
1942 if ((tex
= i
->asTex())) {
1943 switch (targ
->getChipset() & ~0xf) {
1948 texConstraintNV50(tex
);
1952 texConstraintNVC0(tex
);
1955 case NVISA_GK110_CHIPSET
:
1956 texConstraintNVE0(tex
);
1962 if (i
->op
== OP_EXPORT
|| i
->op
== OP_STORE
) {
1963 for (size
= typeSizeof(i
->dType
), s
= 1; size
> 0; ++s
) {
1964 assert(i
->srcExists(s
));
1965 size
-= i
->getSrc(s
)->reg
.size
;
1967 condenseSrcs(i
, 1, s
- 1);
1969 if (i
->op
== OP_LOAD
|| i
->op
== OP_VFETCH
) {
1971 if (i
->src(0).isIndirect(0) && typeSizeof(i
->dType
) >= 8)
1972 addHazard(i
, i
->src(0).getIndirect(0));
1974 if (i
->op
== OP_UNION
||
1975 i
->op
== OP_MERGE
||
1976 i
->op
== OP_SPLIT
) {
1977 constrList
.push_back(i
);
1983 // Insert extra moves so that, if multiple register constraints on a value are
1984 // in conflict, these conflicts can be resolved.
1986 RegAlloc::InsertConstraintsPass::insertConstraintMoves()
1988 for (std::list
<Instruction
*>::iterator it
= constrList
.begin();
1989 it
!= constrList
.end();
1991 Instruction
*cst
= *it
;
1994 if (cst
->op
== OP_SPLIT
&& 0) {
1995 // spilling splits is annoying, just make sure they're separate
1996 for (int d
= 0; cst
->defExists(d
); ++d
) {
1997 if (!cst
->getDef(d
)->refCount())
1999 LValue
*lval
= new_LValue(func
, cst
->def(d
).getFile());
2000 const uint8_t size
= cst
->def(d
).getSize();
2001 lval
->reg
.size
= size
;
2003 mov
= new_Instruction(func
, OP_MOV
, typeOfSize(size
));
2004 mov
->setSrc(0, lval
);
2005 mov
->setDef(0, cst
->getDef(d
));
2006 cst
->setDef(d
, mov
->getSrc(0));
2007 cst
->bb
->insertAfter(cst
, mov
);
2009 cst
->getSrc(0)->asLValue()->noSpill
= 1;
2010 mov
->getSrc(0)->asLValue()->noSpill
= 1;
2013 if (cst
->op
== OP_MERGE
|| cst
->op
== OP_UNION
) {
2014 for (int s
= 0; cst
->srcExists(s
); ++s
) {
2015 const uint8_t size
= cst
->src(s
).getSize();
2017 if (!cst
->getSrc(s
)->defs
.size()) {
2018 mov
= new_Instruction(func
, OP_NOP
, typeOfSize(size
));
2019 mov
->setDef(0, cst
->getSrc(s
));
2020 cst
->bb
->insertBefore(cst
, mov
);
2023 assert(cst
->getSrc(s
)->defs
.size() == 1); // still SSA
2025 Instruction
*defi
= cst
->getSrc(s
)->defs
.front()->getInsn();
2026 // catch some cases where don't really need MOVs
2027 if (cst
->getSrc(s
)->refCount() == 1 && !defi
->constrainedDefs())
2030 LValue
*lval
= new_LValue(func
, cst
->src(s
).getFile());
2031 lval
->reg
.size
= size
;
2033 mov
= new_Instruction(func
, OP_MOV
, typeOfSize(size
));
2034 mov
->setDef(0, lval
);
2035 mov
->setSrc(0, cst
->getSrc(s
));
2036 cst
->setSrc(s
, mov
->getDef(0));
2037 cst
->bb
->insertBefore(cst
, mov
);
2039 cst
->getDef(0)->asLValue()->noSpill
= 1; // doesn't help
2041 if (cst
->op
== OP_UNION
)
2042 mov
->setPredicate(defi
->cc
, defi
->getPredicate());
2050 } // namespace nv50_ir