8c79c9a62609f47d22f7bcdd8a23345a44d41de6
[mesa.git] / src / gallium / drivers / nv50 / codegen / nv50_ir_ra.cpp
1 /*
2 * Copyright 2011 Christoph Bumiller
3 *
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:
10 *
11 * The above copyright notice and this permission notice shall be included in
12 * all copies or substantial portions of the Software.
13 *
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 BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
18 * WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF
19 * OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
20 * SOFTWARE.
21 */
22
23 #include "nv50_ir.h"
24 #include "nv50_ir_target.h"
25
26 #include <stack>
27 #include <limits>
28
29 namespace nv50_ir {
30
31 #define MAX_REGISTER_FILE_SIZE 256
32
33 class RegisterSet
34 {
35 public:
36 RegisterSet(const Target *);
37
38 void init(const Target *);
39 void reset(DataFile, bool resetMax = false);
40
41 void periodicMask(DataFile f, uint32_t lock, uint32_t unlock);
42 void intersect(DataFile f, const RegisterSet *);
43
44 bool assign(int32_t& reg, DataFile f, unsigned int size);
45 void release(DataFile f, int32_t reg, unsigned int size);
46 bool occupy(DataFile f, int32_t reg, unsigned int size, bool noTest = false);
47 bool occupy(const Value *);
48 void occupyMask(DataFile f, int32_t reg, uint8_t mask);
49
50 inline int getMaxAssigned(DataFile f) const { return fill[f]; }
51
52 inline unsigned int getFileSize(DataFile f, uint8_t regSize) const
53 {
54 if (restrictedGPR16Range && f == FILE_GPR && regSize == 2)
55 return (last[f] + 1) / 2;
56 return last[f] + 1;
57 }
58
59 inline unsigned int units(DataFile f, unsigned int size) const
60 {
61 return size >> unit[f];
62 }
63 // for regs of size >= 4, id is counted in 4-byte words (like nv50/c0 binary)
64 inline unsigned int idToBytes(const Value *v) const
65 {
66 return v->reg.data.id * MIN2(v->reg.size, 4);
67 }
68 inline unsigned int idToUnits(const Value *v) const
69 {
70 return units(v->reg.file, idToBytes(v));
71 }
72 inline int bytesToId(Value *v, unsigned int bytes) const
73 {
74 if (v->reg.size < 4)
75 return units(v->reg.file, bytes);
76 return bytes / 4;
77 }
78 inline int unitsToId(DataFile f, int u, uint8_t size) const
79 {
80 if (u < 0)
81 return -1;
82 return (size < 4) ? u : ((u << unit[f]) / 4);
83 }
84
85 void print() const;
86
87 private:
88 BitSet bits[LAST_REGISTER_FILE + 1];
89
90 int unit[LAST_REGISTER_FILE + 1]; // log2 of allocation granularity
91
92 int last[LAST_REGISTER_FILE + 1];
93 int fill[LAST_REGISTER_FILE + 1];
94
95 const bool restrictedGPR16Range;
96 };
97
98 void
99 RegisterSet::reset(DataFile f, bool resetMax)
100 {
101 bits[f].fill(0);
102 if (resetMax)
103 fill[f] = -1;
104 }
105
106 void
107 RegisterSet::init(const Target *targ)
108 {
109 for (unsigned int rf = 0; rf <= FILE_ADDRESS; ++rf) {
110 DataFile f = static_cast<DataFile>(rf);
111 last[rf] = targ->getFileSize(f) - 1;
112 unit[rf] = targ->getFileUnit(f);
113 fill[rf] = -1;
114 assert(last[rf] < MAX_REGISTER_FILE_SIZE);
115 bits[rf].allocate(last[rf] + 1, true);
116 }
117 }
118
119 RegisterSet::RegisterSet(const Target *targ)
120 : restrictedGPR16Range(targ->getChipset() < 0xc0)
121 {
122 init(targ);
123 for (unsigned int i = 0; i <= LAST_REGISTER_FILE; ++i)
124 reset(static_cast<DataFile>(i));
125 }
126
127 void
128 RegisterSet::periodicMask(DataFile f, uint32_t lock, uint32_t unlock)
129 {
130 bits[f].periodicMask32(lock, unlock);
131 }
132
133 void
134 RegisterSet::intersect(DataFile f, const RegisterSet *set)
135 {
136 bits[f] |= set->bits[f];
137 }
138
139 void
140 RegisterSet::print() const
141 {
142 INFO("GPR:");
143 bits[FILE_GPR].print();
144 INFO("\n");
145 }
146
147 bool
148 RegisterSet::assign(int32_t& reg, DataFile f, unsigned int size)
149 {
150 reg = bits[f].findFreeRange(size);
151 if (reg < 0)
152 return false;
153 fill[f] = MAX2(fill[f], (int32_t)(reg + size - 1));
154 return true;
155 }
156
157 bool
158 RegisterSet::occupy(const Value *v)
159 {
160 return occupy(v->reg.file, v->reg.data.id, v->reg.size >> unit[v->reg.file]);
161 }
162
163 void
164 RegisterSet::occupyMask(DataFile f, int32_t reg, uint8_t mask)
165 {
166 bits[f].setMask(reg & ~31, static_cast<uint32_t>(mask) << (reg % 32));
167 }
168
169 bool
170 RegisterSet::occupy(DataFile f, int32_t reg, unsigned int size, bool noTest)
171 {
172 if (!noTest && bits[f].testRange(reg, size))
173 return false;
174
175 bits[f].setRange(reg, size);
176
177 INFO_DBG(0, REG_ALLOC, "reg occupy: %u[%i] %u\n", f, reg, size);
178
179 fill[f] = MAX2(fill[f], (int32_t)(reg + size - 1));
180
181 return true;
182 }
183
184 void
185 RegisterSet::release(DataFile f, int32_t reg, unsigned int size)
186 {
187 bits[f].clrRange(reg, size);
188
189 INFO_DBG(0, REG_ALLOC, "reg release: %u[%i] %u\n", f, reg, size);
190 }
191
192 class RegAlloc
193 {
194 public:
195 RegAlloc(Program *program) : prog(program), sequence(0) { }
196
197 bool exec();
198 bool execFunc();
199
200 private:
201 class PhiMovesPass : public Pass {
202 private:
203 virtual bool visit(BasicBlock *);
204 inline bool needNewElseBlock(BasicBlock *b, BasicBlock *p);
205 };
206
207 class ArgumentMovesPass : public Pass {
208 private:
209 virtual bool visit(BasicBlock *);
210 };
211
212 class BuildIntervalsPass : public Pass {
213 private:
214 virtual bool visit(BasicBlock *);
215 void collectLiveValues(BasicBlock *);
216 void addLiveRange(Value *, const BasicBlock *, int end);
217 };
218
219 class InsertConstraintsPass : public Pass {
220 public:
221 bool exec(Function *func);
222 private:
223 virtual bool visit(BasicBlock *);
224
225 bool insertConstraintMoves();
226
227 void condenseDefs(Instruction *);
228 void condenseSrcs(Instruction *, const int first, const int last);
229
230 void addHazard(Instruction *i, const ValueRef *src);
231 void textureMask(TexInstruction *);
232 void addConstraint(Instruction *, int s, int n);
233 bool detectConflict(Instruction *, int s);
234
235 // target specific functions, TODO: put in subclass or Target
236 void texConstraintNV50(TexInstruction *);
237 void texConstraintNVC0(TexInstruction *);
238 void texConstraintNVE0(TexInstruction *);
239
240 std::list<Instruction *> constrList;
241
242 const Target *targ;
243 };
244
245 bool buildLiveSets(BasicBlock *);
246
247 private:
248 Program *prog;
249 Function *func;
250
251 // instructions in control flow / chronological order
252 ArrayList insns;
253
254 int sequence; // for manual passes through CFG
255 };
256
257 typedef std::pair<Value *, Value *> ValuePair;
258
259 class SpillCodeInserter
260 {
261 public:
262 SpillCodeInserter(Function *fn) : func(fn), stackSize(0), stackBase(0) { }
263
264 bool run(const std::list<ValuePair>&);
265
266 Symbol *assignSlot(const Interval&, const unsigned int size);
267 inline int32_t getStackSize() const { return stackSize; }
268
269 private:
270 Function *func;
271
272 struct SpillSlot
273 {
274 Interval occup;
275 std::list<Value *> residents; // needed to recalculate occup
276 Symbol *sym;
277 int32_t offset;
278 inline uint8_t size() const { return sym->reg.size; }
279 };
280 std::list<SpillSlot> slots;
281 int32_t stackSize;
282 int32_t stackBase;
283
284 LValue *unspill(Instruction *usei, LValue *, Value *slot);
285 void spill(Instruction *defi, Value *slot, LValue *);
286 };
287
288 void
289 RegAlloc::BuildIntervalsPass::addLiveRange(Value *val,
290 const BasicBlock *bb,
291 int end)
292 {
293 Instruction *insn = val->getUniqueInsn();
294
295 if (!insn)
296 insn = bb->getFirst();
297
298 assert(bb->getFirst()->serial <= bb->getExit()->serial);
299 assert(bb->getExit()->serial + 1 >= end);
300
301 int begin = insn->serial;
302 if (begin < bb->getEntry()->serial || begin > bb->getExit()->serial)
303 begin = bb->getEntry()->serial;
304
305 INFO_DBG(prog->dbgFlags, REG_ALLOC, "%%%i <- live range [%i(%i), %i)\n",
306 val->id, begin, insn->serial, end);
307
308 if (begin != end) // empty ranges are only added as hazards for fixed regs
309 val->livei.extend(begin, end);
310 }
311
312 bool
313 RegAlloc::PhiMovesPass::needNewElseBlock(BasicBlock *b, BasicBlock *p)
314 {
315 if (b->cfg.incidentCount() <= 1)
316 return false;
317
318 int n = 0;
319 for (Graph::EdgeIterator ei = p->cfg.outgoing(); !ei.end(); ei.next())
320 if (ei.getType() == Graph::Edge::TREE ||
321 ei.getType() == Graph::Edge::FORWARD)
322 ++n;
323 return (n == 2);
324 }
325
326 // For each operand of each PHI in b, generate a new value by inserting a MOV
327 // at the end of the block it is coming from and replace the operand with its
328 // result. This eliminates liveness conflicts and enables us to let values be
329 // copied to the right register if such a conflict exists nonetheless.
330 //
331 // These MOVs are also crucial in making sure the live intervals of phi srces
332 // are extended until the end of the loop, since they are not included in the
333 // live-in sets.
334 bool
335 RegAlloc::PhiMovesPass::visit(BasicBlock *bb)
336 {
337 Instruction *phi, *mov;
338 BasicBlock *pb, *pn;
339
340 std::stack<BasicBlock *> stack;
341
342 for (Graph::EdgeIterator ei = bb->cfg.incident(); !ei.end(); ei.next()) {
343 pb = BasicBlock::get(ei.getNode());
344 assert(pb);
345 if (needNewElseBlock(bb, pb))
346 stack.push(pb);
347 }
348 while (!stack.empty()) {
349 pb = stack.top();
350 pn = new BasicBlock(func);
351 stack.pop();
352
353 pb->cfg.detach(&bb->cfg);
354 pb->cfg.attach(&pn->cfg, Graph::Edge::TREE);
355 pn->cfg.attach(&bb->cfg, Graph::Edge::FORWARD);
356
357 assert(pb->getExit()->op != OP_CALL);
358 if (pb->getExit()->asFlow()->target.bb == bb)
359 pb->getExit()->asFlow()->target.bb = pn;
360 }
361
362 // insert MOVs (phi->src(j) should stem from j-th in-BB)
363 int j = 0;
364 for (Graph::EdgeIterator ei = bb->cfg.incident(); !ei.end(); ei.next()) {
365 pb = BasicBlock::get(ei.getNode());
366 if (!pb->isTerminated())
367 pb->insertTail(new_FlowInstruction(func, OP_BRA, bb));
368
369 for (phi = bb->getPhi(); phi && phi->op == OP_PHI; phi = phi->next) {
370 mov = new_Instruction(func, OP_MOV, TYPE_U32);
371
372 mov->setSrc(0, phi->getSrc(j));
373 mov->setDef(0, new_LValue(func, phi->getDef(0)->asLValue()));
374 phi->setSrc(j, mov->getDef(0));
375
376 pb->insertBefore(pb->getExit(), mov);
377 }
378 ++j;
379 }
380
381 return true;
382 }
383
384 bool
385 RegAlloc::ArgumentMovesPass::visit(BasicBlock *bb)
386 {
387 // Bind function call inputs/outputs to the same physical register
388 // the callee uses, inserting moves as appropriate for the case a
389 // conflict arises.
390 for (Instruction *i = bb->getEntry(); i; i = i->next) {
391 FlowInstruction *cal = i->asFlow();
392 if (!cal || cal->op != OP_CALL || cal->builtin)
393 continue;
394 RegisterSet clobberSet(prog->getTarget());
395
396 // Bind input values.
397 for (int s = 0; cal->srcExists(s); ++s) {
398 LValue *tmp = new_LValue(func, cal->getSrc(s)->asLValue());
399 tmp->reg.data.id = cal->target.fn->ins[s].rep()->reg.data.id;
400
401 Instruction *mov =
402 new_Instruction(func, OP_MOV, typeOfSize(tmp->reg.size));
403 mov->setDef(0, tmp);
404 mov->setSrc(0, cal->getSrc(s));
405 cal->setSrc(s, tmp);
406
407 bb->insertBefore(cal, mov);
408 }
409
410 // Bind output values.
411 for (int d = 0; cal->defExists(d); ++d) {
412 LValue *tmp = new_LValue(func, cal->getDef(d)->asLValue());
413 tmp->reg.data.id = cal->target.fn->outs[d].rep()->reg.data.id;
414
415 Instruction *mov =
416 new_Instruction(func, OP_MOV, typeOfSize(tmp->reg.size));
417 mov->setSrc(0, tmp);
418 mov->setDef(0, cal->getDef(d));
419 cal->setDef(d, tmp);
420
421 bb->insertAfter(cal, mov);
422 clobberSet.occupy(tmp);
423 }
424
425 // Bind clobbered values.
426 for (std::deque<Value *>::iterator it = cal->target.fn->clobbers.begin();
427 it != cal->target.fn->clobbers.end();
428 ++it) {
429 if (clobberSet.occupy(*it)) {
430 Value *tmp = new_LValue(func, (*it)->asLValue());
431 tmp->reg.data.id = (*it)->reg.data.id;
432 cal->setDef(cal->defCount(), tmp);
433 }
434 }
435 }
436
437 // Update the clobber set of the function.
438 if (BasicBlock::get(func->cfgExit) == bb) {
439 func->buildDefSets();
440 for (unsigned int i = 0; i < bb->defSet.getSize(); ++i)
441 if (bb->defSet.test(i))
442 func->clobbers.push_back(func->getLValue(i));
443 }
444
445 return true;
446 }
447
448 // Build the set of live-in variables of bb.
449 bool
450 RegAlloc::buildLiveSets(BasicBlock *bb)
451 {
452 Function *f = bb->getFunction();
453 BasicBlock *bn;
454 Instruction *i;
455 unsigned int s, d;
456
457 INFO_DBG(prog->dbgFlags, REG_ALLOC, "buildLiveSets(BB:%i)\n", bb->getId());
458
459 bb->liveSet.allocate(func->allLValues.getSize(), false);
460
461 int n = 0;
462 for (Graph::EdgeIterator ei = bb->cfg.outgoing(); !ei.end(); ei.next()) {
463 bn = BasicBlock::get(ei.getNode());
464 if (bn == bb)
465 continue;
466 if (bn->cfg.visit(sequence))
467 if (!buildLiveSets(bn))
468 return false;
469 if (n++ || bb->liveSet.marker)
470 bb->liveSet |= bn->liveSet;
471 else
472 bb->liveSet = bn->liveSet;
473 }
474 if (!n && !bb->liveSet.marker)
475 bb->liveSet.fill(0);
476 bb->liveSet.marker = true;
477
478 if (prog->dbgFlags & NV50_IR_DEBUG_REG_ALLOC) {
479 INFO("BB:%i live set of out blocks:\n", bb->getId());
480 bb->liveSet.print();
481 }
482
483 // if (!bb->getEntry())
484 // return true;
485
486 if (bb == BasicBlock::get(f->cfgExit)) {
487 for (std::deque<ValueRef>::iterator it = f->outs.begin();
488 it != f->outs.end(); ++it) {
489 assert(it->get()->asLValue());
490 bb->liveSet.set(it->get()->id);
491 }
492 }
493
494 for (i = bb->getExit(); i && i != bb->getEntry()->prev; i = i->prev) {
495 for (d = 0; i->defExists(d); ++d)
496 bb->liveSet.clr(i->getDef(d)->id);
497 for (s = 0; i->srcExists(s); ++s)
498 if (i->getSrc(s)->asLValue())
499 bb->liveSet.set(i->getSrc(s)->id);
500 }
501 for (i = bb->getPhi(); i && i->op == OP_PHI; i = i->next)
502 bb->liveSet.clr(i->getDef(0)->id);
503
504 if (prog->dbgFlags & NV50_IR_DEBUG_REG_ALLOC) {
505 INFO("BB:%i live set after propagation:\n", bb->getId());
506 bb->liveSet.print();
507 }
508
509 return true;
510 }
511
512 void
513 RegAlloc::BuildIntervalsPass::collectLiveValues(BasicBlock *bb)
514 {
515 BasicBlock *bbA = NULL, *bbB = NULL;
516
517 if (bb->cfg.outgoingCount()) {
518 // trickery to save a loop of OR'ing liveSets
519 // aliasing works fine with BitSet::setOr
520 for (Graph::EdgeIterator ei = bb->cfg.outgoing(); !ei.end(); ei.next()) {
521 if (ei.getType() == Graph::Edge::DUMMY)
522 continue;
523 if (bbA) {
524 bb->liveSet.setOr(&bbA->liveSet, &bbB->liveSet);
525 bbA = bb;
526 } else {
527 bbA = bbB;
528 }
529 bbB = BasicBlock::get(ei.getNode());
530 }
531 bb->liveSet.setOr(&bbB->liveSet, bbA ? &bbA->liveSet : NULL);
532 } else
533 if (bb->cfg.incidentCount()) {
534 bb->liveSet.fill(0);
535 }
536 }
537
538 bool
539 RegAlloc::BuildIntervalsPass::visit(BasicBlock *bb)
540 {
541 collectLiveValues(bb);
542
543 INFO_DBG(prog->dbgFlags, REG_ALLOC, "BuildIntervals(BB:%i)\n", bb->getId());
544
545 // go through out blocks and delete phi sources that do not originate from
546 // the current block from the live set
547 for (Graph::EdgeIterator ei = bb->cfg.outgoing(); !ei.end(); ei.next()) {
548 BasicBlock *out = BasicBlock::get(ei.getNode());
549
550 for (Instruction *i = out->getPhi(); i && i->op == OP_PHI; i = i->next) {
551 bb->liveSet.clr(i->getDef(0)->id);
552
553 for (int s = 0; i->srcExists(s); ++s) {
554 assert(i->src(s).getInsn());
555 if (i->getSrc(s)->getUniqueInsn()->bb == bb) // XXX: reachableBy ?
556 bb->liveSet.set(i->getSrc(s)->id);
557 else
558 bb->liveSet.clr(i->getSrc(s)->id);
559 }
560 }
561 }
562
563 // remaining live-outs are live until end
564 if (bb->getExit()) {
565 for (unsigned int j = 0; j < bb->liveSet.getSize(); ++j)
566 if (bb->liveSet.test(j))
567 addLiveRange(func->getLValue(j), bb, bb->getExit()->serial + 1);
568 }
569
570 for (Instruction *i = bb->getExit(); i && i->op != OP_PHI; i = i->prev) {
571 for (int d = 0; i->defExists(d); ++d) {
572 bb->liveSet.clr(i->getDef(d)->id);
573 if (i->getDef(d)->reg.data.id >= 0) // add hazard for fixed regs
574 i->getDef(d)->livei.extend(i->serial, i->serial);
575 }
576
577 for (int s = 0; i->srcExists(s); ++s) {
578 if (!i->getSrc(s)->asLValue())
579 continue;
580 if (!bb->liveSet.test(i->getSrc(s)->id)) {
581 bb->liveSet.set(i->getSrc(s)->id);
582 addLiveRange(i->getSrc(s), bb, i->serial);
583 }
584 }
585 }
586
587 if (bb == BasicBlock::get(func->cfg.getRoot())) {
588 for (std::deque<ValueDef>::iterator it = func->ins.begin();
589 it != func->ins.end(); ++it) {
590 if (it->get()->reg.data.id >= 0) // add hazard for fixed regs
591 it->get()->livei.extend(0, 1);
592 }
593 }
594
595 return true;
596 }
597
598
599 #define JOIN_MASK_PHI (1 << 0)
600 #define JOIN_MASK_UNION (1 << 1)
601 #define JOIN_MASK_MOV (1 << 2)
602 #define JOIN_MASK_TEX (1 << 3)
603
604 class GCRA
605 {
606 public:
607 GCRA(Function *, SpillCodeInserter&);
608 ~GCRA();
609
610 bool allocateRegisters(ArrayList& insns);
611
612 void printNodeInfo() const;
613
614 private:
615 class RIG_Node : public Graph::Node
616 {
617 public:
618 RIG_Node();
619
620 void init(const RegisterSet&, LValue *);
621
622 void addInterference(RIG_Node *);
623 void addRegPreference(RIG_Node *);
624
625 inline LValue *getValue() const
626 {
627 return reinterpret_cast<LValue *>(data);
628 }
629 inline void setValue(LValue *lval) { data = lval; }
630
631 inline uint8_t getCompMask() const
632 {
633 return ((1 << colors) - 1) << (reg & 7);
634 }
635
636 static inline RIG_Node *get(const Graph::EdgeIterator& ei)
637 {
638 return static_cast<RIG_Node *>(ei.getNode());
639 }
640
641 public:
642 uint32_t degree;
643 uint16_t degreeLimit; // if deg < degLimit, node is trivially colourable
644 uint16_t colors;
645
646 DataFile f;
647 int32_t reg;
648
649 float weight;
650
651 // list pointers for simplify() phase
652 RIG_Node *next;
653 RIG_Node *prev;
654
655 // union of the live intervals of all coalesced values (we want to retain
656 // the separate intervals for testing interference of compound values)
657 Interval livei;
658
659 std::list<RIG_Node *> prefRegs;
660 };
661
662 private:
663 inline RIG_Node *getNode(const LValue *v) const { return &nodes[v->id]; }
664
665 void buildRIG(ArrayList&);
666 bool coalesce(ArrayList&);
667 bool doCoalesce(ArrayList&, unsigned int mask);
668 void calculateSpillWeights();
669 void simplify();
670 bool selectRegisters();
671 void cleanup(const bool success);
672
673 void simplifyEdge(RIG_Node *, RIG_Node *);
674 void simplifyNode(RIG_Node *);
675
676 bool coalesceValues(Value *, Value *, bool force);
677 void resolveSplitsAndMerges();
678 void makeCompound(Instruction *, bool isSplit);
679
680 inline void checkInterference(const RIG_Node *, Graph::EdgeIterator&);
681
682 inline void insertOrderedTail(std::list<RIG_Node *>&, RIG_Node *);
683 void checkList(std::list<RIG_Node *>&);
684
685 private:
686 std::stack<uint32_t> stack;
687
688 // list headers for simplify() phase
689 RIG_Node lo[2];
690 RIG_Node hi;
691
692 Graph RIG;
693 RIG_Node *nodes;
694 unsigned int nodeCount;
695
696 Function *func;
697 Program *prog;
698
699 static uint8_t relDegree[17][17];
700
701 RegisterSet regs;
702
703 // need to fixup register id for participants of OP_MERGE/SPLIT
704 std::list<Instruction *> merges;
705 std::list<Instruction *> splits;
706
707 SpillCodeInserter& spill;
708 std::list<ValuePair> mustSpill;
709 };
710
711 uint8_t GCRA::relDegree[17][17];
712
713 GCRA::RIG_Node::RIG_Node() : Node(NULL), next(this), prev(this)
714 {
715 colors = 0;
716 }
717
718 void
719 GCRA::printNodeInfo() const
720 {
721 for (unsigned int i = 0; i < nodeCount; ++i) {
722 if (!nodes[i].colors)
723 continue;
724 INFO("RIG_Node[%%%i]($[%u]%i): %u colors, weight %f, deg %u/%u\n X",
725 i,
726 nodes[i].f,nodes[i].reg,nodes[i].colors,
727 nodes[i].weight,
728 nodes[i].degree, nodes[i].degreeLimit);
729
730 for (Graph::EdgeIterator ei = nodes[i].outgoing(); !ei.end(); ei.next())
731 INFO(" %%%i", RIG_Node::get(ei)->getValue()->id);
732 for (Graph::EdgeIterator ei = nodes[i].incident(); !ei.end(); ei.next())
733 INFO(" %%%i", RIG_Node::get(ei)->getValue()->id);
734 INFO("\n");
735 }
736 }
737
738 void
739 GCRA::RIG_Node::init(const RegisterSet& regs, LValue *lval)
740 {
741 setValue(lval);
742 if (lval->reg.data.id >= 0)
743 lval->noSpill = lval->fixedReg = 1;
744
745 colors = regs.units(lval->reg.file, lval->reg.size);
746 f = lval->reg.file;
747 reg = -1;
748 if (lval->reg.data.id >= 0)
749 reg = regs.idToUnits(lval);
750
751 weight = std::numeric_limits<float>::infinity();
752 degree = 0;
753 degreeLimit = regs.getFileSize(f, lval->reg.size);
754
755 livei.insert(lval->livei);
756 }
757
758 bool
759 GCRA::coalesceValues(Value *dst, Value *src, bool force)
760 {
761 LValue *rep = dst->join->asLValue();
762 LValue *val = src->join->asLValue();
763
764 if (!force && val->reg.data.id >= 0) {
765 rep = src->join->asLValue();
766 val = dst->join->asLValue();
767 }
768 RIG_Node *nRep = &nodes[rep->id];
769 RIG_Node *nVal = &nodes[val->id];
770
771 if (src->reg.file != dst->reg.file) {
772 if (!force)
773 return false;
774 WARN("forced coalescing of values in different files !\n");
775 }
776 if (!force && dst->reg.size != src->reg.size)
777 return false;
778
779 if ((rep->reg.data.id >= 0) && (rep->reg.data.id != val->reg.data.id)) {
780 if (force) {
781 if (val->reg.data.id >= 0)
782 WARN("forced coalescing of values in different fixed regs !\n");
783 } else {
784 if (val->reg.data.id >= 0)
785 return false;
786 // make sure that there is no overlap with the fixed register of rep
787 for (ArrayList::Iterator it = func->allLValues.iterator();
788 !it.end(); it.next()) {
789 Value *reg = reinterpret_cast<Value *>(it.get())->asLValue();
790 assert(reg);
791 if (reg->interfers(rep) && reg->livei.overlaps(nVal->livei))
792 return false;
793 }
794 }
795 }
796
797 if (!force && nRep->livei.overlaps(nVal->livei))
798 return false;
799
800 INFO_DBG(prog->dbgFlags, REG_ALLOC, "joining %%%i($%i) <- %%%i\n",
801 rep->id, rep->reg.data.id, val->id);
802
803 // set join pointer of all values joined with val
804 for (Value::DefIterator def = val->defs.begin(); def != val->defs.end();
805 ++def)
806 (*def)->get()->join = rep;
807 assert(rep->join == rep && val->join == rep);
808
809 // add val's definitions to rep and extend the live interval of its RIG node
810 rep->defs.insert(rep->defs.end(), val->defs.begin(), val->defs.end());
811 nRep->livei.unify(nVal->livei);
812 return true;
813 }
814
815 bool
816 GCRA::coalesce(ArrayList& insns)
817 {
818 bool ret = doCoalesce(insns, JOIN_MASK_PHI);
819 if (!ret)
820 return false;
821 switch (func->getProgram()->getTarget()->getChipset() & ~0xf) {
822 case 0x50:
823 case 0x80:
824 case 0x90:
825 case 0xa0:
826 ret = doCoalesce(insns, JOIN_MASK_UNION | JOIN_MASK_TEX);
827 break;
828 case 0xc0:
829 case 0xd0:
830 case 0xe0:
831 ret = doCoalesce(insns, JOIN_MASK_UNION);
832 break;
833 default:
834 break;
835 }
836 if (!ret)
837 return false;
838 return doCoalesce(insns, JOIN_MASK_MOV);
839 }
840
841 static inline uint8_t makeCompMask(int compSize, int base, int size)
842 {
843 uint8_t m = ((1 << size) - 1) << base;
844
845 switch (compSize) {
846 case 1:
847 return 0xff;
848 case 2:
849 m |= (m << 2);
850 return (m << 4) | m;
851 case 3:
852 case 4:
853 return (m << 4) | m;
854 default:
855 assert(compSize <= 8);
856 return m;
857 }
858 }
859
860 static inline void copyCompound(Value *dst, Value *src)
861 {
862 LValue *ldst = dst->asLValue();
863 LValue *lsrc = src->asLValue();
864
865 ldst->compound = lsrc->compound;
866 ldst->compMask = lsrc->compMask;
867 }
868
869 void
870 GCRA::makeCompound(Instruction *insn, bool split)
871 {
872 LValue *rep = (split ? insn->getSrc(0) : insn->getDef(0))->asLValue();
873
874 if (prog->dbgFlags & NV50_IR_DEBUG_REG_ALLOC) {
875 INFO("makeCompound(split = %i): ", split);
876 insn->print();
877 }
878
879 const unsigned int size = getNode(rep)->colors;
880 unsigned int base = 0;
881
882 if (!rep->compound)
883 rep->compMask = 0xff;
884 rep->compound = 1;
885
886 for (int c = 0; split ? insn->defExists(c) : insn->srcExists(c); ++c) {
887 LValue *val = (split ? insn->getDef(c) : insn->getSrc(c))->asLValue();
888
889 val->compound = 1;
890 if (!val->compMask)
891 val->compMask = 0xff;
892 val->compMask &= makeCompMask(size, base, getNode(val)->colors);
893 assert(val->compMask);
894
895 INFO_DBG(prog->dbgFlags, REG_ALLOC, "compound: %%%i:%02x <- %%%i:%02x\n",
896 rep->id, rep->compMask, val->id, val->compMask);
897
898 base += getNode(val)->colors;
899 }
900 assert(base == size);
901 }
902
903 bool
904 GCRA::doCoalesce(ArrayList& insns, unsigned int mask)
905 {
906 int c, n;
907
908 for (n = 0; n < insns.getSize(); ++n) {
909 Instruction *i;
910 Instruction *insn = reinterpret_cast<Instruction *>(insns.get(n));
911
912 switch (insn->op) {
913 case OP_PHI:
914 if (!(mask & JOIN_MASK_PHI))
915 break;
916 for (c = 0; insn->srcExists(c); ++c)
917 if (!coalesceValues(insn->getDef(0), insn->getSrc(c), false)) {
918 // this is bad
919 ERROR("failed to coalesce phi operands\n");
920 return false;
921 }
922 break;
923 case OP_UNION:
924 case OP_MERGE:
925 if (!(mask & JOIN_MASK_UNION))
926 break;
927 for (c = 0; insn->srcExists(c); ++c)
928 coalesceValues(insn->getDef(0), insn->getSrc(c), true);
929 if (insn->op == OP_MERGE) {
930 merges.push_back(insn);
931 if (insn->srcExists(1))
932 makeCompound(insn, false);
933 }
934 break;
935 case OP_SPLIT:
936 if (!(mask & JOIN_MASK_UNION))
937 break;
938 splits.push_back(insn);
939 for (c = 0; insn->defExists(c); ++c)
940 coalesceValues(insn->getSrc(0), insn->getDef(c), true);
941 makeCompound(insn, true);
942 break;
943 case OP_MOV:
944 if (!(mask & JOIN_MASK_MOV))
945 break;
946 i = NULL;
947 if (!insn->getDef(0)->uses.empty())
948 i = insn->getDef(0)->uses.front()->getInsn();
949 // if this is a contraint-move there will only be a single use
950 if (i && i->op == OP_MERGE) // do we really still need this ?
951 break;
952 i = insn->getSrc(0)->getUniqueInsn();
953 if (i && !i->constrainedDefs()) {
954 if (coalesceValues(insn->getDef(0), insn->getSrc(0), false))
955 copyCompound(insn->getSrc(0), insn->getDef(0));
956 }
957 break;
958 case OP_TEX:
959 case OP_TXB:
960 case OP_TXL:
961 case OP_TXF:
962 case OP_TXQ:
963 case OP_TXD:
964 case OP_TXG:
965 case OP_TEXCSAA:
966 if (!(mask & JOIN_MASK_TEX))
967 break;
968 for (c = 0; insn->srcExists(c) && c != insn->predSrc; ++c)
969 coalesceValues(insn->getDef(c), insn->getSrc(c), true);
970 break;
971 default:
972 break;
973 }
974 }
975 return true;
976 }
977
978 void
979 GCRA::RIG_Node::addInterference(RIG_Node *node)
980 {
981 this->degree += relDegree[node->colors][colors];
982 node->degree += relDegree[colors][node->colors];
983
984 this->attach(node, Graph::Edge::CROSS);
985 }
986
987 void
988 GCRA::RIG_Node::addRegPreference(RIG_Node *node)
989 {
990 prefRegs.push_back(node);
991 }
992
993 GCRA::GCRA(Function *fn, SpillCodeInserter& spill) :
994 func(fn),
995 regs(fn->getProgram()->getTarget()),
996 spill(spill)
997 {
998 prog = func->getProgram();
999
1000 // initialize relative degrees array - i takes away from j
1001 for (int i = 1; i <= 16; ++i)
1002 for (int j = 1; j <= 16; ++j)
1003 relDegree[i][j] = j * ((i + j - 1) / j);
1004 }
1005
1006 GCRA::~GCRA()
1007 {
1008 if (nodes)
1009 delete[] nodes;
1010 }
1011
1012 void
1013 GCRA::checkList(std::list<RIG_Node *>& lst)
1014 {
1015 GCRA::RIG_Node *prev = NULL;
1016
1017 for (std::list<RIG_Node *>::iterator it = lst.begin();
1018 it != lst.end();
1019 ++it) {
1020 assert((*it)->getValue()->join == (*it)->getValue());
1021 if (prev)
1022 assert(prev->livei.begin() <= (*it)->livei.begin());
1023 prev = *it;
1024 }
1025 }
1026
1027 void
1028 GCRA::insertOrderedTail(std::list<RIG_Node *>& list, RIG_Node *node)
1029 {
1030 if (node->livei.isEmpty())
1031 return;
1032 // only the intervals of joined values don't necessarily arrive in order
1033 std::list<RIG_Node *>::iterator prev, it;
1034 for (it = list.end(); it != list.begin(); it = prev) {
1035 prev = it;
1036 --prev;
1037 if ((*prev)->livei.begin() <= node->livei.begin())
1038 break;
1039 }
1040 list.insert(it, node);
1041 }
1042
1043 void
1044 GCRA::buildRIG(ArrayList& insns)
1045 {
1046 std::list<RIG_Node *> values, active;
1047
1048 for (std::deque<ValueDef>::iterator it = func->ins.begin();
1049 it != func->ins.end(); ++it)
1050 insertOrderedTail(values, getNode(it->get()->asLValue()));
1051
1052 for (int i = 0; i < insns.getSize(); ++i) {
1053 Instruction *insn = reinterpret_cast<Instruction *>(insns.get(i));
1054 for (int d = 0; insn->defExists(d); ++d)
1055 if (insn->getDef(d)->rep() == insn->getDef(d))
1056 insertOrderedTail(values, getNode(insn->getDef(d)->asLValue()));
1057 }
1058 checkList(values);
1059
1060 while (!values.empty()) {
1061 RIG_Node *cur = values.front();
1062
1063 for (std::list<RIG_Node *>::iterator it = active.begin();
1064 it != active.end();
1065 ++it) {
1066 RIG_Node *node = *it;
1067
1068 if (node->livei.end() <= cur->livei.begin()) {
1069 it = active.erase(it);
1070 --it;
1071 } else
1072 if (node->f == cur->f && node->livei.overlaps(cur->livei)) {
1073 cur->addInterference(node);
1074 }
1075 }
1076 values.pop_front();
1077 active.push_back(cur);
1078 }
1079 }
1080
1081 void
1082 GCRA::calculateSpillWeights()
1083 {
1084 for (unsigned int i = 0; i < nodeCount; ++i) {
1085 RIG_Node *const n = &nodes[i];
1086 if (!nodes[i].colors || nodes[i].livei.isEmpty())
1087 continue;
1088 if (nodes[i].reg >= 0) {
1089 // update max reg
1090 regs.occupy(n->f, n->reg, n->colors);
1091 continue;
1092 }
1093 LValue *val = nodes[i].getValue();
1094
1095 if (!val->noSpill) {
1096 int rc = 0;
1097 for (Value::DefIterator it = val->defs.begin();
1098 it != val->defs.end();
1099 ++it)
1100 rc += (*it)->get()->refCount();
1101
1102 nodes[i].weight =
1103 (float)rc * (float)rc / (float)nodes[i].livei.extent();
1104 }
1105
1106 if (nodes[i].degree < nodes[i].degreeLimit) {
1107 int l = 0;
1108 if (val->reg.size > 4)
1109 l = 1;
1110 DLLIST_ADDHEAD(&lo[l], &nodes[i]);
1111 } else {
1112 DLLIST_ADDHEAD(&hi, &nodes[i]);
1113 }
1114 }
1115 if (prog->dbgFlags & NV50_IR_DEBUG_REG_ALLOC)
1116 printNodeInfo();
1117 }
1118
1119 void
1120 GCRA::simplifyEdge(RIG_Node *a, RIG_Node *b)
1121 {
1122 bool move = b->degree >= b->degreeLimit;
1123
1124 INFO_DBG(prog->dbgFlags, REG_ALLOC,
1125 "edge: (%%%i, deg %u/%u) >-< (%%%i, deg %u/%u)\n",
1126 a->getValue()->id, a->degree, a->degreeLimit,
1127 b->getValue()->id, b->degree, b->degreeLimit);
1128
1129 b->degree -= relDegree[a->colors][b->colors];
1130
1131 move = move && b->degree < b->degreeLimit;
1132 if (move && !DLLIST_EMPTY(b)) {
1133 int l = (b->getValue()->reg.size > 4) ? 1 : 0;
1134 DLLIST_DEL(b);
1135 DLLIST_ADDTAIL(&lo[l], b);
1136 }
1137 }
1138
1139 void
1140 GCRA::simplifyNode(RIG_Node *node)
1141 {
1142 for (Graph::EdgeIterator ei = node->outgoing(); !ei.end(); ei.next())
1143 simplifyEdge(node, RIG_Node::get(ei));
1144
1145 for (Graph::EdgeIterator ei = node->incident(); !ei.end(); ei.next())
1146 simplifyEdge(node, RIG_Node::get(ei));
1147
1148 DLLIST_DEL(node);
1149 stack.push(node->getValue()->id);
1150
1151 INFO_DBG(prog->dbgFlags, REG_ALLOC, "SIMPLIFY: pushed %%%i%s\n",
1152 node->getValue()->id,
1153 (node->degree < node->degreeLimit) ? "" : "(spill)");
1154 }
1155
1156 void
1157 GCRA::simplify()
1158 {
1159 for (;;) {
1160 if (!DLLIST_EMPTY(&lo[0])) {
1161 do {
1162 simplifyNode(lo[0].next);
1163 } while (!DLLIST_EMPTY(&lo[0]));
1164 } else
1165 if (!DLLIST_EMPTY(&lo[1])) {
1166 simplifyNode(lo[1].next);
1167 } else
1168 if (!DLLIST_EMPTY(&hi)) {
1169 RIG_Node *best = hi.next;
1170 float bestScore = best->weight / (float)best->degree;
1171 // spill candidate
1172 for (RIG_Node *it = best->next; it != &hi; it = it->next) {
1173 float score = it->weight / (float)it->degree;
1174 if (score < bestScore) {
1175 best = it;
1176 bestScore = score;
1177 }
1178 }
1179 if (isinf(bestScore)) {
1180 ERROR("no viable spill candidates left\n");
1181 break;
1182 }
1183 simplifyNode(best);
1184 } else {
1185 break;
1186 }
1187 }
1188 }
1189
1190 void
1191 GCRA::checkInterference(const RIG_Node *node, Graph::EdgeIterator& ei)
1192 {
1193 const RIG_Node *intf = RIG_Node::get(ei);
1194
1195 if (intf->reg < 0)
1196 return;
1197 const LValue *vA = node->getValue();
1198 const LValue *vB = intf->getValue();
1199
1200 const uint8_t intfMask = ((1 << intf->colors) - 1) << (intf->reg & 7);
1201
1202 if (vA->compound | vB->compound) {
1203 // NOTE: this only works for >aligned< register tuples !
1204 for (Value::DefCIterator D = vA->defs.begin(); D != vA->defs.end(); ++D) {
1205 for (Value::DefCIterator d = vB->defs.begin(); d != vB->defs.end(); ++d) {
1206 const LValue *vD = (*D)->get()->asLValue();
1207 const LValue *vd = (*d)->get()->asLValue();
1208
1209 if (!vD->livei.overlaps(vd->livei)) {
1210 INFO_DBG(prog->dbgFlags, REG_ALLOC, "(%%%i) X (%%%i): no overlap\n",
1211 vD->id, vd->id);
1212 continue;
1213 }
1214
1215 uint8_t mask = vD->compound ? vD->compMask : ~0;
1216 if (vd->compound) {
1217 assert(vB->compound);
1218 mask &= vd->compMask & vB->compMask;
1219 } else {
1220 mask &= intfMask;
1221 }
1222
1223 INFO_DBG(prog->dbgFlags, REG_ALLOC,
1224 "(%%%i)%02x X (%%%i)%02x & %02x: $r%i.%02x\n",
1225 vD->id,
1226 vD->compound ? vD->compMask : 0xff,
1227 vd->id,
1228 vd->compound ? vd->compMask : intfMask,
1229 vB->compMask, intf->reg & ~7, mask);
1230 if (mask)
1231 regs.occupyMask(node->f, intf->reg & ~7, mask);
1232 }
1233 }
1234 } else {
1235 INFO_DBG(prog->dbgFlags, REG_ALLOC,
1236 "(%%%i) X (%%%i): $r%i + %u\n",
1237 vA->id, vB->id, intf->reg, intf->colors);
1238 regs.occupy(node->f, intf->reg, intf->colors, true);
1239 }
1240 }
1241
1242 bool
1243 GCRA::selectRegisters()
1244 {
1245 INFO_DBG(prog->dbgFlags, REG_ALLOC, "\nSELECT phase\n");
1246
1247 while (!stack.empty()) {
1248 RIG_Node *node = &nodes[stack.top()];
1249 stack.pop();
1250
1251 regs.reset(node->f);
1252
1253 INFO_DBG(prog->dbgFlags, REG_ALLOC, "\nNODE[%%%i, %u colors]\n",
1254 node->getValue()->id, node->colors);
1255
1256 for (Graph::EdgeIterator ei = node->outgoing(); !ei.end(); ei.next())
1257 checkInterference(node, ei);
1258 for (Graph::EdgeIterator ei = node->incident(); !ei.end(); ei.next())
1259 checkInterference(node, ei);
1260
1261 if (!node->prefRegs.empty()) {
1262 for (std::list<RIG_Node *>::const_iterator it = node->prefRegs.begin();
1263 it != node->prefRegs.end();
1264 ++it) {
1265 if ((*it)->reg >= 0 &&
1266 regs.occupy(node->f, (*it)->reg, node->colors)) {
1267 node->reg = (*it)->reg;
1268 break;
1269 }
1270 }
1271 }
1272 if (node->reg >= 0)
1273 continue;
1274 LValue *lval = node->getValue();
1275 if (prog->dbgFlags & NV50_IR_DEBUG_REG_ALLOC)
1276 regs.print();
1277 bool ret = regs.assign(node->reg, node->f, node->colors);
1278 if (ret) {
1279 INFO_DBG(prog->dbgFlags, REG_ALLOC, "assigned reg %i\n", node->reg);
1280 lval->compMask = node->getCompMask();
1281 } else {
1282 INFO_DBG(prog->dbgFlags, REG_ALLOC, "must spill: %%%i (size %u)\n",
1283 lval->id, lval->reg.size);
1284 Symbol *slot = NULL;
1285 if (lval->reg.file == FILE_GPR)
1286 slot = spill.assignSlot(node->livei, lval->reg.size);
1287 mustSpill.push_back(ValuePair(lval, slot));
1288 }
1289 }
1290 if (!mustSpill.empty())
1291 return false;
1292 for (unsigned int i = 0; i < nodeCount; ++i) {
1293 LValue *lval = nodes[i].getValue();
1294 if (nodes[i].reg >= 0 && nodes[i].colors > 0)
1295 lval->reg.data.id =
1296 regs.unitsToId(nodes[i].f, nodes[i].reg, lval->reg.size);
1297 }
1298 return true;
1299 }
1300
1301 bool
1302 GCRA::allocateRegisters(ArrayList& insns)
1303 {
1304 bool ret;
1305
1306 INFO_DBG(prog->dbgFlags, REG_ALLOC,
1307 "allocateRegisters to %u instructions\n", insns.getSize());
1308
1309 nodeCount = func->allLValues.getSize();
1310 nodes = new RIG_Node[nodeCount];
1311 if (!nodes)
1312 return false;
1313 for (unsigned int i = 0; i < nodeCount; ++i) {
1314 LValue *lval = reinterpret_cast<LValue *>(func->allLValues.get(i));
1315 if (lval) {
1316 nodes[i].init(regs, lval);
1317 RIG.insert(&nodes[i]);
1318 }
1319 }
1320
1321 // coalesce first, we use only 1 RIG node for a group of joined values
1322 ret = coalesce(insns);
1323 if (!ret)
1324 goto out;
1325
1326 if (func->getProgram()->dbgFlags & NV50_IR_DEBUG_REG_ALLOC)
1327 func->printLiveIntervals();
1328
1329 buildRIG(insns);
1330 calculateSpillWeights();
1331 simplify();
1332
1333 ret = selectRegisters();
1334 if (!ret) {
1335 INFO_DBG(prog->dbgFlags, REG_ALLOC,
1336 "selectRegisters failed, inserting spill code ...\n");
1337 regs.reset(FILE_GPR, true);
1338 spill.run(mustSpill);
1339 if (prog->dbgFlags & NV50_IR_DEBUG_REG_ALLOC)
1340 func->print();
1341 } else {
1342 prog->maxGPR = regs.getMaxAssigned(FILE_GPR);
1343 }
1344
1345 out:
1346 cleanup(ret);
1347 return ret;
1348 }
1349
1350 void
1351 GCRA::cleanup(const bool success)
1352 {
1353 mustSpill.clear();
1354
1355 for (ArrayList::Iterator it = func->allLValues.iterator();
1356 !it.end(); it.next()) {
1357 LValue *lval = reinterpret_cast<LValue *>(it.get());
1358
1359 lval->livei.clear();
1360
1361 lval->compound = 0;
1362 lval->compMask = 0;
1363
1364 if (lval->join == lval)
1365 continue;
1366
1367 if (success) {
1368 lval->reg.data.id = lval->join->reg.data.id;
1369 } else {
1370 for (Value::DefIterator d = lval->defs.begin(); d != lval->defs.end();
1371 ++d)
1372 lval->join->defs.remove(*d);
1373 lval->join = lval;
1374 }
1375 }
1376
1377 if (success)
1378 resolveSplitsAndMerges();
1379 splits.clear(); // avoid duplicate entries on next coalesce pass
1380 merges.clear();
1381
1382 delete[] nodes;
1383 nodes = NULL;
1384 }
1385
1386 Symbol *
1387 SpillCodeInserter::assignSlot(const Interval &livei, const unsigned int size)
1388 {
1389 SpillSlot slot;
1390 int32_t offsetBase = stackSize;
1391 int32_t offset;
1392 std::list<SpillSlot>::iterator pos = slots.end(), it = slots.begin();
1393
1394 if (offsetBase % size)
1395 offsetBase += size - (offsetBase % size);
1396
1397 slot.sym = NULL;
1398
1399 for (offset = offsetBase; offset < stackSize; offset += size) {
1400 const int32_t entryEnd = offset + size;
1401 while (it != slots.end() && it->offset < offset)
1402 ++it;
1403 if (it == slots.end()) // no slots left
1404 break;
1405 std::list<SpillSlot>::iterator bgn = it;
1406
1407 while (it != slots.end() && it->offset < entryEnd) {
1408 it->occup.print();
1409 if (it->occup.overlaps(livei))
1410 break;
1411 ++it;
1412 }
1413 if (it == slots.end() || it->offset >= entryEnd) {
1414 // fits
1415 for (; bgn != slots.end() && bgn->offset < entryEnd; ++bgn) {
1416 bgn->occup.insert(livei);
1417 if (bgn->size() == size)
1418 slot.sym = bgn->sym;
1419 }
1420 break;
1421 }
1422 }
1423 if (!slot.sym) {
1424 stackSize = offset + size;
1425 slot.offset = offset;
1426 slot.sym = new_Symbol(func->getProgram(), FILE_MEMORY_LOCAL);
1427 if (!func->stackPtr)
1428 offset += func->tlsBase;
1429 slot.sym->setAddress(NULL, offset);
1430 slot.sym->reg.size = size;
1431 slots.insert(pos, slot)->occup.insert(livei);
1432 }
1433 return slot.sym;
1434 }
1435
1436 void
1437 SpillCodeInserter::spill(Instruction *defi, Value *slot, LValue *lval)
1438 {
1439 const DataType ty = typeOfSize(slot->reg.size);
1440
1441 Instruction *st;
1442 if (slot->reg.file == FILE_MEMORY_LOCAL) {
1443 st = new_Instruction(func, OP_STORE, ty);
1444 st->setSrc(0, slot);
1445 st->setSrc(1, lval);
1446 lval->noSpill = 1;
1447 } else {
1448 st = new_Instruction(func, OP_CVT, ty);
1449 st->setDef(0, slot);
1450 st->setSrc(0, lval);
1451 }
1452 defi->bb->insertAfter(defi, st);
1453 }
1454
1455 LValue *
1456 SpillCodeInserter::unspill(Instruction *usei, LValue *lval, Value *slot)
1457 {
1458 const DataType ty = typeOfSize(slot->reg.size);
1459
1460 lval = cloneShallow(func, lval);
1461
1462 Instruction *ld;
1463 if (slot->reg.file == FILE_MEMORY_LOCAL) {
1464 lval->noSpill = 1;
1465 ld = new_Instruction(func, OP_LOAD, ty);
1466 } else {
1467 ld = new_Instruction(func, OP_CVT, ty);
1468 }
1469 ld->setDef(0, lval);
1470 ld->setSrc(0, slot);
1471
1472 usei->bb->insertBefore(usei, ld);
1473 return lval;
1474 }
1475
1476 bool
1477 SpillCodeInserter::run(const std::list<ValuePair>& lst)
1478 {
1479 for (std::list<ValuePair>::const_iterator it = lst.begin(); it != lst.end();
1480 ++it) {
1481 LValue *lval = it->first->asLValue();
1482 Symbol *mem = it->second ? it->second->asSym() : NULL;
1483
1484 for (Value::DefIterator d = lval->defs.begin(); d != lval->defs.end();
1485 ++d) {
1486 Value *slot = mem ?
1487 static_cast<Value *>(mem) : new_LValue(func, FILE_GPR);
1488 Value *tmp = NULL;
1489 Instruction *last = NULL;
1490
1491 LValue *dval = (*d)->get()->asLValue();
1492 Instruction *defi = (*d)->getInsn();
1493
1494 // handle uses first or they'll contain the spill stores
1495 while (!dval->uses.empty()) {
1496 ValueRef *u = dval->uses.front();
1497 Instruction *usei = u->getInsn();
1498 assert(usei);
1499 if (usei->op == OP_PHI) {
1500 tmp = (slot->reg.file == FILE_MEMORY_LOCAL) ? NULL : slot;
1501 last = NULL;
1502 } else
1503 if (!last || usei != last->next) { // TODO: sort uses
1504 tmp = unspill(usei, dval, slot);
1505 last = usei;
1506 }
1507 u->set(tmp);
1508 }
1509
1510 assert(defi);
1511 if (defi->op == OP_PHI) {
1512 d = lval->defs.erase(d);
1513 --d;
1514 if (slot->reg.file == FILE_MEMORY_LOCAL)
1515 delete_Instruction(func->getProgram(), defi);
1516 else
1517 defi->setDef(0, slot);
1518 } else {
1519 spill(defi, slot, dval);
1520 }
1521 }
1522
1523 }
1524
1525 // TODO: We're not trying to reuse old slots in a potential next iteration.
1526 // We have to update the slots' livei intervals to be able to do that.
1527 stackBase = stackSize;
1528 slots.clear();
1529 return true;
1530 }
1531
1532 bool
1533 RegAlloc::exec()
1534 {
1535 for (IteratorRef it = prog->calls.iteratorDFS(false);
1536 !it->end(); it->next()) {
1537 func = Function::get(reinterpret_cast<Graph::Node *>(it->get()));
1538
1539 func->tlsBase = prog->tlsSize;
1540 if (!execFunc())
1541 return false;
1542 prog->tlsSize += func->tlsSize;
1543 }
1544 return true;
1545 }
1546
1547 bool
1548 RegAlloc::execFunc()
1549 {
1550 InsertConstraintsPass insertConstr;
1551 PhiMovesPass insertPhiMoves;
1552 ArgumentMovesPass insertArgMoves;
1553 BuildIntervalsPass buildIntervals;
1554 SpillCodeInserter insertSpills(func);
1555
1556 GCRA gcra(func, insertSpills);
1557
1558 unsigned int i, retries;
1559 bool ret;
1560
1561 ret = insertConstr.exec(func);
1562 if (!ret)
1563 goto out;
1564
1565 ret = insertPhiMoves.run(func);
1566 if (!ret)
1567 goto out;
1568
1569 ret = insertArgMoves.run(func);
1570 if (!ret)
1571 goto out;
1572
1573 // TODO: need to fix up spill slot usage ranges to support > 1 retry
1574 for (retries = 0; retries < 3; ++retries) {
1575 if (retries && (prog->dbgFlags & NV50_IR_DEBUG_REG_ALLOC))
1576 INFO("Retry: %i\n", retries);
1577 if (prog->dbgFlags & NV50_IR_DEBUG_REG_ALLOC)
1578 func->print();
1579
1580 // spilling to registers may add live ranges, need to rebuild everything
1581 ret = true;
1582 for (sequence = func->cfg.nextSequence(), i = 0;
1583 ret && i <= func->loopNestingBound;
1584 sequence = func->cfg.nextSequence(), ++i)
1585 ret = buildLiveSets(BasicBlock::get(func->cfg.getRoot()));
1586 if (!ret)
1587 break;
1588 func->orderInstructions(this->insns);
1589
1590 ret = buildIntervals.run(func);
1591 if (!ret)
1592 break;
1593 ret = gcra.allocateRegisters(insns);
1594 if (ret)
1595 break; // success
1596 }
1597 INFO_DBG(prog->dbgFlags, REG_ALLOC, "RegAlloc done: %i\n", ret);
1598
1599 func->tlsSize = insertSpills.getStackSize();
1600 out:
1601 return ret;
1602 }
1603
1604 // TODO: check if modifying Instruction::join here breaks anything
1605 void
1606 GCRA::resolveSplitsAndMerges()
1607 {
1608 for (std::list<Instruction *>::iterator it = splits.begin();
1609 it != splits.end();
1610 ++it) {
1611 Instruction *split = *it;
1612 unsigned int reg = regs.idToBytes(split->getSrc(0));
1613 for (int d = 0; split->defExists(d); ++d) {
1614 Value *v = split->getDef(d);
1615 v->reg.data.id = regs.bytesToId(v, reg);
1616 v->join = v;
1617 reg += v->reg.size;
1618 }
1619 }
1620 splits.clear();
1621
1622 for (std::list<Instruction *>::iterator it = merges.begin();
1623 it != merges.end();
1624 ++it) {
1625 Instruction *merge = *it;
1626 unsigned int reg = regs.idToBytes(merge->getDef(0));
1627 for (int s = 0; merge->srcExists(s); ++s) {
1628 Value *v = merge->getSrc(s);
1629 v->reg.data.id = regs.bytesToId(v, reg);
1630 v->join = v;
1631 reg += v->reg.size;
1632 }
1633 }
1634 merges.clear();
1635 }
1636
1637 bool Program::registerAllocation()
1638 {
1639 RegAlloc ra(this);
1640 return ra.exec();
1641 }
1642
1643 bool
1644 RegAlloc::InsertConstraintsPass::exec(Function *ir)
1645 {
1646 constrList.clear();
1647
1648 bool ret = run(ir, true, true);
1649 if (ret)
1650 ret = insertConstraintMoves();
1651 return ret;
1652 }
1653
1654 // TODO: make part of texture insn
1655 void
1656 RegAlloc::InsertConstraintsPass::textureMask(TexInstruction *tex)
1657 {
1658 Value *def[4];
1659 int c, k, d;
1660 uint8_t mask = 0;
1661
1662 for (d = 0, k = 0, c = 0; c < 4; ++c) {
1663 if (!(tex->tex.mask & (1 << c)))
1664 continue;
1665 if (tex->getDef(k)->refCount()) {
1666 mask |= 1 << c;
1667 def[d++] = tex->getDef(k);
1668 }
1669 ++k;
1670 }
1671 tex->tex.mask = mask;
1672
1673 for (c = 0; c < d; ++c)
1674 tex->setDef(c, def[c]);
1675 for (; c < 4; ++c)
1676 tex->setDef(c, NULL);
1677 }
1678
1679 bool
1680 RegAlloc::InsertConstraintsPass::detectConflict(Instruction *cst, int s)
1681 {
1682 Value *v = cst->getSrc(s);
1683
1684 // current register allocation can't handle it if a value participates in
1685 // multiple constraints
1686 for (Value::UseIterator it = v->uses.begin(); it != v->uses.end(); ++it) {
1687 if (cst != (*it)->getInsn())
1688 return true;
1689 }
1690
1691 // can start at s + 1 because detectConflict is called on all sources
1692 for (int c = s + 1; cst->srcExists(c); ++c)
1693 if (v == cst->getSrc(c))
1694 return true;
1695
1696 Instruction *defi = v->getInsn();
1697
1698 return (!defi || defi->constrainedDefs());
1699 }
1700
1701 void
1702 RegAlloc::InsertConstraintsPass::addConstraint(Instruction *i, int s, int n)
1703 {
1704 Instruction *cst;
1705 int d;
1706
1707 // first, look for an existing identical constraint op
1708 for (std::list<Instruction *>::iterator it = constrList.begin();
1709 it != constrList.end();
1710 ++it) {
1711 cst = (*it);
1712 if (!i->bb->dominatedBy(cst->bb))
1713 break;
1714 for (d = 0; d < n; ++d)
1715 if (cst->getSrc(d) != i->getSrc(d + s))
1716 break;
1717 if (d >= n) {
1718 for (d = 0; d < n; ++d, ++s)
1719 i->setSrc(s, cst->getDef(d));
1720 return;
1721 }
1722 }
1723 cst = new_Instruction(func, OP_CONSTRAINT, i->dType);
1724
1725 for (d = 0; d < n; ++s, ++d) {
1726 cst->setDef(d, new_LValue(func, FILE_GPR));
1727 cst->setSrc(d, i->getSrc(s));
1728 i->setSrc(s, cst->getDef(d));
1729 }
1730 i->bb->insertBefore(i, cst);
1731
1732 constrList.push_back(cst);
1733 }
1734
1735 // Add a dummy use of the pointer source of >= 8 byte loads after the load
1736 // to prevent it from being assigned a register which overlapping the load's
1737 // destination, which would produce random corruptions.
1738 void
1739 RegAlloc::InsertConstraintsPass::addHazard(Instruction *i, const ValueRef *src)
1740 {
1741 Instruction *hzd = new_Instruction(func, OP_NOP, TYPE_NONE);
1742 hzd->setSrc(0, src->get());
1743 i->bb->insertAfter(i, hzd);
1744
1745 }
1746
1747 // b32 { %r0 %r1 %r2 %r3 } -> b128 %r0q
1748 void
1749 RegAlloc::InsertConstraintsPass::condenseDefs(Instruction *insn)
1750 {
1751 uint8_t size = 0;
1752 int n;
1753 for (n = 0; insn->defExists(n) && insn->def(n).getFile() == FILE_GPR; ++n)
1754 size += insn->getDef(n)->reg.size;
1755 if (n < 2)
1756 return;
1757 LValue *lval = new_LValue(func, FILE_GPR);
1758 lval->reg.size = size;
1759
1760 Instruction *split = new_Instruction(func, OP_SPLIT, typeOfSize(size));
1761 split->setSrc(0, lval);
1762 for (int d = 0; d < n; ++d) {
1763 split->setDef(d, insn->getDef(d));
1764 insn->setDef(d, NULL);
1765 }
1766 insn->setDef(0, lval);
1767
1768 for (int k = 1, d = n; insn->defExists(d); ++d, ++k) {
1769 insn->setDef(k, insn->getDef(d));
1770 insn->setDef(d, NULL);
1771 }
1772 // carry over predicate if any (mainly for OP_UNION uses)
1773 split->setPredicate(insn->cc, insn->getPredicate());
1774
1775 insn->bb->insertAfter(insn, split);
1776 constrList.push_back(split);
1777 }
1778 void
1779 RegAlloc::InsertConstraintsPass::condenseSrcs(Instruction *insn,
1780 const int a, const int b)
1781 {
1782 uint8_t size = 0;
1783 if (a >= b)
1784 return;
1785 for (int s = a; s <= b; ++s)
1786 size += insn->getSrc(s)->reg.size;
1787 if (!size)
1788 return;
1789 LValue *lval = new_LValue(func, FILE_GPR);
1790 lval->reg.size = size;
1791
1792 Value *save[3];
1793 insn->takeExtraSources(0, save);
1794
1795 Instruction *merge = new_Instruction(func, OP_MERGE, typeOfSize(size));
1796 merge->setDef(0, lval);
1797 for (int s = a, i = 0; s <= b; ++s, ++i) {
1798 merge->setSrc(i, insn->getSrc(s));
1799 insn->setSrc(s, NULL);
1800 }
1801 insn->setSrc(a, lval);
1802
1803 for (int k = a + 1, s = b + 1; insn->srcExists(s); ++s, ++k) {
1804 insn->setSrc(k, insn->getSrc(s));
1805 insn->setSrc(s, NULL);
1806 }
1807 insn->bb->insertBefore(insn, merge);
1808
1809 insn->putExtraSources(0, save);
1810
1811 constrList.push_back(merge);
1812 }
1813
1814 void
1815 RegAlloc::InsertConstraintsPass::texConstraintNVE0(TexInstruction *tex)
1816 {
1817 textureMask(tex);
1818 condenseDefs(tex);
1819
1820 int n = tex->srcCount(0xff, true);
1821 if (n > 4) {
1822 condenseSrcs(tex, 0, 3);
1823 if (n > 5) // NOTE: first call modified positions already
1824 condenseSrcs(tex, 4 - (4 - 1), n - 1 - (4 - 1));
1825 } else
1826 if (n > 1) {
1827 condenseSrcs(tex, 0, n - 1);
1828 }
1829 }
1830
1831 void
1832 RegAlloc::InsertConstraintsPass::texConstraintNVC0(TexInstruction *tex)
1833 {
1834 int n, s;
1835
1836 textureMask(tex);
1837
1838 if (tex->op == OP_TXQ) {
1839 s = tex->srcCount(0xff);
1840 n = 0;
1841 } else {
1842 s = tex->tex.target.getArgCount();
1843 if (!tex->tex.target.isArray() &&
1844 (tex->tex.rIndirectSrc >= 0 || tex->tex.sIndirectSrc >= 0))
1845 ++s;
1846 if (tex->op == OP_TXD && tex->tex.useOffsets)
1847 ++s;
1848 n = tex->srcCount(0xff) - s;
1849 assert(n <= 4);
1850 }
1851
1852 if (s > 1)
1853 condenseSrcs(tex, 0, s - 1);
1854 if (n > 1) // NOTE: first call modified positions already
1855 condenseSrcs(tex, 1, n);
1856
1857 condenseDefs(tex);
1858 }
1859
1860 void
1861 RegAlloc::InsertConstraintsPass::texConstraintNV50(TexInstruction *tex)
1862 {
1863 Value *pred = tex->getPredicate();
1864 if (pred)
1865 tex->setPredicate(tex->cc, NULL);
1866
1867 textureMask(tex);
1868
1869 assert(tex->defExists(0) && tex->srcExists(0));
1870 // make src and def count match
1871 int c;
1872 for (c = 0; tex->srcExists(c) || tex->defExists(c); ++c) {
1873 if (!tex->srcExists(c))
1874 tex->setSrc(c, new_LValue(func, tex->getSrc(0)->asLValue()));
1875 if (!tex->defExists(c))
1876 tex->setDef(c, new_LValue(func, tex->getDef(0)->asLValue()));
1877 }
1878 if (pred)
1879 tex->setPredicate(tex->cc, pred);
1880 condenseDefs(tex);
1881 condenseSrcs(tex, 0, c - 1);
1882 }
1883
1884 // Insert constraint markers for instructions whose multiple sources must be
1885 // located in consecutive registers.
1886 bool
1887 RegAlloc::InsertConstraintsPass::visit(BasicBlock *bb)
1888 {
1889 TexInstruction *tex;
1890 Instruction *next;
1891 int s, size;
1892
1893 targ = bb->getProgram()->getTarget();
1894
1895 for (Instruction *i = bb->getEntry(); i; i = next) {
1896 next = i->next;
1897
1898 if ((tex = i->asTex())) {
1899 switch (targ->getChipset() & ~0xf) {
1900 case 0x50:
1901 case 0x80:
1902 case 0x90:
1903 case 0xa0:
1904 texConstraintNV50(tex);
1905 break;
1906 case 0xc0:
1907 case 0xd0:
1908 texConstraintNVC0(tex);
1909 break;
1910 case 0xe0:
1911 case NVISA_GK110_CHIPSET:
1912 texConstraintNVE0(tex);
1913 break;
1914 default:
1915 break;
1916 }
1917 } else
1918 if (i->op == OP_EXPORT || i->op == OP_STORE) {
1919 for (size = typeSizeof(i->dType), s = 1; size > 0; ++s) {
1920 assert(i->srcExists(s));
1921 size -= i->getSrc(s)->reg.size;
1922 }
1923 condenseSrcs(i, 1, s - 1);
1924 } else
1925 if (i->op == OP_LOAD || i->op == OP_VFETCH) {
1926 condenseDefs(i);
1927 if (i->src(0).isIndirect(0) && typeSizeof(i->dType) >= 8)
1928 addHazard(i, i->src(0).getIndirect(0));
1929 } else
1930 if (i->op == OP_UNION) {
1931 constrList.push_back(i);
1932 }
1933 }
1934 return true;
1935 }
1936
1937 // Insert extra moves so that, if multiple register constraints on a value are
1938 // in conflict, these conflicts can be resolved.
1939 bool
1940 RegAlloc::InsertConstraintsPass::insertConstraintMoves()
1941 {
1942 for (std::list<Instruction *>::iterator it = constrList.begin();
1943 it != constrList.end();
1944 ++it) {
1945 Instruction *cst = *it;
1946 Instruction *mov;
1947
1948 if (cst->op == OP_SPLIT && 0) {
1949 // spilling splits is annoying, just make sure they're separate
1950 for (int d = 0; cst->defExists(d); ++d) {
1951 if (!cst->getDef(d)->refCount())
1952 continue;
1953 LValue *lval = new_LValue(func, cst->def(d).getFile());
1954 const uint8_t size = cst->def(d).getSize();
1955 lval->reg.size = size;
1956
1957 mov = new_Instruction(func, OP_MOV, typeOfSize(size));
1958 mov->setSrc(0, lval);
1959 mov->setDef(0, cst->getDef(d));
1960 cst->setDef(d, mov->getSrc(0));
1961 cst->bb->insertAfter(cst, mov);
1962
1963 cst->getSrc(0)->asLValue()->noSpill = 1;
1964 mov->getSrc(0)->asLValue()->noSpill = 1;
1965 }
1966 } else
1967 if (cst->op == OP_MERGE || cst->op == OP_UNION) {
1968 for (int s = 0; cst->srcExists(s); ++s) {
1969 const uint8_t size = cst->src(s).getSize();
1970
1971 if (!cst->getSrc(s)->defs.size()) {
1972 mov = new_Instruction(func, OP_NOP, typeOfSize(size));
1973 mov->setDef(0, cst->getSrc(s));
1974 cst->bb->insertBefore(cst, mov);
1975 continue;
1976 }
1977 assert(cst->getSrc(s)->defs.size() == 1); // still SSA
1978
1979 Instruction *defi = cst->getSrc(s)->defs.front()->getInsn();
1980 // catch some cases where don't really need MOVs
1981 if (cst->getSrc(s)->refCount() == 1 && !defi->constrainedDefs())
1982 continue;
1983
1984 LValue *lval = new_LValue(func, cst->src(s).getFile());
1985 lval->reg.size = size;
1986
1987 mov = new_Instruction(func, OP_MOV, typeOfSize(size));
1988 mov->setDef(0, lval);
1989 mov->setSrc(0, cst->getSrc(s));
1990 cst->setSrc(s, mov->getDef(0));
1991 cst->bb->insertBefore(cst, mov);
1992
1993 cst->getDef(0)->asLValue()->noSpill = 1; // doesn't help
1994
1995 if (cst->op == OP_UNION)
1996 mov->setPredicate(defi->cc, defi->getPredicate());
1997 }
1998 }
1999 }
2000
2001 return true;
2002 }
2003
2004 } // namespace nv50_ir