nv50/ir/ra: improve condition for short regs, unify with cond for 16-bit
[mesa.git] / src / gallium / drivers / nouveau / 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 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.
21 */
22
23 #include "codegen/nv50_ir.h"
24 #include "codegen/nv50_ir_target.h"
25
26 #include <algorithm>
27 #include <stack>
28 #include <limits>
29 #if __cplusplus >= 201103L
30 #include <unordered_map>
31 #else
32 #include <tr1/unordered_map>
33 #endif
34
35 namespace nv50_ir {
36
37 #if __cplusplus >= 201103L
38 using std::hash;
39 using std::unordered_map;
40 #else
41 using std::tr1::hash;
42 using std::tr1::unordered_map;
43 #endif
44
45 #define MAX_REGISTER_FILE_SIZE 256
46
47 class RegisterSet
48 {
49 public:
50 RegisterSet(const Target *);
51
52 void init(const Target *);
53 void reset(DataFile, bool resetMax = false);
54
55 void periodicMask(DataFile f, uint32_t lock, uint32_t unlock);
56 void intersect(DataFile f, const RegisterSet *);
57
58 bool assign(int32_t& reg, DataFile f, unsigned int size);
59 void release(DataFile f, int32_t reg, unsigned int size);
60 void occupy(DataFile f, int32_t reg, unsigned int size);
61 void occupy(const Value *);
62 void occupyMask(DataFile f, int32_t reg, uint8_t mask);
63 bool isOccupied(DataFile f, int32_t reg, unsigned int size) const;
64 bool testOccupy(const Value *);
65 bool testOccupy(DataFile f, int32_t reg, unsigned int size);
66
67 inline int getMaxAssigned(DataFile f) const { return fill[f]; }
68
69 inline unsigned int getFileSize(DataFile f) const
70 {
71 return last[f] + 1;
72 }
73
74 inline unsigned int units(DataFile f, unsigned int size) const
75 {
76 return size >> unit[f];
77 }
78 // for regs of size >= 4, id is counted in 4-byte words (like nv50/c0 binary)
79 inline unsigned int idToBytes(const Value *v) const
80 {
81 return v->reg.data.id * MIN2(v->reg.size, 4);
82 }
83 inline unsigned int idToUnits(const Value *v) const
84 {
85 return units(v->reg.file, idToBytes(v));
86 }
87 inline int bytesToId(Value *v, unsigned int bytes) const
88 {
89 if (v->reg.size < 4)
90 return units(v->reg.file, bytes);
91 return bytes / 4;
92 }
93 inline int unitsToId(DataFile f, int u, uint8_t size) const
94 {
95 if (u < 0)
96 return -1;
97 return (size < 4) ? u : ((u << unit[f]) / 4);
98 }
99
100 void print(DataFile f) const;
101
102 const bool restrictedGPR16Range;
103
104 private:
105 BitSet bits[LAST_REGISTER_FILE + 1];
106
107 int unit[LAST_REGISTER_FILE + 1]; // log2 of allocation granularity
108
109 int last[LAST_REGISTER_FILE + 1];
110 int fill[LAST_REGISTER_FILE + 1];
111 };
112
113 void
114 RegisterSet::reset(DataFile f, bool resetMax)
115 {
116 bits[f].fill(0);
117 if (resetMax)
118 fill[f] = -1;
119 }
120
121 void
122 RegisterSet::init(const Target *targ)
123 {
124 for (unsigned int rf = 0; rf <= FILE_ADDRESS; ++rf) {
125 DataFile f = static_cast<DataFile>(rf);
126 last[rf] = targ->getFileSize(f) - 1;
127 unit[rf] = targ->getFileUnit(f);
128 fill[rf] = -1;
129 assert(last[rf] < MAX_REGISTER_FILE_SIZE);
130 bits[rf].allocate(last[rf] + 1, true);
131 }
132 }
133
134 RegisterSet::RegisterSet(const Target *targ)
135 : restrictedGPR16Range(targ->getChipset() < 0xc0)
136 {
137 init(targ);
138 for (unsigned int i = 0; i <= LAST_REGISTER_FILE; ++i)
139 reset(static_cast<DataFile>(i));
140 }
141
142 void
143 RegisterSet::periodicMask(DataFile f, uint32_t lock, uint32_t unlock)
144 {
145 bits[f].periodicMask32(lock, unlock);
146 }
147
148 void
149 RegisterSet::intersect(DataFile f, const RegisterSet *set)
150 {
151 bits[f] |= set->bits[f];
152 }
153
154 void
155 RegisterSet::print(DataFile f) const
156 {
157 INFO("GPR:");
158 bits[f].print();
159 INFO("\n");
160 }
161
162 bool
163 RegisterSet::assign(int32_t& reg, DataFile f, unsigned int size)
164 {
165 reg = bits[f].findFreeRange(size);
166 if (reg < 0)
167 return false;
168 fill[f] = MAX2(fill[f], (int32_t)(reg + size - 1));
169 return true;
170 }
171
172 bool
173 RegisterSet::isOccupied(DataFile f, int32_t reg, unsigned int size) const
174 {
175 return bits[f].testRange(reg, size);
176 }
177
178 void
179 RegisterSet::occupy(const Value *v)
180 {
181 occupy(v->reg.file, idToUnits(v), v->reg.size >> unit[v->reg.file]);
182 }
183
184 void
185 RegisterSet::occupyMask(DataFile f, int32_t reg, uint8_t mask)
186 {
187 bits[f].setMask(reg & ~31, static_cast<uint32_t>(mask) << (reg % 32));
188 }
189
190 void
191 RegisterSet::occupy(DataFile f, int32_t reg, unsigned int size)
192 {
193 bits[f].setRange(reg, size);
194
195 INFO_DBG(0, REG_ALLOC, "reg occupy: %u[%i] %u\n", f, reg, size);
196
197 fill[f] = MAX2(fill[f], (int32_t)(reg + size - 1));
198 }
199
200 bool
201 RegisterSet::testOccupy(const Value *v)
202 {
203 return testOccupy(v->reg.file,
204 idToUnits(v), v->reg.size >> unit[v->reg.file]);
205 }
206
207 bool
208 RegisterSet::testOccupy(DataFile f, int32_t reg, unsigned int size)
209 {
210 if (isOccupied(f, reg, size))
211 return false;
212 occupy(f, reg, size);
213 return true;
214 }
215
216 void
217 RegisterSet::release(DataFile f, int32_t reg, unsigned int size)
218 {
219 bits[f].clrRange(reg, size);
220
221 INFO_DBG(0, REG_ALLOC, "reg release: %u[%i] %u\n", f, reg, size);
222 }
223
224 class RegAlloc
225 {
226 public:
227 RegAlloc(Program *program) : prog(program), sequence(0) { }
228
229 bool exec();
230 bool execFunc();
231
232 private:
233 class PhiMovesPass : public Pass {
234 private:
235 virtual bool visit(BasicBlock *);
236 inline bool needNewElseBlock(BasicBlock *b, BasicBlock *p);
237 inline void splitEdges(BasicBlock *b);
238 };
239
240 class ArgumentMovesPass : public Pass {
241 private:
242 virtual bool visit(BasicBlock *);
243 };
244
245 class BuildIntervalsPass : public Pass {
246 private:
247 virtual bool visit(BasicBlock *);
248 void collectLiveValues(BasicBlock *);
249 void addLiveRange(Value *, const BasicBlock *, int end);
250 };
251
252 class InsertConstraintsPass : public Pass {
253 public:
254 bool exec(Function *func);
255 private:
256 virtual bool visit(BasicBlock *);
257
258 void insertConstraintMove(Instruction *, int s);
259 bool insertConstraintMoves();
260
261 void condenseDefs(Instruction *);
262 void condenseDefs(Instruction *, const int first, const int last);
263 void condenseSrcs(Instruction *, const int first, const int last);
264
265 void addHazard(Instruction *i, const ValueRef *src);
266 void textureMask(TexInstruction *);
267 void addConstraint(Instruction *, int s, int n);
268 bool detectConflict(Instruction *, int s);
269
270 // target specific functions, TODO: put in subclass or Target
271 void texConstraintNV50(TexInstruction *);
272 void texConstraintNVC0(TexInstruction *);
273 void texConstraintNVE0(TexInstruction *);
274 void texConstraintGM107(TexInstruction *);
275
276 bool isScalarTexGM107(TexInstruction *);
277 void handleScalarTexGM107(TexInstruction *);
278
279 std::list<Instruction *> constrList;
280
281 const Target *targ;
282 };
283
284 bool buildLiveSets(BasicBlock *);
285
286 private:
287 Program *prog;
288 Function *func;
289
290 // instructions in control flow / chronological order
291 ArrayList insns;
292
293 int sequence; // for manual passes through CFG
294 };
295
296 typedef std::pair<Value *, Value *> ValuePair;
297
298 class SpillCodeInserter
299 {
300 public:
301 SpillCodeInserter(Function *fn) : func(fn), stackSize(0), stackBase(0) { }
302
303 bool run(const std::list<ValuePair>&);
304
305 Symbol *assignSlot(const Interval&, const unsigned int size);
306 Value *offsetSlot(Value *, const LValue *);
307 inline int32_t getStackSize() const { return stackSize; }
308
309 private:
310 Function *func;
311
312 struct SpillSlot
313 {
314 Interval occup;
315 std::list<Value *> residents; // needed to recalculate occup
316 Symbol *sym;
317 int32_t offset;
318 inline uint8_t size() const { return sym->reg.size; }
319 };
320 std::list<SpillSlot> slots;
321 int32_t stackSize;
322 int32_t stackBase;
323
324 LValue *unspill(Instruction *usei, LValue *, Value *slot);
325 void spill(Instruction *defi, Value *slot, LValue *);
326 };
327
328 void
329 RegAlloc::BuildIntervalsPass::addLiveRange(Value *val,
330 const BasicBlock *bb,
331 int end)
332 {
333 Instruction *insn = val->getUniqueInsn();
334
335 if (!insn)
336 insn = bb->getFirst();
337
338 assert(bb->getFirst()->serial <= bb->getExit()->serial);
339 assert(bb->getExit()->serial + 1 >= end);
340
341 int begin = insn->serial;
342 if (begin < bb->getEntry()->serial || begin > bb->getExit()->serial)
343 begin = bb->getEntry()->serial;
344
345 INFO_DBG(prog->dbgFlags, REG_ALLOC, "%%%i <- live range [%i(%i), %i)\n",
346 val->id, begin, insn->serial, end);
347
348 if (begin != end) // empty ranges are only added as hazards for fixed regs
349 val->livei.extend(begin, end);
350 }
351
352 bool
353 RegAlloc::PhiMovesPass::needNewElseBlock(BasicBlock *b, BasicBlock *p)
354 {
355 if (b->cfg.incidentCount() <= 1)
356 return false;
357
358 int n = 0;
359 for (Graph::EdgeIterator ei = p->cfg.outgoing(); !ei.end(); ei.next())
360 if (ei.getType() == Graph::Edge::TREE ||
361 ei.getType() == Graph::Edge::FORWARD)
362 ++n;
363 return (n == 2);
364 }
365
366 struct PhiMapHash {
367 size_t operator()(const std::pair<Instruction *, BasicBlock *>& val) const {
368 return hash<Instruction*>()(val.first) * 31 +
369 hash<BasicBlock*>()(val.second);
370 }
371 };
372
373 typedef unordered_map<
374 std::pair<Instruction *, BasicBlock *>, Value *, PhiMapHash> PhiMap;
375
376 // Critical edges need to be split up so that work can be inserted along
377 // specific edge transitions. Unfortunately manipulating incident edges into a
378 // BB invalidates all the PHI nodes since their sources are implicitly ordered
379 // by incident edge order.
380 //
381 // TODO: Make it so that that is not the case, and PHI nodes store pointers to
382 // the original BBs.
383 void
384 RegAlloc::PhiMovesPass::splitEdges(BasicBlock *bb)
385 {
386 BasicBlock *pb, *pn;
387 Instruction *phi;
388 Graph::EdgeIterator ei;
389 std::stack<BasicBlock *> stack;
390 int j = 0;
391
392 for (ei = bb->cfg.incident(); !ei.end(); ei.next()) {
393 pb = BasicBlock::get(ei.getNode());
394 assert(pb);
395 if (needNewElseBlock(bb, pb))
396 stack.push(pb);
397 }
398
399 // No critical edges were found, no need to perform any work.
400 if (stack.empty())
401 return;
402
403 // We're about to, potentially, reorder the inbound edges. This means that
404 // we need to hold on to the (phi, bb) -> src mapping, and fix up the phi
405 // nodes after the graph has been modified.
406 PhiMap phis;
407
408 j = 0;
409 for (ei = bb->cfg.incident(); !ei.end(); ei.next(), j++) {
410 pb = BasicBlock::get(ei.getNode());
411 for (phi = bb->getPhi(); phi && phi->op == OP_PHI; phi = phi->next)
412 phis.insert(std::make_pair(std::make_pair(phi, pb), phi->getSrc(j)));
413 }
414
415 while (!stack.empty()) {
416 pb = stack.top();
417 pn = new BasicBlock(func);
418 stack.pop();
419
420 pb->cfg.detach(&bb->cfg);
421 pb->cfg.attach(&pn->cfg, Graph::Edge::TREE);
422 pn->cfg.attach(&bb->cfg, Graph::Edge::FORWARD);
423
424 assert(pb->getExit()->op != OP_CALL);
425 if (pb->getExit()->asFlow()->target.bb == bb)
426 pb->getExit()->asFlow()->target.bb = pn;
427
428 for (phi = bb->getPhi(); phi && phi->op == OP_PHI; phi = phi->next) {
429 PhiMap::iterator it = phis.find(std::make_pair(phi, pb));
430 assert(it != phis.end());
431 phis.insert(std::make_pair(std::make_pair(phi, pn), it->second));
432 phis.erase(it);
433 }
434 }
435
436 // Now go through and fix up all of the phi node sources.
437 j = 0;
438 for (ei = bb->cfg.incident(); !ei.end(); ei.next(), j++) {
439 pb = BasicBlock::get(ei.getNode());
440 for (phi = bb->getPhi(); phi && phi->op == OP_PHI; phi = phi->next) {
441 PhiMap::const_iterator it = phis.find(std::make_pair(phi, pb));
442 assert(it != phis.end());
443
444 phi->setSrc(j, it->second);
445 }
446 }
447 }
448
449 // For each operand of each PHI in b, generate a new value by inserting a MOV
450 // at the end of the block it is coming from and replace the operand with its
451 // result. This eliminates liveness conflicts and enables us to let values be
452 // copied to the right register if such a conflict exists nonetheless.
453 //
454 // These MOVs are also crucial in making sure the live intervals of phi srces
455 // are extended until the end of the loop, since they are not included in the
456 // live-in sets.
457 bool
458 RegAlloc::PhiMovesPass::visit(BasicBlock *bb)
459 {
460 Instruction *phi, *mov;
461
462 splitEdges(bb);
463
464 // insert MOVs (phi->src(j) should stem from j-th in-BB)
465 int j = 0;
466 for (Graph::EdgeIterator ei = bb->cfg.incident(); !ei.end(); ei.next()) {
467 BasicBlock *pb = BasicBlock::get(ei.getNode());
468 if (!pb->isTerminated())
469 pb->insertTail(new_FlowInstruction(func, OP_BRA, bb));
470
471 for (phi = bb->getPhi(); phi && phi->op == OP_PHI; phi = phi->next) {
472 LValue *tmp = new_LValue(func, phi->getDef(0)->asLValue());
473 mov = new_Instruction(func, OP_MOV, typeOfSize(tmp->reg.size));
474
475 mov->setSrc(0, phi->getSrc(j));
476 mov->setDef(0, tmp);
477 phi->setSrc(j, tmp);
478
479 pb->insertBefore(pb->getExit(), mov);
480 }
481 ++j;
482 }
483
484 return true;
485 }
486
487 bool
488 RegAlloc::ArgumentMovesPass::visit(BasicBlock *bb)
489 {
490 // Bind function call inputs/outputs to the same physical register
491 // the callee uses, inserting moves as appropriate for the case a
492 // conflict arises.
493 for (Instruction *i = bb->getEntry(); i; i = i->next) {
494 FlowInstruction *cal = i->asFlow();
495 // TODO: Handle indirect calls.
496 // Right now they should only be generated for builtins.
497 if (!cal || cal->op != OP_CALL || cal->builtin || cal->indirect)
498 continue;
499 RegisterSet clobberSet(prog->getTarget());
500
501 // Bind input values.
502 for (int s = cal->indirect ? 1 : 0; cal->srcExists(s); ++s) {
503 const int t = cal->indirect ? (s - 1) : s;
504 LValue *tmp = new_LValue(func, cal->getSrc(s)->asLValue());
505 tmp->reg.data.id = cal->target.fn->ins[t].rep()->reg.data.id;
506
507 Instruction *mov =
508 new_Instruction(func, OP_MOV, typeOfSize(tmp->reg.size));
509 mov->setDef(0, tmp);
510 mov->setSrc(0, cal->getSrc(s));
511 cal->setSrc(s, tmp);
512
513 bb->insertBefore(cal, mov);
514 }
515
516 // Bind output values.
517 for (int d = 0; cal->defExists(d); ++d) {
518 LValue *tmp = new_LValue(func, cal->getDef(d)->asLValue());
519 tmp->reg.data.id = cal->target.fn->outs[d].rep()->reg.data.id;
520
521 Instruction *mov =
522 new_Instruction(func, OP_MOV, typeOfSize(tmp->reg.size));
523 mov->setSrc(0, tmp);
524 mov->setDef(0, cal->getDef(d));
525 cal->setDef(d, tmp);
526
527 bb->insertAfter(cal, mov);
528 clobberSet.occupy(tmp);
529 }
530
531 // Bind clobbered values.
532 for (std::deque<Value *>::iterator it = cal->target.fn->clobbers.begin();
533 it != cal->target.fn->clobbers.end();
534 ++it) {
535 if (clobberSet.testOccupy(*it)) {
536 Value *tmp = new_LValue(func, (*it)->asLValue());
537 tmp->reg.data.id = (*it)->reg.data.id;
538 cal->setDef(cal->defCount(), tmp);
539 }
540 }
541 }
542
543 // Update the clobber set of the function.
544 if (BasicBlock::get(func->cfgExit) == bb) {
545 func->buildDefSets();
546 for (unsigned int i = 0; i < bb->defSet.getSize(); ++i)
547 if (bb->defSet.test(i))
548 func->clobbers.push_back(func->getLValue(i));
549 }
550
551 return true;
552 }
553
554 // Build the set of live-in variables of bb.
555 bool
556 RegAlloc::buildLiveSets(BasicBlock *bb)
557 {
558 Function *f = bb->getFunction();
559 BasicBlock *bn;
560 Instruction *i;
561 unsigned int s, d;
562
563 INFO_DBG(prog->dbgFlags, REG_ALLOC, "buildLiveSets(BB:%i)\n", bb->getId());
564
565 bb->liveSet.allocate(func->allLValues.getSize(), false);
566
567 int n = 0;
568 for (Graph::EdgeIterator ei = bb->cfg.outgoing(); !ei.end(); ei.next()) {
569 bn = BasicBlock::get(ei.getNode());
570 if (bn == bb)
571 continue;
572 if (bn->cfg.visit(sequence))
573 if (!buildLiveSets(bn))
574 return false;
575 if (n++ || bb->liveSet.marker)
576 bb->liveSet |= bn->liveSet;
577 else
578 bb->liveSet = bn->liveSet;
579 }
580 if (!n && !bb->liveSet.marker)
581 bb->liveSet.fill(0);
582 bb->liveSet.marker = true;
583
584 if (prog->dbgFlags & NV50_IR_DEBUG_REG_ALLOC) {
585 INFO("BB:%i live set of out blocks:\n", bb->getId());
586 bb->liveSet.print();
587 }
588
589 // if (!bb->getEntry())
590 // return true;
591
592 if (bb == BasicBlock::get(f->cfgExit)) {
593 for (std::deque<ValueRef>::iterator it = f->outs.begin();
594 it != f->outs.end(); ++it) {
595 assert(it->get()->asLValue());
596 bb->liveSet.set(it->get()->id);
597 }
598 }
599
600 for (i = bb->getExit(); i && i != bb->getEntry()->prev; i = i->prev) {
601 for (d = 0; i->defExists(d); ++d)
602 bb->liveSet.clr(i->getDef(d)->id);
603 for (s = 0; i->srcExists(s); ++s)
604 if (i->getSrc(s)->asLValue())
605 bb->liveSet.set(i->getSrc(s)->id);
606 }
607 for (i = bb->getPhi(); i && i->op == OP_PHI; i = i->next)
608 bb->liveSet.clr(i->getDef(0)->id);
609
610 if (prog->dbgFlags & NV50_IR_DEBUG_REG_ALLOC) {
611 INFO("BB:%i live set after propagation:\n", bb->getId());
612 bb->liveSet.print();
613 }
614
615 return true;
616 }
617
618 void
619 RegAlloc::BuildIntervalsPass::collectLiveValues(BasicBlock *bb)
620 {
621 BasicBlock *bbA = NULL, *bbB = NULL;
622
623 if (bb->cfg.outgoingCount()) {
624 // trickery to save a loop of OR'ing liveSets
625 // aliasing works fine with BitSet::setOr
626 for (Graph::EdgeIterator ei = bb->cfg.outgoing(); !ei.end(); ei.next()) {
627 if (ei.getType() == Graph::Edge::DUMMY)
628 continue;
629 if (bbA) {
630 bb->liveSet.setOr(&bbA->liveSet, &bbB->liveSet);
631 bbA = bb;
632 } else {
633 bbA = bbB;
634 }
635 bbB = BasicBlock::get(ei.getNode());
636 }
637 bb->liveSet.setOr(&bbB->liveSet, bbA ? &bbA->liveSet : NULL);
638 } else
639 if (bb->cfg.incidentCount()) {
640 bb->liveSet.fill(0);
641 }
642 }
643
644 bool
645 RegAlloc::BuildIntervalsPass::visit(BasicBlock *bb)
646 {
647 collectLiveValues(bb);
648
649 INFO_DBG(prog->dbgFlags, REG_ALLOC, "BuildIntervals(BB:%i)\n", bb->getId());
650
651 // go through out blocks and delete phi sources that do not originate from
652 // the current block from the live set
653 for (Graph::EdgeIterator ei = bb->cfg.outgoing(); !ei.end(); ei.next()) {
654 BasicBlock *out = BasicBlock::get(ei.getNode());
655
656 for (Instruction *i = out->getPhi(); i && i->op == OP_PHI; i = i->next) {
657 bb->liveSet.clr(i->getDef(0)->id);
658
659 for (int s = 0; i->srcExists(s); ++s) {
660 assert(i->src(s).getInsn());
661 if (i->getSrc(s)->getUniqueInsn()->bb == bb) // XXX: reachableBy ?
662 bb->liveSet.set(i->getSrc(s)->id);
663 else
664 bb->liveSet.clr(i->getSrc(s)->id);
665 }
666 }
667 }
668
669 // remaining live-outs are live until end
670 if (bb->getExit()) {
671 for (unsigned int j = 0; j < bb->liveSet.getSize(); ++j)
672 if (bb->liveSet.test(j))
673 addLiveRange(func->getLValue(j), bb, bb->getExit()->serial + 1);
674 }
675
676 for (Instruction *i = bb->getExit(); i && i->op != OP_PHI; i = i->prev) {
677 for (int d = 0; i->defExists(d); ++d) {
678 bb->liveSet.clr(i->getDef(d)->id);
679 if (i->getDef(d)->reg.data.id >= 0) // add hazard for fixed regs
680 i->getDef(d)->livei.extend(i->serial, i->serial);
681 }
682
683 for (int s = 0; i->srcExists(s); ++s) {
684 if (!i->getSrc(s)->asLValue())
685 continue;
686 if (!bb->liveSet.test(i->getSrc(s)->id)) {
687 bb->liveSet.set(i->getSrc(s)->id);
688 addLiveRange(i->getSrc(s), bb, i->serial);
689 }
690 }
691 }
692
693 if (bb == BasicBlock::get(func->cfg.getRoot())) {
694 for (std::deque<ValueDef>::iterator it = func->ins.begin();
695 it != func->ins.end(); ++it) {
696 if (it->get()->reg.data.id >= 0) // add hazard for fixed regs
697 it->get()->livei.extend(0, 1);
698 }
699 }
700
701 return true;
702 }
703
704
705 #define JOIN_MASK_PHI (1 << 0)
706 #define JOIN_MASK_UNION (1 << 1)
707 #define JOIN_MASK_MOV (1 << 2)
708 #define JOIN_MASK_TEX (1 << 3)
709
710 class GCRA
711 {
712 public:
713 GCRA(Function *, SpillCodeInserter&);
714 ~GCRA();
715
716 bool allocateRegisters(ArrayList& insns);
717
718 void printNodeInfo() const;
719
720 private:
721 class RIG_Node : public Graph::Node
722 {
723 public:
724 RIG_Node();
725
726 void init(const RegisterSet&, LValue *);
727
728 void addInterference(RIG_Node *);
729 void addRegPreference(RIG_Node *);
730
731 inline LValue *getValue() const
732 {
733 return reinterpret_cast<LValue *>(data);
734 }
735 inline void setValue(LValue *lval) { data = lval; }
736
737 inline uint8_t getCompMask() const
738 {
739 return ((1 << colors) - 1) << (reg & 7);
740 }
741
742 static inline RIG_Node *get(const Graph::EdgeIterator& ei)
743 {
744 return static_cast<RIG_Node *>(ei.getNode());
745 }
746
747 public:
748 uint32_t degree;
749 uint16_t degreeLimit; // if deg < degLimit, node is trivially colourable
750 uint16_t colors;
751
752 DataFile f;
753 int32_t reg;
754
755 float weight;
756
757 // list pointers for simplify() phase
758 RIG_Node *next;
759 RIG_Node *prev;
760
761 // union of the live intervals of all coalesced values (we want to retain
762 // the separate intervals for testing interference of compound values)
763 Interval livei;
764
765 std::list<RIG_Node *> prefRegs;
766 };
767
768 private:
769 inline RIG_Node *getNode(const LValue *v) const { return &nodes[v->id]; }
770
771 void buildRIG(ArrayList&);
772 bool coalesce(ArrayList&);
773 bool doCoalesce(ArrayList&, unsigned int mask);
774 void calculateSpillWeights();
775 bool simplify();
776 bool selectRegisters();
777 void cleanup(const bool success);
778
779 void simplifyEdge(RIG_Node *, RIG_Node *);
780 void simplifyNode(RIG_Node *);
781
782 bool coalesceValues(Value *, Value *, bool force);
783 void resolveSplitsAndMerges();
784 void makeCompound(Instruction *, bool isSplit);
785
786 inline void checkInterference(const RIG_Node *, Graph::EdgeIterator&);
787
788 inline void insertOrderedTail(std::list<RIG_Node *>&, RIG_Node *);
789 void checkList(std::list<RIG_Node *>&);
790
791 private:
792 std::stack<uint32_t> stack;
793
794 // list headers for simplify() phase
795 RIG_Node lo[2];
796 RIG_Node hi;
797
798 Graph RIG;
799 RIG_Node *nodes;
800 unsigned int nodeCount;
801
802 Function *func;
803 Program *prog;
804
805 static uint8_t relDegree[17][17];
806
807 RegisterSet regs;
808
809 // need to fixup register id for participants of OP_MERGE/SPLIT
810 std::list<Instruction *> merges;
811 std::list<Instruction *> splits;
812
813 SpillCodeInserter& spill;
814 std::list<ValuePair> mustSpill;
815 };
816
817 uint8_t GCRA::relDegree[17][17];
818
819 GCRA::RIG_Node::RIG_Node() : Node(NULL), next(this), prev(this)
820 {
821 colors = 0;
822 }
823
824 void
825 GCRA::printNodeInfo() const
826 {
827 for (unsigned int i = 0; i < nodeCount; ++i) {
828 if (!nodes[i].colors)
829 continue;
830 INFO("RIG_Node[%%%i]($[%u]%i): %u colors, weight %f, deg %u/%u\n X",
831 i,
832 nodes[i].f,nodes[i].reg,nodes[i].colors,
833 nodes[i].weight,
834 nodes[i].degree, nodes[i].degreeLimit);
835
836 for (Graph::EdgeIterator ei = nodes[i].outgoing(); !ei.end(); ei.next())
837 INFO(" %%%i", RIG_Node::get(ei)->getValue()->id);
838 for (Graph::EdgeIterator ei = nodes[i].incident(); !ei.end(); ei.next())
839 INFO(" %%%i", RIG_Node::get(ei)->getValue()->id);
840 INFO("\n");
841 }
842 }
843
844 static bool
845 isShortRegOp(Instruction *insn)
846 {
847 // Immediates are always in src1 (except zeroes, which end up getting
848 // replaced with a zero reg). Every other situation can be resolved by
849 // using a long encoding.
850 return insn->srcExists(1) && insn->src(1).getFile() == FILE_IMMEDIATE &&
851 insn->getSrc(1)->reg.data.u64;
852 }
853
854 // Check if this LValue is ever used in an instruction that can't be encoded
855 // with long registers (i.e. > r63)
856 static bool
857 isShortRegVal(LValue *lval)
858 {
859 if (lval->getInsn() == NULL)
860 return false;
861 for (Value::DefCIterator def = lval->defs.begin();
862 def != lval->defs.end(); ++def)
863 if (isShortRegOp((*def)->getInsn()))
864 return true;
865 for (Value::UseCIterator use = lval->uses.begin();
866 use != lval->uses.end(); ++use)
867 if (isShortRegOp((*use)->getInsn()))
868 return true;
869 return false;
870 }
871
872 void
873 GCRA::RIG_Node::init(const RegisterSet& regs, LValue *lval)
874 {
875 setValue(lval);
876 if (lval->reg.data.id >= 0)
877 lval->noSpill = lval->fixedReg = 1;
878
879 colors = regs.units(lval->reg.file, lval->reg.size);
880 f = lval->reg.file;
881 reg = -1;
882 if (lval->reg.data.id >= 0)
883 reg = regs.idToUnits(lval);
884
885 weight = std::numeric_limits<float>::infinity();
886 degree = 0;
887 int size = regs.getFileSize(f);
888 // On nv50, we lose a bit of gpr encoding when there's an embedded
889 // immediate.
890 if (regs.restrictedGPR16Range && f == FILE_GPR && (lval->reg.size == 2 || isShortRegVal(lval)))
891 size /= 2;
892 degreeLimit = size;
893 degreeLimit -= relDegree[1][colors] - 1;
894
895 livei.insert(lval->livei);
896 }
897
898 bool
899 GCRA::coalesceValues(Value *dst, Value *src, bool force)
900 {
901 LValue *rep = dst->join->asLValue();
902 LValue *val = src->join->asLValue();
903
904 if (!force && val->reg.data.id >= 0) {
905 rep = src->join->asLValue();
906 val = dst->join->asLValue();
907 }
908 RIG_Node *nRep = &nodes[rep->id];
909 RIG_Node *nVal = &nodes[val->id];
910
911 if (src->reg.file != dst->reg.file) {
912 if (!force)
913 return false;
914 WARN("forced coalescing of values in different files !\n");
915 }
916 if (!force && dst->reg.size != src->reg.size)
917 return false;
918
919 if ((rep->reg.data.id >= 0) && (rep->reg.data.id != val->reg.data.id)) {
920 if (force) {
921 if (val->reg.data.id >= 0)
922 WARN("forced coalescing of values in different fixed regs !\n");
923 } else {
924 if (val->reg.data.id >= 0)
925 return false;
926 // make sure that there is no overlap with the fixed register of rep
927 for (ArrayList::Iterator it = func->allLValues.iterator();
928 !it.end(); it.next()) {
929 Value *reg = reinterpret_cast<Value *>(it.get())->asLValue();
930 assert(reg);
931 if (reg->interfers(rep) && reg->livei.overlaps(nVal->livei))
932 return false;
933 }
934 }
935 }
936
937 if (!force && nRep->livei.overlaps(nVal->livei))
938 return false;
939
940 INFO_DBG(prog->dbgFlags, REG_ALLOC, "joining %%%i($%i) <- %%%i\n",
941 rep->id, rep->reg.data.id, val->id);
942
943 // set join pointer of all values joined with val
944 for (Value::DefIterator def = val->defs.begin(); def != val->defs.end();
945 ++def)
946 (*def)->get()->join = rep;
947 assert(rep->join == rep && val->join == rep);
948
949 // add val's definitions to rep and extend the live interval of its RIG node
950 rep->defs.insert(rep->defs.end(), val->defs.begin(), val->defs.end());
951 nRep->livei.unify(nVal->livei);
952 return true;
953 }
954
955 bool
956 GCRA::coalesce(ArrayList& insns)
957 {
958 bool ret = doCoalesce(insns, JOIN_MASK_PHI);
959 if (!ret)
960 return false;
961 switch (func->getProgram()->getTarget()->getChipset() & ~0xf) {
962 case 0x50:
963 case 0x80:
964 case 0x90:
965 case 0xa0:
966 ret = doCoalesce(insns, JOIN_MASK_UNION | JOIN_MASK_TEX);
967 break;
968 case 0xc0:
969 case 0xd0:
970 case 0xe0:
971 case 0xf0:
972 case 0x100:
973 case 0x110:
974 case 0x120:
975 case 0x130:
976 ret = doCoalesce(insns, JOIN_MASK_UNION);
977 break;
978 default:
979 break;
980 }
981 if (!ret)
982 return false;
983 return doCoalesce(insns, JOIN_MASK_MOV);
984 }
985
986 static inline uint8_t makeCompMask(int compSize, int base, int size)
987 {
988 uint8_t m = ((1 << size) - 1) << base;
989
990 switch (compSize) {
991 case 1:
992 return 0xff;
993 case 2:
994 m |= (m << 2);
995 return (m << 4) | m;
996 case 3:
997 case 4:
998 return (m << 4) | m;
999 default:
1000 assert(compSize <= 8);
1001 return m;
1002 }
1003 }
1004
1005 // Used when coalescing moves. The non-compound value will become one, e.g.:
1006 // mov b32 $r0 $r2 / merge b64 $r0d { $r0 $r1 }
1007 // split b64 { $r0 $r1 } $r0d / mov b64 $r0d f64 $r2d
1008 static inline void copyCompound(Value *dst, Value *src)
1009 {
1010 LValue *ldst = dst->asLValue();
1011 LValue *lsrc = src->asLValue();
1012
1013 if (ldst->compound && !lsrc->compound) {
1014 LValue *swap = lsrc;
1015 lsrc = ldst;
1016 ldst = swap;
1017 }
1018
1019 ldst->compound = lsrc->compound;
1020 ldst->compMask = lsrc->compMask;
1021 }
1022
1023 void
1024 GCRA::makeCompound(Instruction *insn, bool split)
1025 {
1026 LValue *rep = (split ? insn->getSrc(0) : insn->getDef(0))->asLValue();
1027
1028 if (prog->dbgFlags & NV50_IR_DEBUG_REG_ALLOC) {
1029 INFO("makeCompound(split = %i): ", split);
1030 insn->print();
1031 }
1032
1033 const unsigned int size = getNode(rep)->colors;
1034 unsigned int base = 0;
1035
1036 if (!rep->compound)
1037 rep->compMask = 0xff;
1038 rep->compound = 1;
1039
1040 for (int c = 0; split ? insn->defExists(c) : insn->srcExists(c); ++c) {
1041 LValue *val = (split ? insn->getDef(c) : insn->getSrc(c))->asLValue();
1042
1043 val->compound = 1;
1044 if (!val->compMask)
1045 val->compMask = 0xff;
1046 val->compMask &= makeCompMask(size, base, getNode(val)->colors);
1047 assert(val->compMask);
1048
1049 INFO_DBG(prog->dbgFlags, REG_ALLOC, "compound: %%%i:%02x <- %%%i:%02x\n",
1050 rep->id, rep->compMask, val->id, val->compMask);
1051
1052 base += getNode(val)->colors;
1053 }
1054 assert(base == size);
1055 }
1056
1057 bool
1058 GCRA::doCoalesce(ArrayList& insns, unsigned int mask)
1059 {
1060 int c, n;
1061
1062 for (n = 0; n < insns.getSize(); ++n) {
1063 Instruction *i;
1064 Instruction *insn = reinterpret_cast<Instruction *>(insns.get(n));
1065
1066 switch (insn->op) {
1067 case OP_PHI:
1068 if (!(mask & JOIN_MASK_PHI))
1069 break;
1070 for (c = 0; insn->srcExists(c); ++c)
1071 if (!coalesceValues(insn->getDef(0), insn->getSrc(c), false)) {
1072 // this is bad
1073 ERROR("failed to coalesce phi operands\n");
1074 return false;
1075 }
1076 break;
1077 case OP_UNION:
1078 case OP_MERGE:
1079 if (!(mask & JOIN_MASK_UNION))
1080 break;
1081 for (c = 0; insn->srcExists(c); ++c)
1082 coalesceValues(insn->getDef(0), insn->getSrc(c), true);
1083 if (insn->op == OP_MERGE) {
1084 merges.push_back(insn);
1085 if (insn->srcExists(1))
1086 makeCompound(insn, false);
1087 }
1088 break;
1089 case OP_SPLIT:
1090 if (!(mask & JOIN_MASK_UNION))
1091 break;
1092 splits.push_back(insn);
1093 for (c = 0; insn->defExists(c); ++c)
1094 coalesceValues(insn->getSrc(0), insn->getDef(c), true);
1095 makeCompound(insn, true);
1096 break;
1097 case OP_MOV:
1098 if (!(mask & JOIN_MASK_MOV))
1099 break;
1100 i = NULL;
1101 if (!insn->getDef(0)->uses.empty())
1102 i = (*insn->getDef(0)->uses.begin())->getInsn();
1103 // if this is a contraint-move there will only be a single use
1104 if (i && i->op == OP_MERGE) // do we really still need this ?
1105 break;
1106 i = insn->getSrc(0)->getUniqueInsn();
1107 if (i && !i->constrainedDefs()) {
1108 if (coalesceValues(insn->getDef(0), insn->getSrc(0), false))
1109 copyCompound(insn->getSrc(0), insn->getDef(0));
1110 }
1111 break;
1112 case OP_TEX:
1113 case OP_TXB:
1114 case OP_TXL:
1115 case OP_TXF:
1116 case OP_TXQ:
1117 case OP_TXD:
1118 case OP_TXG:
1119 case OP_TXLQ:
1120 case OP_TEXCSAA:
1121 case OP_TEXPREP:
1122 if (!(mask & JOIN_MASK_TEX))
1123 break;
1124 for (c = 0; insn->srcExists(c) && c != insn->predSrc; ++c)
1125 coalesceValues(insn->getDef(c), insn->getSrc(c), true);
1126 break;
1127 default:
1128 break;
1129 }
1130 }
1131 return true;
1132 }
1133
1134 void
1135 GCRA::RIG_Node::addInterference(RIG_Node *node)
1136 {
1137 this->degree += relDegree[node->colors][colors];
1138 node->degree += relDegree[colors][node->colors];
1139
1140 this->attach(node, Graph::Edge::CROSS);
1141 }
1142
1143 void
1144 GCRA::RIG_Node::addRegPreference(RIG_Node *node)
1145 {
1146 prefRegs.push_back(node);
1147 }
1148
1149 GCRA::GCRA(Function *fn, SpillCodeInserter& spill) :
1150 func(fn),
1151 regs(fn->getProgram()->getTarget()),
1152 spill(spill)
1153 {
1154 prog = func->getProgram();
1155
1156 // initialize relative degrees array - i takes away from j
1157 for (int i = 1; i <= 16; ++i)
1158 for (int j = 1; j <= 16; ++j)
1159 relDegree[i][j] = j * ((i + j - 1) / j);
1160 }
1161
1162 GCRA::~GCRA()
1163 {
1164 if (nodes)
1165 delete[] nodes;
1166 }
1167
1168 void
1169 GCRA::checkList(std::list<RIG_Node *>& lst)
1170 {
1171 GCRA::RIG_Node *prev = NULL;
1172
1173 for (std::list<RIG_Node *>::iterator it = lst.begin();
1174 it != lst.end();
1175 ++it) {
1176 assert((*it)->getValue()->join == (*it)->getValue());
1177 if (prev)
1178 assert(prev->livei.begin() <= (*it)->livei.begin());
1179 prev = *it;
1180 }
1181 }
1182
1183 void
1184 GCRA::insertOrderedTail(std::list<RIG_Node *>& list, RIG_Node *node)
1185 {
1186 if (node->livei.isEmpty())
1187 return;
1188 // only the intervals of joined values don't necessarily arrive in order
1189 std::list<RIG_Node *>::iterator prev, it;
1190 for (it = list.end(); it != list.begin(); it = prev) {
1191 prev = it;
1192 --prev;
1193 if ((*prev)->livei.begin() <= node->livei.begin())
1194 break;
1195 }
1196 list.insert(it, node);
1197 }
1198
1199 void
1200 GCRA::buildRIG(ArrayList& insns)
1201 {
1202 std::list<RIG_Node *> values, active;
1203
1204 for (std::deque<ValueDef>::iterator it = func->ins.begin();
1205 it != func->ins.end(); ++it)
1206 insertOrderedTail(values, getNode(it->get()->asLValue()));
1207
1208 for (int i = 0; i < insns.getSize(); ++i) {
1209 Instruction *insn = reinterpret_cast<Instruction *>(insns.get(i));
1210 for (int d = 0; insn->defExists(d); ++d)
1211 if (insn->getDef(d)->rep() == insn->getDef(d))
1212 insertOrderedTail(values, getNode(insn->getDef(d)->asLValue()));
1213 }
1214 checkList(values);
1215
1216 while (!values.empty()) {
1217 RIG_Node *cur = values.front();
1218
1219 for (std::list<RIG_Node *>::iterator it = active.begin();
1220 it != active.end();) {
1221 RIG_Node *node = *it;
1222
1223 if (node->livei.end() <= cur->livei.begin()) {
1224 it = active.erase(it);
1225 } else {
1226 if (node->f == cur->f && node->livei.overlaps(cur->livei))
1227 cur->addInterference(node);
1228 ++it;
1229 }
1230 }
1231 values.pop_front();
1232 active.push_back(cur);
1233 }
1234 }
1235
1236 void
1237 GCRA::calculateSpillWeights()
1238 {
1239 for (unsigned int i = 0; i < nodeCount; ++i) {
1240 RIG_Node *const n = &nodes[i];
1241 if (!nodes[i].colors || nodes[i].livei.isEmpty())
1242 continue;
1243 if (nodes[i].reg >= 0) {
1244 // update max reg
1245 regs.occupy(n->f, n->reg, n->colors);
1246 continue;
1247 }
1248 LValue *val = nodes[i].getValue();
1249
1250 if (!val->noSpill) {
1251 int rc = 0;
1252 for (Value::DefIterator it = val->defs.begin();
1253 it != val->defs.end();
1254 ++it)
1255 rc += (*it)->get()->refCount();
1256
1257 nodes[i].weight =
1258 (float)rc * (float)rc / (float)nodes[i].livei.extent();
1259 }
1260
1261 if (nodes[i].degree < nodes[i].degreeLimit) {
1262 int l = 0;
1263 if (val->reg.size > 4)
1264 l = 1;
1265 DLLIST_ADDHEAD(&lo[l], &nodes[i]);
1266 } else {
1267 DLLIST_ADDHEAD(&hi, &nodes[i]);
1268 }
1269 }
1270 if (prog->dbgFlags & NV50_IR_DEBUG_REG_ALLOC)
1271 printNodeInfo();
1272 }
1273
1274 void
1275 GCRA::simplifyEdge(RIG_Node *a, RIG_Node *b)
1276 {
1277 bool move = b->degree >= b->degreeLimit;
1278
1279 INFO_DBG(prog->dbgFlags, REG_ALLOC,
1280 "edge: (%%%i, deg %u/%u) >-< (%%%i, deg %u/%u)\n",
1281 a->getValue()->id, a->degree, a->degreeLimit,
1282 b->getValue()->id, b->degree, b->degreeLimit);
1283
1284 b->degree -= relDegree[a->colors][b->colors];
1285
1286 move = move && b->degree < b->degreeLimit;
1287 if (move && !DLLIST_EMPTY(b)) {
1288 int l = (b->getValue()->reg.size > 4) ? 1 : 0;
1289 DLLIST_DEL(b);
1290 DLLIST_ADDTAIL(&lo[l], b);
1291 }
1292 }
1293
1294 void
1295 GCRA::simplifyNode(RIG_Node *node)
1296 {
1297 for (Graph::EdgeIterator ei = node->outgoing(); !ei.end(); ei.next())
1298 simplifyEdge(node, RIG_Node::get(ei));
1299
1300 for (Graph::EdgeIterator ei = node->incident(); !ei.end(); ei.next())
1301 simplifyEdge(node, RIG_Node::get(ei));
1302
1303 DLLIST_DEL(node);
1304 stack.push(node->getValue()->id);
1305
1306 INFO_DBG(prog->dbgFlags, REG_ALLOC, "SIMPLIFY: pushed %%%i%s\n",
1307 node->getValue()->id,
1308 (node->degree < node->degreeLimit) ? "" : "(spill)");
1309 }
1310
1311 bool
1312 GCRA::simplify()
1313 {
1314 for (;;) {
1315 if (!DLLIST_EMPTY(&lo[0])) {
1316 do {
1317 simplifyNode(lo[0].next);
1318 } while (!DLLIST_EMPTY(&lo[0]));
1319 } else
1320 if (!DLLIST_EMPTY(&lo[1])) {
1321 simplifyNode(lo[1].next);
1322 } else
1323 if (!DLLIST_EMPTY(&hi)) {
1324 RIG_Node *best = hi.next;
1325 float bestScore = best->weight / (float)best->degree;
1326 // spill candidate
1327 for (RIG_Node *it = best->next; it != &hi; it = it->next) {
1328 float score = it->weight / (float)it->degree;
1329 if (score < bestScore) {
1330 best = it;
1331 bestScore = score;
1332 }
1333 }
1334 if (isinf(bestScore)) {
1335 ERROR("no viable spill candidates left\n");
1336 return false;
1337 }
1338 simplifyNode(best);
1339 } else {
1340 return true;
1341 }
1342 }
1343 }
1344
1345 void
1346 GCRA::checkInterference(const RIG_Node *node, Graph::EdgeIterator& ei)
1347 {
1348 const RIG_Node *intf = RIG_Node::get(ei);
1349
1350 if (intf->reg < 0)
1351 return;
1352 const LValue *vA = node->getValue();
1353 const LValue *vB = intf->getValue();
1354
1355 const uint8_t intfMask = ((1 << intf->colors) - 1) << (intf->reg & 7);
1356
1357 if (vA->compound | vB->compound) {
1358 // NOTE: this only works for >aligned< register tuples !
1359 for (Value::DefCIterator D = vA->defs.begin(); D != vA->defs.end(); ++D) {
1360 for (Value::DefCIterator d = vB->defs.begin(); d != vB->defs.end(); ++d) {
1361 const LValue *vD = (*D)->get()->asLValue();
1362 const LValue *vd = (*d)->get()->asLValue();
1363
1364 if (!vD->livei.overlaps(vd->livei)) {
1365 INFO_DBG(prog->dbgFlags, REG_ALLOC, "(%%%i) X (%%%i): no overlap\n",
1366 vD->id, vd->id);
1367 continue;
1368 }
1369
1370 uint8_t mask = vD->compound ? vD->compMask : ~0;
1371 if (vd->compound) {
1372 assert(vB->compound);
1373 mask &= vd->compMask & vB->compMask;
1374 } else {
1375 mask &= intfMask;
1376 }
1377
1378 INFO_DBG(prog->dbgFlags, REG_ALLOC,
1379 "(%%%i)%02x X (%%%i)%02x & %02x: $r%i.%02x\n",
1380 vD->id,
1381 vD->compound ? vD->compMask : 0xff,
1382 vd->id,
1383 vd->compound ? vd->compMask : intfMask,
1384 vB->compMask, intf->reg & ~7, mask);
1385 if (mask)
1386 regs.occupyMask(node->f, intf->reg & ~7, mask);
1387 }
1388 }
1389 } else {
1390 INFO_DBG(prog->dbgFlags, REG_ALLOC,
1391 "(%%%i) X (%%%i): $r%i + %u\n",
1392 vA->id, vB->id, intf->reg, intf->colors);
1393 regs.occupy(node->f, intf->reg, intf->colors);
1394 }
1395 }
1396
1397 bool
1398 GCRA::selectRegisters()
1399 {
1400 INFO_DBG(prog->dbgFlags, REG_ALLOC, "\nSELECT phase\n");
1401
1402 while (!stack.empty()) {
1403 RIG_Node *node = &nodes[stack.top()];
1404 stack.pop();
1405
1406 regs.reset(node->f);
1407
1408 INFO_DBG(prog->dbgFlags, REG_ALLOC, "\nNODE[%%%i, %u colors]\n",
1409 node->getValue()->id, node->colors);
1410
1411 for (Graph::EdgeIterator ei = node->outgoing(); !ei.end(); ei.next())
1412 checkInterference(node, ei);
1413 for (Graph::EdgeIterator ei = node->incident(); !ei.end(); ei.next())
1414 checkInterference(node, ei);
1415
1416 if (!node->prefRegs.empty()) {
1417 for (std::list<RIG_Node *>::const_iterator it = node->prefRegs.begin();
1418 it != node->prefRegs.end();
1419 ++it) {
1420 if ((*it)->reg >= 0 &&
1421 regs.testOccupy(node->f, (*it)->reg, node->colors)) {
1422 node->reg = (*it)->reg;
1423 break;
1424 }
1425 }
1426 }
1427 if (node->reg >= 0)
1428 continue;
1429 LValue *lval = node->getValue();
1430 if (prog->dbgFlags & NV50_IR_DEBUG_REG_ALLOC)
1431 regs.print(node->f);
1432 bool ret = regs.assign(node->reg, node->f, node->colors);
1433 if (ret) {
1434 INFO_DBG(prog->dbgFlags, REG_ALLOC, "assigned reg %i\n", node->reg);
1435 lval->compMask = node->getCompMask();
1436 } else {
1437 INFO_DBG(prog->dbgFlags, REG_ALLOC, "must spill: %%%i (size %u)\n",
1438 lval->id, lval->reg.size);
1439 Symbol *slot = NULL;
1440 if (lval->reg.file == FILE_GPR)
1441 slot = spill.assignSlot(node->livei, lval->reg.size);
1442 mustSpill.push_back(ValuePair(lval, slot));
1443 }
1444 }
1445 if (!mustSpill.empty())
1446 return false;
1447 for (unsigned int i = 0; i < nodeCount; ++i) {
1448 LValue *lval = nodes[i].getValue();
1449 if (nodes[i].reg >= 0 && nodes[i].colors > 0)
1450 lval->reg.data.id =
1451 regs.unitsToId(nodes[i].f, nodes[i].reg, lval->reg.size);
1452 }
1453 return true;
1454 }
1455
1456 bool
1457 GCRA::allocateRegisters(ArrayList& insns)
1458 {
1459 bool ret;
1460
1461 INFO_DBG(prog->dbgFlags, REG_ALLOC,
1462 "allocateRegisters to %u instructions\n", insns.getSize());
1463
1464 nodeCount = func->allLValues.getSize();
1465 nodes = new RIG_Node[nodeCount];
1466 if (!nodes)
1467 return false;
1468 for (unsigned int i = 0; i < nodeCount; ++i) {
1469 LValue *lval = reinterpret_cast<LValue *>(func->allLValues.get(i));
1470 if (lval) {
1471 nodes[i].init(regs, lval);
1472 RIG.insert(&nodes[i]);
1473
1474 if (lval->inFile(FILE_GPR) && lval->getInsn() != NULL) {
1475 Instruction *insn = lval->getInsn();
1476 if (insn->op != OP_MAD && insn->op != OP_FMA && insn->op != OP_SAD)
1477 continue;
1478 // For both of the cases below, we only want to add the preference
1479 // if all arguments are in registers.
1480 if (insn->src(0).getFile() != FILE_GPR ||
1481 insn->src(1).getFile() != FILE_GPR ||
1482 insn->src(2).getFile() != FILE_GPR)
1483 continue;
1484 if (prog->getTarget()->getChipset() < 0xc0) {
1485 // Outputting a flag is not supported with short encodings nor
1486 // with immediate arguments.
1487 // See handleMADforNV50.
1488 if (insn->flagsDef >= 0)
1489 continue;
1490 } else {
1491 // We can only fold immediate arguments if dst == src2. This
1492 // only matters if one of the first two arguments is an
1493 // immediate. This form is also only supported for floats.
1494 // See handleMADforNVC0.
1495 ImmediateValue imm;
1496 if (insn->dType != TYPE_F32)
1497 continue;
1498 if (!insn->src(0).getImmediate(imm) &&
1499 !insn->src(1).getImmediate(imm))
1500 continue;
1501 }
1502
1503 nodes[i].addRegPreference(getNode(insn->getSrc(2)->asLValue()));
1504 }
1505 }
1506 }
1507
1508 // coalesce first, we use only 1 RIG node for a group of joined values
1509 ret = coalesce(insns);
1510 if (!ret)
1511 goto out;
1512
1513 if (func->getProgram()->dbgFlags & NV50_IR_DEBUG_REG_ALLOC)
1514 func->printLiveIntervals();
1515
1516 buildRIG(insns);
1517 calculateSpillWeights();
1518 ret = simplify();
1519 if (!ret)
1520 goto out;
1521
1522 ret = selectRegisters();
1523 if (!ret) {
1524 INFO_DBG(prog->dbgFlags, REG_ALLOC,
1525 "selectRegisters failed, inserting spill code ...\n");
1526 regs.reset(FILE_GPR, true);
1527 spill.run(mustSpill);
1528 if (prog->dbgFlags & NV50_IR_DEBUG_REG_ALLOC)
1529 func->print();
1530 } else {
1531 prog->maxGPR = std::max(prog->maxGPR, regs.getMaxAssigned(FILE_GPR));
1532 }
1533
1534 out:
1535 cleanup(ret);
1536 return ret;
1537 }
1538
1539 void
1540 GCRA::cleanup(const bool success)
1541 {
1542 mustSpill.clear();
1543
1544 for (ArrayList::Iterator it = func->allLValues.iterator();
1545 !it.end(); it.next()) {
1546 LValue *lval = reinterpret_cast<LValue *>(it.get());
1547
1548 lval->livei.clear();
1549
1550 lval->compound = 0;
1551 lval->compMask = 0;
1552
1553 if (lval->join == lval)
1554 continue;
1555
1556 if (success) {
1557 lval->reg.data.id = lval->join->reg.data.id;
1558 } else {
1559 for (Value::DefIterator d = lval->defs.begin(); d != lval->defs.end();
1560 ++d)
1561 lval->join->defs.remove(*d);
1562 lval->join = lval;
1563 }
1564 }
1565
1566 if (success)
1567 resolveSplitsAndMerges();
1568 splits.clear(); // avoid duplicate entries on next coalesce pass
1569 merges.clear();
1570
1571 delete[] nodes;
1572 nodes = NULL;
1573 hi.next = hi.prev = &hi;
1574 lo[0].next = lo[0].prev = &lo[0];
1575 lo[1].next = lo[1].prev = &lo[1];
1576 }
1577
1578 Symbol *
1579 SpillCodeInserter::assignSlot(const Interval &livei, const unsigned int size)
1580 {
1581 SpillSlot slot;
1582 int32_t offsetBase = stackSize;
1583 int32_t offset;
1584 std::list<SpillSlot>::iterator pos = slots.end(), it = slots.begin();
1585
1586 if (offsetBase % size)
1587 offsetBase += size - (offsetBase % size);
1588
1589 slot.sym = NULL;
1590
1591 for (offset = offsetBase; offset < stackSize; offset += size) {
1592 const int32_t entryEnd = offset + size;
1593 while (it != slots.end() && it->offset < offset)
1594 ++it;
1595 if (it == slots.end()) // no slots left
1596 break;
1597 std::list<SpillSlot>::iterator bgn = it;
1598
1599 while (it != slots.end() && it->offset < entryEnd) {
1600 it->occup.print();
1601 if (it->occup.overlaps(livei))
1602 break;
1603 ++it;
1604 }
1605 if (it == slots.end() || it->offset >= entryEnd) {
1606 // fits
1607 for (; bgn != slots.end() && bgn->offset < entryEnd; ++bgn) {
1608 bgn->occup.insert(livei);
1609 if (bgn->size() == size)
1610 slot.sym = bgn->sym;
1611 }
1612 break;
1613 }
1614 }
1615 if (!slot.sym) {
1616 stackSize = offset + size;
1617 slot.offset = offset;
1618 slot.sym = new_Symbol(func->getProgram(), FILE_MEMORY_LOCAL);
1619 if (!func->stackPtr)
1620 offset += func->tlsBase;
1621 slot.sym->setAddress(NULL, offset);
1622 slot.sym->reg.size = size;
1623 slots.insert(pos, slot)->occup.insert(livei);
1624 }
1625 return slot.sym;
1626 }
1627
1628 Value *
1629 SpillCodeInserter::offsetSlot(Value *base, const LValue *lval)
1630 {
1631 if (!lval->compound || (lval->compMask & 0x1))
1632 return base;
1633 Value *slot = cloneShallow(func, base);
1634
1635 slot->reg.data.offset += (ffs(lval->compMask) - 1) * lval->reg.size;
1636 slot->reg.size = lval->reg.size;
1637
1638 return slot;
1639 }
1640
1641 void
1642 SpillCodeInserter::spill(Instruction *defi, Value *slot, LValue *lval)
1643 {
1644 const DataType ty = typeOfSize(lval->reg.size);
1645
1646 slot = offsetSlot(slot, lval);
1647
1648 Instruction *st;
1649 if (slot->reg.file == FILE_MEMORY_LOCAL) {
1650 lval->noSpill = 1;
1651 if (ty != TYPE_B96) {
1652 st = new_Instruction(func, OP_STORE, ty);
1653 st->setSrc(0, slot);
1654 st->setSrc(1, lval);
1655 } else {
1656 st = new_Instruction(func, OP_SPLIT, ty);
1657 st->setSrc(0, lval);
1658 for (int d = 0; d < lval->reg.size / 4; ++d)
1659 st->setDef(d, new_LValue(func, FILE_GPR));
1660
1661 for (int d = lval->reg.size / 4 - 1; d >= 0; --d) {
1662 Value *tmp = cloneShallow(func, slot);
1663 tmp->reg.size = 4;
1664 tmp->reg.data.offset += 4 * d;
1665
1666 Instruction *s = new_Instruction(func, OP_STORE, TYPE_U32);
1667 s->setSrc(0, tmp);
1668 s->setSrc(1, st->getDef(d));
1669 defi->bb->insertAfter(defi, s);
1670 }
1671 }
1672 } else {
1673 st = new_Instruction(func, OP_CVT, ty);
1674 st->setDef(0, slot);
1675 st->setSrc(0, lval);
1676 if (lval->reg.file == FILE_FLAGS)
1677 st->flagsSrc = 0;
1678 }
1679 defi->bb->insertAfter(defi, st);
1680 }
1681
1682 LValue *
1683 SpillCodeInserter::unspill(Instruction *usei, LValue *lval, Value *slot)
1684 {
1685 const DataType ty = typeOfSize(lval->reg.size);
1686
1687 slot = offsetSlot(slot, lval);
1688 lval = cloneShallow(func, lval);
1689
1690 Instruction *ld;
1691 if (slot->reg.file == FILE_MEMORY_LOCAL) {
1692 lval->noSpill = 1;
1693 if (ty != TYPE_B96) {
1694 ld = new_Instruction(func, OP_LOAD, ty);
1695 } else {
1696 ld = new_Instruction(func, OP_MERGE, ty);
1697 for (int d = 0; d < lval->reg.size / 4; ++d) {
1698 Value *tmp = cloneShallow(func, slot);
1699 LValue *val;
1700 tmp->reg.size = 4;
1701 tmp->reg.data.offset += 4 * d;
1702
1703 Instruction *l = new_Instruction(func, OP_LOAD, TYPE_U32);
1704 l->setDef(0, (val = new_LValue(func, FILE_GPR)));
1705 l->setSrc(0, tmp);
1706 usei->bb->insertBefore(usei, l);
1707 ld->setSrc(d, val);
1708 val->noSpill = 1;
1709 }
1710 ld->setDef(0, lval);
1711 usei->bb->insertBefore(usei, ld);
1712 return lval;
1713 }
1714 } else {
1715 ld = new_Instruction(func, OP_CVT, ty);
1716 }
1717 ld->setDef(0, lval);
1718 ld->setSrc(0, slot);
1719 if (lval->reg.file == FILE_FLAGS)
1720 ld->flagsDef = 0;
1721
1722 usei->bb->insertBefore(usei, ld);
1723 return lval;
1724 }
1725
1726 static bool
1727 value_cmp(ValueRef *a, ValueRef *b) {
1728 Instruction *ai = a->getInsn(), *bi = b->getInsn();
1729 if (ai->bb != bi->bb)
1730 return ai->bb->getId() < bi->bb->getId();
1731 return ai->serial < bi->serial;
1732 }
1733
1734 // For each value that is to be spilled, go through all its definitions.
1735 // A value can have multiple definitions if it has been coalesced before.
1736 // For each definition, first go through all its uses and insert an unspill
1737 // instruction before it, then replace the use with the temporary register.
1738 // Unspill can be either a load from memory or simply a move to another
1739 // register file.
1740 // For "Pseudo" instructions (like PHI, SPLIT, MERGE) we can erase the use
1741 // if we have spilled to a memory location, or simply with the new register.
1742 // No load or conversion instruction should be needed.
1743 bool
1744 SpillCodeInserter::run(const std::list<ValuePair>& lst)
1745 {
1746 for (std::list<ValuePair>::const_iterator it = lst.begin(); it != lst.end();
1747 ++it) {
1748 LValue *lval = it->first->asLValue();
1749 Symbol *mem = it->second ? it->second->asSym() : NULL;
1750
1751 // Keep track of which instructions to delete later. Deleting them
1752 // inside the loop is unsafe since a single instruction may have
1753 // multiple destinations that all need to be spilled (like OP_SPLIT).
1754 unordered_set<Instruction *> to_del;
1755
1756 for (Value::DefIterator d = lval->defs.begin(); d != lval->defs.end();
1757 ++d) {
1758 Value *slot = mem ?
1759 static_cast<Value *>(mem) : new_LValue(func, FILE_GPR);
1760 Value *tmp = NULL;
1761 Instruction *last = NULL;
1762
1763 LValue *dval = (*d)->get()->asLValue();
1764 Instruction *defi = (*d)->getInsn();
1765
1766 // Sort all the uses by BB/instruction so that we don't unspill
1767 // multiple times in a row, and also remove a source of
1768 // non-determinism.
1769 std::vector<ValueRef *> refs(dval->uses.begin(), dval->uses.end());
1770 std::sort(refs.begin(), refs.end(), value_cmp);
1771
1772 // Unspill at each use *before* inserting spill instructions,
1773 // we don't want to have the spill instructions in the use list here.
1774 for (std::vector<ValueRef*>::const_iterator it = refs.begin();
1775 it != refs.end(); ++it) {
1776 ValueRef *u = *it;
1777 Instruction *usei = u->getInsn();
1778 assert(usei);
1779 if (usei->isPseudo()) {
1780 tmp = (slot->reg.file == FILE_MEMORY_LOCAL) ? NULL : slot;
1781 last = NULL;
1782 } else {
1783 if (!last || (usei != last->next && usei != last))
1784 tmp = unspill(usei, dval, slot);
1785 last = usei;
1786 }
1787 u->set(tmp);
1788 }
1789
1790 assert(defi);
1791 if (defi->isPseudo()) {
1792 d = lval->defs.erase(d);
1793 --d;
1794 if (slot->reg.file == FILE_MEMORY_LOCAL)
1795 to_del.insert(defi);
1796 else
1797 defi->setDef(0, slot);
1798 } else {
1799 spill(defi, slot, dval);
1800 }
1801 }
1802
1803 for (unordered_set<Instruction *>::const_iterator it = to_del.begin();
1804 it != to_del.end(); ++it)
1805 delete_Instruction(func->getProgram(), *it);
1806 }
1807
1808 // TODO: We're not trying to reuse old slots in a potential next iteration.
1809 // We have to update the slots' livei intervals to be able to do that.
1810 stackBase = stackSize;
1811 slots.clear();
1812 return true;
1813 }
1814
1815 bool
1816 RegAlloc::exec()
1817 {
1818 for (IteratorRef it = prog->calls.iteratorDFS(false);
1819 !it->end(); it->next()) {
1820 func = Function::get(reinterpret_cast<Graph::Node *>(it->get()));
1821
1822 func->tlsBase = prog->tlsSize;
1823 if (!execFunc())
1824 return false;
1825 prog->tlsSize += func->tlsSize;
1826 }
1827 return true;
1828 }
1829
1830 bool
1831 RegAlloc::execFunc()
1832 {
1833 InsertConstraintsPass insertConstr;
1834 PhiMovesPass insertPhiMoves;
1835 ArgumentMovesPass insertArgMoves;
1836 BuildIntervalsPass buildIntervals;
1837 SpillCodeInserter insertSpills(func);
1838
1839 GCRA gcra(func, insertSpills);
1840
1841 unsigned int i, retries;
1842 bool ret;
1843
1844 if (!func->ins.empty()) {
1845 // Insert a nop at the entry so inputs only used by the first instruction
1846 // don't count as having an empty live range.
1847 Instruction *nop = new_Instruction(func, OP_NOP, TYPE_NONE);
1848 BasicBlock::get(func->cfg.getRoot())->insertHead(nop);
1849 }
1850
1851 ret = insertConstr.exec(func);
1852 if (!ret)
1853 goto out;
1854
1855 ret = insertPhiMoves.run(func);
1856 if (!ret)
1857 goto out;
1858
1859 ret = insertArgMoves.run(func);
1860 if (!ret)
1861 goto out;
1862
1863 // TODO: need to fix up spill slot usage ranges to support > 1 retry
1864 for (retries = 0; retries < 3; ++retries) {
1865 if (retries && (prog->dbgFlags & NV50_IR_DEBUG_REG_ALLOC))
1866 INFO("Retry: %i\n", retries);
1867 if (prog->dbgFlags & NV50_IR_DEBUG_REG_ALLOC)
1868 func->print();
1869
1870 // spilling to registers may add live ranges, need to rebuild everything
1871 ret = true;
1872 for (sequence = func->cfg.nextSequence(), i = 0;
1873 ret && i <= func->loopNestingBound;
1874 sequence = func->cfg.nextSequence(), ++i)
1875 ret = buildLiveSets(BasicBlock::get(func->cfg.getRoot()));
1876 // reset marker
1877 for (ArrayList::Iterator bi = func->allBBlocks.iterator();
1878 !bi.end(); bi.next())
1879 BasicBlock::get(bi)->liveSet.marker = false;
1880 if (!ret)
1881 break;
1882 func->orderInstructions(this->insns);
1883
1884 ret = buildIntervals.run(func);
1885 if (!ret)
1886 break;
1887 ret = gcra.allocateRegisters(insns);
1888 if (ret)
1889 break; // success
1890 }
1891 INFO_DBG(prog->dbgFlags, REG_ALLOC, "RegAlloc done: %i\n", ret);
1892
1893 func->tlsSize = insertSpills.getStackSize();
1894 out:
1895 return ret;
1896 }
1897
1898 // TODO: check if modifying Instruction::join here breaks anything
1899 void
1900 GCRA::resolveSplitsAndMerges()
1901 {
1902 for (std::list<Instruction *>::iterator it = splits.begin();
1903 it != splits.end();
1904 ++it) {
1905 Instruction *split = *it;
1906 unsigned int reg = regs.idToBytes(split->getSrc(0));
1907 for (int d = 0; split->defExists(d); ++d) {
1908 Value *v = split->getDef(d);
1909 v->reg.data.id = regs.bytesToId(v, reg);
1910 v->join = v;
1911 reg += v->reg.size;
1912 }
1913 }
1914 splits.clear();
1915
1916 for (std::list<Instruction *>::iterator it = merges.begin();
1917 it != merges.end();
1918 ++it) {
1919 Instruction *merge = *it;
1920 unsigned int reg = regs.idToBytes(merge->getDef(0));
1921 for (int s = 0; merge->srcExists(s); ++s) {
1922 Value *v = merge->getSrc(s);
1923 v->reg.data.id = regs.bytesToId(v, reg);
1924 v->join = v;
1925 // If the value is defined by a phi/union node, we also need to
1926 // perform the same fixup on that node's sources, since after RA
1927 // their registers should be identical.
1928 if (v->getInsn()->op == OP_PHI || v->getInsn()->op == OP_UNION) {
1929 Instruction *phi = v->getInsn();
1930 for (int phis = 0; phi->srcExists(phis); ++phis) {
1931 phi->getSrc(phis)->join = v;
1932 phi->getSrc(phis)->reg.data.id = v->reg.data.id;
1933 }
1934 }
1935 reg += v->reg.size;
1936 }
1937 }
1938 merges.clear();
1939 }
1940
1941 bool Program::registerAllocation()
1942 {
1943 RegAlloc ra(this);
1944 return ra.exec();
1945 }
1946
1947 bool
1948 RegAlloc::InsertConstraintsPass::exec(Function *ir)
1949 {
1950 constrList.clear();
1951
1952 bool ret = run(ir, true, true);
1953 if (ret)
1954 ret = insertConstraintMoves();
1955 return ret;
1956 }
1957
1958 // TODO: make part of texture insn
1959 void
1960 RegAlloc::InsertConstraintsPass::textureMask(TexInstruction *tex)
1961 {
1962 Value *def[4];
1963 int c, k, d;
1964 uint8_t mask = 0;
1965
1966 for (d = 0, k = 0, c = 0; c < 4; ++c) {
1967 if (!(tex->tex.mask & (1 << c)))
1968 continue;
1969 if (tex->getDef(k)->refCount()) {
1970 mask |= 1 << c;
1971 def[d++] = tex->getDef(k);
1972 }
1973 ++k;
1974 }
1975 tex->tex.mask = mask;
1976
1977 for (c = 0; c < d; ++c)
1978 tex->setDef(c, def[c]);
1979 for (; c < 4; ++c)
1980 tex->setDef(c, NULL);
1981 }
1982
1983 bool
1984 RegAlloc::InsertConstraintsPass::detectConflict(Instruction *cst, int s)
1985 {
1986 Value *v = cst->getSrc(s);
1987
1988 // current register allocation can't handle it if a value participates in
1989 // multiple constraints
1990 for (Value::UseIterator it = v->uses.begin(); it != v->uses.end(); ++it) {
1991 if (cst != (*it)->getInsn())
1992 return true;
1993 }
1994
1995 // can start at s + 1 because detectConflict is called on all sources
1996 for (int c = s + 1; cst->srcExists(c); ++c)
1997 if (v == cst->getSrc(c))
1998 return true;
1999
2000 Instruction *defi = v->getInsn();
2001
2002 return (!defi || defi->constrainedDefs());
2003 }
2004
2005 void
2006 RegAlloc::InsertConstraintsPass::addConstraint(Instruction *i, int s, int n)
2007 {
2008 Instruction *cst;
2009 int d;
2010
2011 // first, look for an existing identical constraint op
2012 for (std::list<Instruction *>::iterator it = constrList.begin();
2013 it != constrList.end();
2014 ++it) {
2015 cst = (*it);
2016 if (!i->bb->dominatedBy(cst->bb))
2017 break;
2018 for (d = 0; d < n; ++d)
2019 if (cst->getSrc(d) != i->getSrc(d + s))
2020 break;
2021 if (d >= n) {
2022 for (d = 0; d < n; ++d, ++s)
2023 i->setSrc(s, cst->getDef(d));
2024 return;
2025 }
2026 }
2027 cst = new_Instruction(func, OP_CONSTRAINT, i->dType);
2028
2029 for (d = 0; d < n; ++s, ++d) {
2030 cst->setDef(d, new_LValue(func, FILE_GPR));
2031 cst->setSrc(d, i->getSrc(s));
2032 i->setSrc(s, cst->getDef(d));
2033 }
2034 i->bb->insertBefore(i, cst);
2035
2036 constrList.push_back(cst);
2037 }
2038
2039 // Add a dummy use of the pointer source of >= 8 byte loads after the load
2040 // to prevent it from being assigned a register which overlapping the load's
2041 // destination, which would produce random corruptions.
2042 void
2043 RegAlloc::InsertConstraintsPass::addHazard(Instruction *i, const ValueRef *src)
2044 {
2045 Instruction *hzd = new_Instruction(func, OP_NOP, TYPE_NONE);
2046 hzd->setSrc(0, src->get());
2047 i->bb->insertAfter(i, hzd);
2048
2049 }
2050
2051 // b32 { %r0 %r1 %r2 %r3 } -> b128 %r0q
2052 void
2053 RegAlloc::InsertConstraintsPass::condenseDefs(Instruction *insn)
2054 {
2055 int n;
2056 for (n = 0; insn->defExists(n) && insn->def(n).getFile() == FILE_GPR; ++n);
2057 condenseDefs(insn, 0, n - 1);
2058 }
2059
2060 void
2061 RegAlloc::InsertConstraintsPass::condenseDefs(Instruction *insn,
2062 const int a, const int b)
2063 {
2064 uint8_t size = 0;
2065 if (a >= b)
2066 return;
2067 for (int s = a; s <= b; ++s)
2068 size += insn->getDef(s)->reg.size;
2069 if (!size)
2070 return;
2071
2072 LValue *lval = new_LValue(func, FILE_GPR);
2073 lval->reg.size = size;
2074
2075 Instruction *split = new_Instruction(func, OP_SPLIT, typeOfSize(size));
2076 split->setSrc(0, lval);
2077 for (int d = a; d <= b; ++d) {
2078 split->setDef(d - a, insn->getDef(d));
2079 insn->setDef(d, NULL);
2080 }
2081 insn->setDef(a, lval);
2082
2083 for (int k = a + 1, d = b + 1; insn->defExists(d); ++d, ++k) {
2084 insn->setDef(k, insn->getDef(d));
2085 insn->setDef(d, NULL);
2086 }
2087 // carry over predicate if any (mainly for OP_UNION uses)
2088 split->setPredicate(insn->cc, insn->getPredicate());
2089
2090 insn->bb->insertAfter(insn, split);
2091 constrList.push_back(split);
2092 }
2093
2094 void
2095 RegAlloc::InsertConstraintsPass::condenseSrcs(Instruction *insn,
2096 const int a, const int b)
2097 {
2098 uint8_t size = 0;
2099 if (a >= b)
2100 return;
2101 for (int s = a; s <= b; ++s)
2102 size += insn->getSrc(s)->reg.size;
2103 if (!size)
2104 return;
2105 LValue *lval = new_LValue(func, FILE_GPR);
2106 lval->reg.size = size;
2107
2108 Value *save[3];
2109 insn->takeExtraSources(0, save);
2110
2111 Instruction *merge = new_Instruction(func, OP_MERGE, typeOfSize(size));
2112 merge->setDef(0, lval);
2113 for (int s = a, i = 0; s <= b; ++s, ++i) {
2114 merge->setSrc(i, insn->getSrc(s));
2115 }
2116 insn->moveSources(b + 1, a - b);
2117 insn->setSrc(a, lval);
2118 insn->bb->insertBefore(insn, merge);
2119
2120 insn->putExtraSources(0, save);
2121
2122 constrList.push_back(merge);
2123 }
2124
2125 bool
2126 RegAlloc::InsertConstraintsPass::isScalarTexGM107(TexInstruction *tex)
2127 {
2128 if (tex->tex.sIndirectSrc >= 0 ||
2129 tex->tex.rIndirectSrc >= 0)
2130 return false;
2131
2132 if (tex->tex.mask == 5 || tex->tex.mask == 6)
2133 return false;
2134
2135 switch (tex->op) {
2136 case OP_TEX:
2137 case OP_TXF:
2138 case OP_TXG:
2139 case OP_TXL:
2140 break;
2141 default:
2142 return false;
2143 }
2144
2145 // legal variants:
2146 // TEXS.1D.LZ
2147 // TEXS.2D
2148 // TEXS.2D.LZ
2149 // TEXS.2D.LL
2150 // TEXS.2D.DC
2151 // TEXS.2D.LL.DC
2152 // TEXS.2D.LZ.DC
2153 // TEXS.A2D
2154 // TEXS.A2D.LZ
2155 // TEXS.A2D.LZ.DC
2156 // TEXS.3D
2157 // TEXS.3D.LZ
2158 // TEXS.CUBE
2159 // TEXS.CUBE.LL
2160
2161 // TLDS.1D.LZ
2162 // TLDS.1D.LL
2163 // TLDS.2D.LZ
2164 // TLSD.2D.LZ.AOFFI
2165 // TLDS.2D.LZ.MZ
2166 // TLDS.2D.LL
2167 // TLDS.2D.LL.AOFFI
2168 // TLDS.A2D.LZ
2169 // TLDS.3D.LZ
2170
2171 // TLD4S: all 2D/RECT variants and only offset
2172
2173 switch (tex->op) {
2174 case OP_TEX:
2175 if (tex->tex.useOffsets)
2176 return false;
2177
2178 switch (tex->tex.target.getEnum()) {
2179 case TEX_TARGET_1D:
2180 case TEX_TARGET_2D_ARRAY_SHADOW:
2181 return tex->tex.levelZero;
2182 case TEX_TARGET_CUBE:
2183 return !tex->tex.levelZero;
2184 case TEX_TARGET_2D:
2185 case TEX_TARGET_2D_ARRAY:
2186 case TEX_TARGET_2D_SHADOW:
2187 case TEX_TARGET_3D:
2188 case TEX_TARGET_RECT:
2189 case TEX_TARGET_RECT_SHADOW:
2190 return true;
2191 default:
2192 return false;
2193 }
2194
2195 case OP_TXL:
2196 if (tex->tex.useOffsets)
2197 return false;
2198
2199 switch (tex->tex.target.getEnum()) {
2200 case TEX_TARGET_2D:
2201 case TEX_TARGET_2D_SHADOW:
2202 case TEX_TARGET_RECT:
2203 case TEX_TARGET_RECT_SHADOW:
2204 case TEX_TARGET_CUBE:
2205 return true;
2206 default:
2207 return false;
2208 }
2209
2210 case OP_TXF:
2211 switch (tex->tex.target.getEnum()) {
2212 case TEX_TARGET_1D:
2213 return !tex->tex.useOffsets;
2214 case TEX_TARGET_2D:
2215 case TEX_TARGET_RECT:
2216 return true;
2217 case TEX_TARGET_2D_ARRAY:
2218 case TEX_TARGET_2D_MS:
2219 case TEX_TARGET_3D:
2220 return !tex->tex.useOffsets && tex->tex.levelZero;
2221 default:
2222 return false;
2223 }
2224
2225 case OP_TXG:
2226 if (tex->tex.useOffsets > 1)
2227 return false;
2228 if (tex->tex.mask != 0x3 && tex->tex.mask != 0xf)
2229 return false;
2230
2231 switch (tex->tex.target.getEnum()) {
2232 case TEX_TARGET_2D:
2233 case TEX_TARGET_2D_MS:
2234 case TEX_TARGET_2D_SHADOW:
2235 case TEX_TARGET_RECT:
2236 case TEX_TARGET_RECT_SHADOW:
2237 return true;
2238 default:
2239 return false;
2240 }
2241
2242 default:
2243 return false;
2244 }
2245 }
2246
2247 void
2248 RegAlloc::InsertConstraintsPass::handleScalarTexGM107(TexInstruction *tex)
2249 {
2250 int defCount = tex->defCount(0xff);
2251 int srcCount = tex->srcCount(0xff);
2252
2253 tex->tex.scalar = true;
2254
2255 // 1. handle defs
2256 if (defCount > 3)
2257 condenseDefs(tex, 2, 3);
2258 if (defCount > 1)
2259 condenseDefs(tex, 0, 1);
2260
2261 // 2. handle srcs
2262 // special case for TXF.A2D
2263 if (tex->op == OP_TXF && tex->tex.target == TEX_TARGET_2D_ARRAY) {
2264 assert(srcCount >= 3);
2265 condenseSrcs(tex, 1, 2);
2266 } else {
2267 if (srcCount > 3)
2268 condenseSrcs(tex, 2, 3);
2269 // only if we have more than 2 sources
2270 if (srcCount > 2)
2271 condenseSrcs(tex, 0, 1);
2272 }
2273
2274 assert(!tex->defExists(2) && !tex->srcExists(2));
2275 }
2276
2277 void
2278 RegAlloc::InsertConstraintsPass::texConstraintGM107(TexInstruction *tex)
2279 {
2280 int n, s;
2281
2282 if (isTextureOp(tex->op))
2283 textureMask(tex);
2284
2285 if (isScalarTexGM107(tex)) {
2286 handleScalarTexGM107(tex);
2287 return;
2288 }
2289
2290 assert(!tex->tex.scalar);
2291 condenseDefs(tex);
2292
2293 if (isSurfaceOp(tex->op)) {
2294 int s = tex->tex.target.getDim() +
2295 (tex->tex.target.isArray() || tex->tex.target.isCube());
2296 int n = 0;
2297
2298 switch (tex->op) {
2299 case OP_SUSTB:
2300 case OP_SUSTP:
2301 n = 4;
2302 break;
2303 case OP_SUREDB:
2304 case OP_SUREDP:
2305 if (tex->subOp == NV50_IR_SUBOP_ATOM_CAS)
2306 n = 2;
2307 break;
2308 default:
2309 break;
2310 }
2311
2312 if (s > 1)
2313 condenseSrcs(tex, 0, s - 1);
2314 if (n > 1)
2315 condenseSrcs(tex, 1, n); // do not condense the tex handle
2316 } else
2317 if (isTextureOp(tex->op)) {
2318 if (tex->op != OP_TXQ) {
2319 s = tex->tex.target.getArgCount() - tex->tex.target.isMS();
2320 if (tex->op == OP_TXD) {
2321 // Indirect handle belongs in the first arg
2322 if (tex->tex.rIndirectSrc >= 0)
2323 s++;
2324 if (!tex->tex.target.isArray() && tex->tex.useOffsets)
2325 s++;
2326 }
2327 n = tex->srcCount(0xff) - s;
2328 } else {
2329 s = tex->srcCount(0xff);
2330 n = 0;
2331 }
2332
2333 if (s > 1)
2334 condenseSrcs(tex, 0, s - 1);
2335 if (n > 1) // NOTE: first call modified positions already
2336 condenseSrcs(tex, 1, n);
2337 }
2338 }
2339
2340 void
2341 RegAlloc::InsertConstraintsPass::texConstraintNVE0(TexInstruction *tex)
2342 {
2343 if (isTextureOp(tex->op))
2344 textureMask(tex);
2345 condenseDefs(tex);
2346
2347 if (tex->op == OP_SUSTB || tex->op == OP_SUSTP) {
2348 condenseSrcs(tex, 3, 6);
2349 } else
2350 if (isTextureOp(tex->op)) {
2351 int n = tex->srcCount(0xff, true);
2352 if (n > 4) {
2353 condenseSrcs(tex, 0, 3);
2354 if (n > 5) // NOTE: first call modified positions already
2355 condenseSrcs(tex, 4 - (4 - 1), n - 1 - (4 - 1));
2356 } else
2357 if (n > 1) {
2358 condenseSrcs(tex, 0, n - 1);
2359 }
2360 }
2361 }
2362
2363 void
2364 RegAlloc::InsertConstraintsPass::texConstraintNVC0(TexInstruction *tex)
2365 {
2366 int n, s;
2367
2368 if (isTextureOp(tex->op))
2369 textureMask(tex);
2370
2371 if (tex->op == OP_TXQ) {
2372 s = tex->srcCount(0xff);
2373 n = 0;
2374 } else if (isSurfaceOp(tex->op)) {
2375 s = tex->tex.target.getDim() + (tex->tex.target.isArray() || tex->tex.target.isCube());
2376 if (tex->op == OP_SUSTB || tex->op == OP_SUSTP)
2377 n = 4;
2378 else
2379 n = 0;
2380 } else {
2381 s = tex->tex.target.getArgCount() - tex->tex.target.isMS();
2382 if (!tex->tex.target.isArray() &&
2383 (tex->tex.rIndirectSrc >= 0 || tex->tex.sIndirectSrc >= 0))
2384 ++s;
2385 if (tex->op == OP_TXD && tex->tex.useOffsets)
2386 ++s;
2387 n = tex->srcCount(0xff) - s;
2388 assert(n <= 4);
2389 }
2390
2391 if (s > 1)
2392 condenseSrcs(tex, 0, s - 1);
2393 if (n > 1) // NOTE: first call modified positions already
2394 condenseSrcs(tex, 1, n);
2395
2396 condenseDefs(tex);
2397 }
2398
2399 void
2400 RegAlloc::InsertConstraintsPass::texConstraintNV50(TexInstruction *tex)
2401 {
2402 Value *pred = tex->getPredicate();
2403 if (pred)
2404 tex->setPredicate(tex->cc, NULL);
2405
2406 textureMask(tex);
2407
2408 assert(tex->defExists(0) && tex->srcExists(0));
2409 // make src and def count match
2410 int c;
2411 for (c = 0; tex->srcExists(c) || tex->defExists(c); ++c) {
2412 if (!tex->srcExists(c))
2413 tex->setSrc(c, new_LValue(func, tex->getSrc(0)->asLValue()));
2414 else
2415 insertConstraintMove(tex, c);
2416 if (!tex->defExists(c))
2417 tex->setDef(c, new_LValue(func, tex->getDef(0)->asLValue()));
2418 }
2419 if (pred)
2420 tex->setPredicate(tex->cc, pred);
2421 condenseDefs(tex);
2422 condenseSrcs(tex, 0, c - 1);
2423 }
2424
2425 // Insert constraint markers for instructions whose multiple sources must be
2426 // located in consecutive registers.
2427 bool
2428 RegAlloc::InsertConstraintsPass::visit(BasicBlock *bb)
2429 {
2430 TexInstruction *tex;
2431 Instruction *next;
2432 int s, size;
2433
2434 targ = bb->getProgram()->getTarget();
2435
2436 for (Instruction *i = bb->getEntry(); i; i = next) {
2437 next = i->next;
2438
2439 if ((tex = i->asTex())) {
2440 switch (targ->getChipset() & ~0xf) {
2441 case 0x50:
2442 case 0x80:
2443 case 0x90:
2444 case 0xa0:
2445 texConstraintNV50(tex);
2446 break;
2447 case 0xc0:
2448 case 0xd0:
2449 texConstraintNVC0(tex);
2450 break;
2451 case 0xe0:
2452 case 0xf0:
2453 case 0x100:
2454 texConstraintNVE0(tex);
2455 break;
2456 case 0x110:
2457 case 0x120:
2458 case 0x130:
2459 texConstraintGM107(tex);
2460 break;
2461 default:
2462 break;
2463 }
2464 } else
2465 if (i->op == OP_EXPORT || i->op == OP_STORE) {
2466 for (size = typeSizeof(i->dType), s = 1; size > 0; ++s) {
2467 assert(i->srcExists(s));
2468 size -= i->getSrc(s)->reg.size;
2469 }
2470 condenseSrcs(i, 1, s - 1);
2471 } else
2472 if (i->op == OP_LOAD || i->op == OP_VFETCH) {
2473 condenseDefs(i);
2474 if (i->src(0).isIndirect(0) && typeSizeof(i->dType) >= 8)
2475 addHazard(i, i->src(0).getIndirect(0));
2476 if (i->src(0).isIndirect(1) && typeSizeof(i->dType) >= 8)
2477 addHazard(i, i->src(0).getIndirect(1));
2478 } else
2479 if (i->op == OP_UNION ||
2480 i->op == OP_MERGE ||
2481 i->op == OP_SPLIT) {
2482 constrList.push_back(i);
2483 }
2484 }
2485 return true;
2486 }
2487
2488 void
2489 RegAlloc::InsertConstraintsPass::insertConstraintMove(Instruction *cst, int s)
2490 {
2491 const uint8_t size = cst->src(s).getSize();
2492
2493 assert(cst->getSrc(s)->defs.size() == 1); // still SSA
2494
2495 Instruction *defi = cst->getSrc(s)->defs.front()->getInsn();
2496 bool imm = defi->op == OP_MOV &&
2497 defi->src(0).getFile() == FILE_IMMEDIATE;
2498 bool load = defi->op == OP_LOAD &&
2499 defi->src(0).getFile() == FILE_MEMORY_CONST &&
2500 !defi->src(0).isIndirect(0);
2501 // catch some cases where don't really need MOVs
2502 if (cst->getSrc(s)->refCount() == 1 && !defi->constrainedDefs()) {
2503 if (imm || load) {
2504 // Move the defi right before the cst. No point in expanding
2505 // the range.
2506 defi->bb->remove(defi);
2507 cst->bb->insertBefore(cst, defi);
2508 }
2509 return;
2510 }
2511
2512 LValue *lval = new_LValue(func, cst->src(s).getFile());
2513 lval->reg.size = size;
2514
2515 Instruction *mov = new_Instruction(func, OP_MOV, typeOfSize(size));
2516 mov->setDef(0, lval);
2517 mov->setSrc(0, cst->getSrc(s));
2518
2519 if (load) {
2520 mov->op = OP_LOAD;
2521 mov->setSrc(0, defi->getSrc(0));
2522 } else if (imm) {
2523 mov->setSrc(0, defi->getSrc(0));
2524 }
2525
2526 if (defi->getPredicate())
2527 mov->setPredicate(defi->cc, defi->getPredicate());
2528
2529 cst->setSrc(s, mov->getDef(0));
2530 cst->bb->insertBefore(cst, mov);
2531
2532 cst->getDef(0)->asLValue()->noSpill = 1; // doesn't help
2533 }
2534
2535 // Insert extra moves so that, if multiple register constraints on a value are
2536 // in conflict, these conflicts can be resolved.
2537 bool
2538 RegAlloc::InsertConstraintsPass::insertConstraintMoves()
2539 {
2540 for (std::list<Instruction *>::iterator it = constrList.begin();
2541 it != constrList.end();
2542 ++it) {
2543 Instruction *cst = *it;
2544 Instruction *mov;
2545
2546 if (cst->op == OP_SPLIT && 0) {
2547 // spilling splits is annoying, just make sure they're separate
2548 for (int d = 0; cst->defExists(d); ++d) {
2549 if (!cst->getDef(d)->refCount())
2550 continue;
2551 LValue *lval = new_LValue(func, cst->def(d).getFile());
2552 const uint8_t size = cst->def(d).getSize();
2553 lval->reg.size = size;
2554
2555 mov = new_Instruction(func, OP_MOV, typeOfSize(size));
2556 mov->setSrc(0, lval);
2557 mov->setDef(0, cst->getDef(d));
2558 cst->setDef(d, mov->getSrc(0));
2559 cst->bb->insertAfter(cst, mov);
2560
2561 cst->getSrc(0)->asLValue()->noSpill = 1;
2562 mov->getSrc(0)->asLValue()->noSpill = 1;
2563 }
2564 } else
2565 if (cst->op == OP_MERGE || cst->op == OP_UNION) {
2566 for (int s = 0; cst->srcExists(s); ++s) {
2567 const uint8_t size = cst->src(s).getSize();
2568
2569 if (!cst->getSrc(s)->defs.size()) {
2570 mov = new_Instruction(func, OP_NOP, typeOfSize(size));
2571 mov->setDef(0, cst->getSrc(s));
2572 cst->bb->insertBefore(cst, mov);
2573 continue;
2574 }
2575
2576 insertConstraintMove(cst, s);
2577 }
2578 }
2579 }
2580
2581 return true;
2582 }
2583
2584 } // namespace nv50_ir