272c591ff0a9c817da62afc62097fa825325e89f
[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, unsigned int maxReg);
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, unsigned int maxReg)
164 {
165 reg = bits[f].findFreeRange(size, maxReg);
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 (bbA) {
628 bb->liveSet.setOr(&bbA->liveSet, &bbB->liveSet);
629 bbA = bb;
630 } else {
631 bbA = bbB;
632 }
633 bbB = BasicBlock::get(ei.getNode());
634 }
635 bb->liveSet.setOr(&bbB->liveSet, bbA ? &bbA->liveSet : NULL);
636 } else
637 if (bb->cfg.incidentCount()) {
638 bb->liveSet.fill(0);
639 }
640 }
641
642 bool
643 RegAlloc::BuildIntervalsPass::visit(BasicBlock *bb)
644 {
645 collectLiveValues(bb);
646
647 INFO_DBG(prog->dbgFlags, REG_ALLOC, "BuildIntervals(BB:%i)\n", bb->getId());
648
649 // go through out blocks and delete phi sources that do not originate from
650 // the current block from the live set
651 for (Graph::EdgeIterator ei = bb->cfg.outgoing(); !ei.end(); ei.next()) {
652 BasicBlock *out = BasicBlock::get(ei.getNode());
653
654 for (Instruction *i = out->getPhi(); i && i->op == OP_PHI; i = i->next) {
655 bb->liveSet.clr(i->getDef(0)->id);
656
657 for (int s = 0; i->srcExists(s); ++s) {
658 assert(i->src(s).getInsn());
659 if (i->getSrc(s)->getUniqueInsn()->bb == bb) // XXX: reachableBy ?
660 bb->liveSet.set(i->getSrc(s)->id);
661 else
662 bb->liveSet.clr(i->getSrc(s)->id);
663 }
664 }
665 }
666
667 // remaining live-outs are live until end
668 if (bb->getExit()) {
669 for (unsigned int j = 0; j < bb->liveSet.getSize(); ++j)
670 if (bb->liveSet.test(j))
671 addLiveRange(func->getLValue(j), bb, bb->getExit()->serial + 1);
672 }
673
674 for (Instruction *i = bb->getExit(); i && i->op != OP_PHI; i = i->prev) {
675 for (int d = 0; i->defExists(d); ++d) {
676 bb->liveSet.clr(i->getDef(d)->id);
677 if (i->getDef(d)->reg.data.id >= 0) // add hazard for fixed regs
678 i->getDef(d)->livei.extend(i->serial, i->serial);
679 }
680
681 for (int s = 0; i->srcExists(s); ++s) {
682 if (!i->getSrc(s)->asLValue())
683 continue;
684 if (!bb->liveSet.test(i->getSrc(s)->id)) {
685 bb->liveSet.set(i->getSrc(s)->id);
686 addLiveRange(i->getSrc(s), bb, i->serial);
687 }
688 }
689 }
690
691 if (bb == BasicBlock::get(func->cfg.getRoot())) {
692 for (std::deque<ValueDef>::iterator it = func->ins.begin();
693 it != func->ins.end(); ++it) {
694 if (it->get()->reg.data.id >= 0) // add hazard for fixed regs
695 it->get()->livei.extend(0, 1);
696 }
697 }
698
699 return true;
700 }
701
702
703 #define JOIN_MASK_PHI (1 << 0)
704 #define JOIN_MASK_UNION (1 << 1)
705 #define JOIN_MASK_MOV (1 << 2)
706 #define JOIN_MASK_TEX (1 << 3)
707
708 class GCRA
709 {
710 public:
711 GCRA(Function *, SpillCodeInserter&);
712 ~GCRA();
713
714 bool allocateRegisters(ArrayList& insns);
715
716 void printNodeInfo() const;
717
718 private:
719 class RIG_Node : public Graph::Node
720 {
721 public:
722 RIG_Node();
723
724 void init(const RegisterSet&, LValue *);
725
726 void addInterference(RIG_Node *);
727 void addRegPreference(RIG_Node *);
728
729 inline LValue *getValue() const
730 {
731 return reinterpret_cast<LValue *>(data);
732 }
733 inline void setValue(LValue *lval) { data = lval; }
734
735 inline uint8_t getCompMask() const
736 {
737 return ((1 << colors) - 1) << (reg & 7);
738 }
739
740 static inline RIG_Node *get(const Graph::EdgeIterator& ei)
741 {
742 return static_cast<RIG_Node *>(ei.getNode());
743 }
744
745 public:
746 uint32_t degree;
747 uint16_t degreeLimit; // if deg < degLimit, node is trivially colourable
748 uint16_t maxReg;
749 uint16_t colors;
750
751 DataFile f;
752 int32_t reg;
753
754 float weight;
755
756 // list pointers for simplify() phase
757 RIG_Node *next;
758 RIG_Node *prev;
759
760 // union of the live intervals of all coalesced values (we want to retain
761 // the separate intervals for testing interference of compound values)
762 Interval livei;
763
764 std::list<RIG_Node *> prefRegs;
765 };
766
767 private:
768 inline RIG_Node *getNode(const LValue *v) const { return &nodes[v->id]; }
769
770 void buildRIG(ArrayList&);
771 bool coalesce(ArrayList&);
772 bool doCoalesce(ArrayList&, unsigned int mask);
773 void calculateSpillWeights();
774 bool simplify();
775 bool selectRegisters();
776 void cleanup(const bool success);
777
778 void simplifyEdge(RIG_Node *, RIG_Node *);
779 void simplifyNode(RIG_Node *);
780
781 bool coalesceValues(Value *, Value *, bool force);
782 void resolveSplitsAndMerges();
783 void makeCompound(Instruction *, bool isSplit);
784
785 inline void checkInterference(const RIG_Node *, Graph::EdgeIterator&);
786
787 inline void insertOrderedTail(std::list<RIG_Node *>&, RIG_Node *);
788 void checkList(std::list<RIG_Node *>&);
789
790 private:
791 std::stack<uint32_t> stack;
792
793 // list headers for simplify() phase
794 RIG_Node lo[2];
795 RIG_Node hi;
796
797 Graph RIG;
798 RIG_Node *nodes;
799 unsigned int nodeCount;
800
801 Function *func;
802 Program *prog;
803
804 struct RelDegree {
805 uint8_t data[17][17];
806
807 RelDegree() {
808 for (int i = 1; i <= 16; ++i)
809 for (int j = 1; j <= 16; ++j)
810 data[i][j] = j * ((i + j - 1) / j);
811 }
812
813 const uint8_t* operator[](std::size_t i) const {
814 return data[i];
815 }
816 };
817
818 static const RelDegree relDegree;
819
820 RegisterSet regs;
821
822 // need to fixup register id for participants of OP_MERGE/SPLIT
823 std::list<Instruction *> merges;
824 std::list<Instruction *> splits;
825
826 SpillCodeInserter& spill;
827 std::list<ValuePair> mustSpill;
828 };
829
830 const GCRA::RelDegree GCRA::relDegree;
831
832 GCRA::RIG_Node::RIG_Node() : Node(NULL), next(this), prev(this)
833 {
834 colors = 0;
835 }
836
837 void
838 GCRA::printNodeInfo() const
839 {
840 for (unsigned int i = 0; i < nodeCount; ++i) {
841 if (!nodes[i].colors)
842 continue;
843 INFO("RIG_Node[%%%i]($[%u]%i): %u colors, weight %f, deg %u/%u\n X",
844 i,
845 nodes[i].f,nodes[i].reg,nodes[i].colors,
846 nodes[i].weight,
847 nodes[i].degree, nodes[i].degreeLimit);
848
849 for (Graph::EdgeIterator ei = nodes[i].outgoing(); !ei.end(); ei.next())
850 INFO(" %%%i", RIG_Node::get(ei)->getValue()->id);
851 for (Graph::EdgeIterator ei = nodes[i].incident(); !ei.end(); ei.next())
852 INFO(" %%%i", RIG_Node::get(ei)->getValue()->id);
853 INFO("\n");
854 }
855 }
856
857 static bool
858 isShortRegOp(Instruction *insn)
859 {
860 // Immediates are always in src1 (except zeroes, which end up getting
861 // replaced with a zero reg). Every other situation can be resolved by
862 // using a long encoding.
863 return insn->srcExists(1) && insn->src(1).getFile() == FILE_IMMEDIATE &&
864 insn->getSrc(1)->reg.data.u64;
865 }
866
867 // Check if this LValue is ever used in an instruction that can't be encoded
868 // with long registers (i.e. > r63)
869 static bool
870 isShortRegVal(LValue *lval)
871 {
872 if (lval->getInsn() == NULL)
873 return false;
874 for (Value::DefCIterator def = lval->defs.begin();
875 def != lval->defs.end(); ++def)
876 if (isShortRegOp((*def)->getInsn()))
877 return true;
878 for (Value::UseCIterator use = lval->uses.begin();
879 use != lval->uses.end(); ++use)
880 if (isShortRegOp((*use)->getInsn()))
881 return true;
882 return false;
883 }
884
885 void
886 GCRA::RIG_Node::init(const RegisterSet& regs, LValue *lval)
887 {
888 setValue(lval);
889 if (lval->reg.data.id >= 0)
890 lval->noSpill = lval->fixedReg = 1;
891
892 colors = regs.units(lval->reg.file, lval->reg.size);
893 f = lval->reg.file;
894 reg = -1;
895 if (lval->reg.data.id >= 0)
896 reg = regs.idToUnits(lval);
897
898 weight = std::numeric_limits<float>::infinity();
899 degree = 0;
900 maxReg = regs.getFileSize(f);
901 // On nv50, we lose a bit of gpr encoding when there's an embedded
902 // immediate.
903 if (regs.restrictedGPR16Range && f == FILE_GPR && (lval->reg.size == 2 || isShortRegVal(lval)))
904 maxReg /= 2;
905 degreeLimit = maxReg;
906 degreeLimit -= relDegree[1][colors] - 1;
907
908 livei.insert(lval->livei);
909 }
910
911 bool
912 GCRA::coalesceValues(Value *dst, Value *src, bool force)
913 {
914 LValue *rep = dst->join->asLValue();
915 LValue *val = src->join->asLValue();
916
917 if (!force && val->reg.data.id >= 0) {
918 rep = src->join->asLValue();
919 val = dst->join->asLValue();
920 }
921 RIG_Node *nRep = &nodes[rep->id];
922 RIG_Node *nVal = &nodes[val->id];
923
924 if (src->reg.file != dst->reg.file) {
925 if (!force)
926 return false;
927 WARN("forced coalescing of values in different files !\n");
928 }
929 if (!force && dst->reg.size != src->reg.size)
930 return false;
931
932 if ((rep->reg.data.id >= 0) && (rep->reg.data.id != val->reg.data.id)) {
933 if (force) {
934 if (val->reg.data.id >= 0)
935 WARN("forced coalescing of values in different fixed regs !\n");
936 } else {
937 if (val->reg.data.id >= 0)
938 return false;
939 // make sure that there is no overlap with the fixed register of rep
940 for (ArrayList::Iterator it = func->allLValues.iterator();
941 !it.end(); it.next()) {
942 Value *reg = reinterpret_cast<Value *>(it.get())->asLValue();
943 assert(reg);
944 if (reg->interfers(rep) && reg->livei.overlaps(nVal->livei))
945 return false;
946 }
947 }
948 }
949
950 if (!force && nRep->livei.overlaps(nVal->livei))
951 return false;
952
953 INFO_DBG(prog->dbgFlags, REG_ALLOC, "joining %%%i($%i) <- %%%i\n",
954 rep->id, rep->reg.data.id, val->id);
955
956 // set join pointer of all values joined with val
957 for (Value::DefIterator def = val->defs.begin(); def != val->defs.end();
958 ++def)
959 (*def)->get()->join = rep;
960 assert(rep->join == rep && val->join == rep);
961
962 // add val's definitions to rep and extend the live interval of its RIG node
963 rep->defs.insert(rep->defs.end(), val->defs.begin(), val->defs.end());
964 nRep->livei.unify(nVal->livei);
965 nRep->degreeLimit = MIN2(nRep->degreeLimit, nVal->degreeLimit);
966 nRep->maxReg = MIN2(nRep->maxReg, nVal->maxReg);
967 return true;
968 }
969
970 bool
971 GCRA::coalesce(ArrayList& insns)
972 {
973 bool ret = doCoalesce(insns, JOIN_MASK_PHI);
974 if (!ret)
975 return false;
976 switch (func->getProgram()->getTarget()->getChipset() & ~0xf) {
977 case 0x50:
978 case 0x80:
979 case 0x90:
980 case 0xa0:
981 ret = doCoalesce(insns, JOIN_MASK_UNION | JOIN_MASK_TEX);
982 break;
983 case 0xc0:
984 case 0xd0:
985 case 0xe0:
986 case 0xf0:
987 case 0x100:
988 case 0x110:
989 case 0x120:
990 case 0x130:
991 case 0x140:
992 ret = doCoalesce(insns, JOIN_MASK_UNION);
993 break;
994 default:
995 break;
996 }
997 if (!ret)
998 return false;
999 return doCoalesce(insns, JOIN_MASK_MOV);
1000 }
1001
1002 static inline uint8_t makeCompMask(int compSize, int base, int size)
1003 {
1004 uint8_t m = ((1 << size) - 1) << base;
1005
1006 switch (compSize) {
1007 case 1:
1008 return 0xff;
1009 case 2:
1010 m |= (m << 2);
1011 return (m << 4) | m;
1012 case 3:
1013 case 4:
1014 return (m << 4) | m;
1015 default:
1016 assert(compSize <= 8);
1017 return m;
1018 }
1019 }
1020
1021 // Used when coalescing moves. The non-compound value will become one, e.g.:
1022 // mov b32 $r0 $r2 / merge b64 $r0d { $r0 $r1 }
1023 // split b64 { $r0 $r1 } $r0d / mov b64 $r0d f64 $r2d
1024 static inline void copyCompound(Value *dst, Value *src)
1025 {
1026 LValue *ldst = dst->asLValue();
1027 LValue *lsrc = src->asLValue();
1028
1029 if (ldst->compound && !lsrc->compound) {
1030 LValue *swap = lsrc;
1031 lsrc = ldst;
1032 ldst = swap;
1033 }
1034
1035 ldst->compound = lsrc->compound;
1036 ldst->compMask = lsrc->compMask;
1037 }
1038
1039 void
1040 GCRA::makeCompound(Instruction *insn, bool split)
1041 {
1042 LValue *rep = (split ? insn->getSrc(0) : insn->getDef(0))->asLValue();
1043
1044 if (prog->dbgFlags & NV50_IR_DEBUG_REG_ALLOC) {
1045 INFO("makeCompound(split = %i): ", split);
1046 insn->print();
1047 }
1048
1049 const unsigned int size = getNode(rep)->colors;
1050 unsigned int base = 0;
1051
1052 if (!rep->compound)
1053 rep->compMask = 0xff;
1054 rep->compound = 1;
1055
1056 for (int c = 0; split ? insn->defExists(c) : insn->srcExists(c); ++c) {
1057 LValue *val = (split ? insn->getDef(c) : insn->getSrc(c))->asLValue();
1058
1059 val->compound = 1;
1060 if (!val->compMask)
1061 val->compMask = 0xff;
1062 val->compMask &= makeCompMask(size, base, getNode(val)->colors);
1063 assert(val->compMask);
1064
1065 INFO_DBG(prog->dbgFlags, REG_ALLOC, "compound: %%%i:%02x <- %%%i:%02x\n",
1066 rep->id, rep->compMask, val->id, val->compMask);
1067
1068 base += getNode(val)->colors;
1069 }
1070 assert(base == size);
1071 }
1072
1073 bool
1074 GCRA::doCoalesce(ArrayList& insns, unsigned int mask)
1075 {
1076 int c, n;
1077
1078 for (n = 0; n < insns.getSize(); ++n) {
1079 Instruction *i;
1080 Instruction *insn = reinterpret_cast<Instruction *>(insns.get(n));
1081
1082 switch (insn->op) {
1083 case OP_PHI:
1084 if (!(mask & JOIN_MASK_PHI))
1085 break;
1086 for (c = 0; insn->srcExists(c); ++c)
1087 if (!coalesceValues(insn->getDef(0), insn->getSrc(c), false)) {
1088 // this is bad
1089 ERROR("failed to coalesce phi operands\n");
1090 return false;
1091 }
1092 break;
1093 case OP_UNION:
1094 case OP_MERGE:
1095 if (!(mask & JOIN_MASK_UNION))
1096 break;
1097 for (c = 0; insn->srcExists(c); ++c)
1098 coalesceValues(insn->getDef(0), insn->getSrc(c), true);
1099 if (insn->op == OP_MERGE) {
1100 merges.push_back(insn);
1101 if (insn->srcExists(1))
1102 makeCompound(insn, false);
1103 }
1104 break;
1105 case OP_SPLIT:
1106 if (!(mask & JOIN_MASK_UNION))
1107 break;
1108 splits.push_back(insn);
1109 for (c = 0; insn->defExists(c); ++c)
1110 coalesceValues(insn->getSrc(0), insn->getDef(c), true);
1111 makeCompound(insn, true);
1112 break;
1113 case OP_MOV:
1114 if (!(mask & JOIN_MASK_MOV))
1115 break;
1116 i = NULL;
1117 if (!insn->getDef(0)->uses.empty())
1118 i = (*insn->getDef(0)->uses.begin())->getInsn();
1119 // if this is a contraint-move there will only be a single use
1120 if (i && i->op == OP_MERGE) // do we really still need this ?
1121 break;
1122 i = insn->getSrc(0)->getUniqueInsn();
1123 if (i && !i->constrainedDefs()) {
1124 if (coalesceValues(insn->getDef(0), insn->getSrc(0), false))
1125 copyCompound(insn->getSrc(0), insn->getDef(0));
1126 }
1127 break;
1128 case OP_TEX:
1129 case OP_TXB:
1130 case OP_TXL:
1131 case OP_TXF:
1132 case OP_TXQ:
1133 case OP_TXD:
1134 case OP_TXG:
1135 case OP_TXLQ:
1136 case OP_TEXCSAA:
1137 case OP_TEXPREP:
1138 if (!(mask & JOIN_MASK_TEX))
1139 break;
1140 for (c = 0; insn->srcExists(c) && c != insn->predSrc; ++c)
1141 coalesceValues(insn->getDef(c), insn->getSrc(c), true);
1142 break;
1143 default:
1144 break;
1145 }
1146 }
1147 return true;
1148 }
1149
1150 void
1151 GCRA::RIG_Node::addInterference(RIG_Node *node)
1152 {
1153 this->degree += relDegree[node->colors][colors];
1154 node->degree += relDegree[colors][node->colors];
1155
1156 this->attach(node, Graph::Edge::CROSS);
1157 }
1158
1159 void
1160 GCRA::RIG_Node::addRegPreference(RIG_Node *node)
1161 {
1162 prefRegs.push_back(node);
1163 }
1164
1165 GCRA::GCRA(Function *fn, SpillCodeInserter& spill) :
1166 func(fn),
1167 regs(fn->getProgram()->getTarget()),
1168 spill(spill)
1169 {
1170 prog = func->getProgram();
1171 }
1172
1173 GCRA::~GCRA()
1174 {
1175 if (nodes)
1176 delete[] nodes;
1177 }
1178
1179 void
1180 GCRA::checkList(std::list<RIG_Node *>& lst)
1181 {
1182 GCRA::RIG_Node *prev = NULL;
1183
1184 for (std::list<RIG_Node *>::iterator it = lst.begin();
1185 it != lst.end();
1186 ++it) {
1187 assert((*it)->getValue()->join == (*it)->getValue());
1188 if (prev)
1189 assert(prev->livei.begin() <= (*it)->livei.begin());
1190 prev = *it;
1191 }
1192 }
1193
1194 void
1195 GCRA::insertOrderedTail(std::list<RIG_Node *>& list, RIG_Node *node)
1196 {
1197 if (node->livei.isEmpty())
1198 return;
1199 // only the intervals of joined values don't necessarily arrive in order
1200 std::list<RIG_Node *>::iterator prev, it;
1201 for (it = list.end(); it != list.begin(); it = prev) {
1202 prev = it;
1203 --prev;
1204 if ((*prev)->livei.begin() <= node->livei.begin())
1205 break;
1206 }
1207 list.insert(it, node);
1208 }
1209
1210 void
1211 GCRA::buildRIG(ArrayList& insns)
1212 {
1213 std::list<RIG_Node *> values, active;
1214
1215 for (std::deque<ValueDef>::iterator it = func->ins.begin();
1216 it != func->ins.end(); ++it)
1217 insertOrderedTail(values, getNode(it->get()->asLValue()));
1218
1219 for (int i = 0; i < insns.getSize(); ++i) {
1220 Instruction *insn = reinterpret_cast<Instruction *>(insns.get(i));
1221 for (int d = 0; insn->defExists(d); ++d)
1222 if (insn->getDef(d)->rep() == insn->getDef(d))
1223 insertOrderedTail(values, getNode(insn->getDef(d)->asLValue()));
1224 }
1225 checkList(values);
1226
1227 while (!values.empty()) {
1228 RIG_Node *cur = values.front();
1229
1230 for (std::list<RIG_Node *>::iterator it = active.begin();
1231 it != active.end();) {
1232 RIG_Node *node = *it;
1233
1234 if (node->livei.end() <= cur->livei.begin()) {
1235 it = active.erase(it);
1236 } else {
1237 if (node->f == cur->f && node->livei.overlaps(cur->livei))
1238 cur->addInterference(node);
1239 ++it;
1240 }
1241 }
1242 values.pop_front();
1243 active.push_back(cur);
1244 }
1245 }
1246
1247 void
1248 GCRA::calculateSpillWeights()
1249 {
1250 for (unsigned int i = 0; i < nodeCount; ++i) {
1251 RIG_Node *const n = &nodes[i];
1252 if (!nodes[i].colors || nodes[i].livei.isEmpty())
1253 continue;
1254 if (nodes[i].reg >= 0) {
1255 // update max reg
1256 regs.occupy(n->f, n->reg, n->colors);
1257 continue;
1258 }
1259 LValue *val = nodes[i].getValue();
1260
1261 if (!val->noSpill) {
1262 int rc = 0;
1263 for (Value::DefIterator it = val->defs.begin();
1264 it != val->defs.end();
1265 ++it)
1266 rc += (*it)->get()->refCount();
1267
1268 nodes[i].weight =
1269 (float)rc * (float)rc / (float)nodes[i].livei.extent();
1270 }
1271
1272 if (nodes[i].degree < nodes[i].degreeLimit) {
1273 int l = 0;
1274 if (val->reg.size > 4)
1275 l = 1;
1276 DLLIST_ADDHEAD(&lo[l], &nodes[i]);
1277 } else {
1278 DLLIST_ADDHEAD(&hi, &nodes[i]);
1279 }
1280 }
1281 if (prog->dbgFlags & NV50_IR_DEBUG_REG_ALLOC)
1282 printNodeInfo();
1283 }
1284
1285 void
1286 GCRA::simplifyEdge(RIG_Node *a, RIG_Node *b)
1287 {
1288 bool move = b->degree >= b->degreeLimit;
1289
1290 INFO_DBG(prog->dbgFlags, REG_ALLOC,
1291 "edge: (%%%i, deg %u/%u) >-< (%%%i, deg %u/%u)\n",
1292 a->getValue()->id, a->degree, a->degreeLimit,
1293 b->getValue()->id, b->degree, b->degreeLimit);
1294
1295 b->degree -= relDegree[a->colors][b->colors];
1296
1297 move = move && b->degree < b->degreeLimit;
1298 if (move && !DLLIST_EMPTY(b)) {
1299 int l = (b->getValue()->reg.size > 4) ? 1 : 0;
1300 DLLIST_DEL(b);
1301 DLLIST_ADDTAIL(&lo[l], b);
1302 }
1303 }
1304
1305 void
1306 GCRA::simplifyNode(RIG_Node *node)
1307 {
1308 for (Graph::EdgeIterator ei = node->outgoing(); !ei.end(); ei.next())
1309 simplifyEdge(node, RIG_Node::get(ei));
1310
1311 for (Graph::EdgeIterator ei = node->incident(); !ei.end(); ei.next())
1312 simplifyEdge(node, RIG_Node::get(ei));
1313
1314 DLLIST_DEL(node);
1315 stack.push(node->getValue()->id);
1316
1317 INFO_DBG(prog->dbgFlags, REG_ALLOC, "SIMPLIFY: pushed %%%i%s\n",
1318 node->getValue()->id,
1319 (node->degree < node->degreeLimit) ? "" : "(spill)");
1320 }
1321
1322 bool
1323 GCRA::simplify()
1324 {
1325 for (;;) {
1326 if (!DLLIST_EMPTY(&lo[0])) {
1327 do {
1328 simplifyNode(lo[0].next);
1329 } while (!DLLIST_EMPTY(&lo[0]));
1330 } else
1331 if (!DLLIST_EMPTY(&lo[1])) {
1332 simplifyNode(lo[1].next);
1333 } else
1334 if (!DLLIST_EMPTY(&hi)) {
1335 RIG_Node *best = hi.next;
1336 unsigned bestMaxReg = best->maxReg;
1337 float bestScore = best->weight / (float)best->degree;
1338 // Spill candidate. First go through the ones with the highest max
1339 // register, then the ones with lower. That way the ones with the
1340 // lowest requirement will be allocated first, since it's a stack.
1341 for (RIG_Node *it = best->next; it != &hi; it = it->next) {
1342 float score = it->weight / (float)it->degree;
1343 if (score < bestScore || it->maxReg > bestMaxReg) {
1344 best = it;
1345 bestScore = score;
1346 bestMaxReg = it->maxReg;
1347 }
1348 }
1349 if (isinf(bestScore)) {
1350 ERROR("no viable spill candidates left\n");
1351 return false;
1352 }
1353 simplifyNode(best);
1354 } else {
1355 return true;
1356 }
1357 }
1358 }
1359
1360 void
1361 GCRA::checkInterference(const RIG_Node *node, Graph::EdgeIterator& ei)
1362 {
1363 const RIG_Node *intf = RIG_Node::get(ei);
1364
1365 if (intf->reg < 0)
1366 return;
1367 const LValue *vA = node->getValue();
1368 const LValue *vB = intf->getValue();
1369
1370 const uint8_t intfMask = ((1 << intf->colors) - 1) << (intf->reg & 7);
1371
1372 if (vA->compound | vB->compound) {
1373 // NOTE: this only works for >aligned< register tuples !
1374 for (Value::DefCIterator D = vA->defs.begin(); D != vA->defs.end(); ++D) {
1375 for (Value::DefCIterator d = vB->defs.begin(); d != vB->defs.end(); ++d) {
1376 const LValue *vD = (*D)->get()->asLValue();
1377 const LValue *vd = (*d)->get()->asLValue();
1378
1379 if (!vD->livei.overlaps(vd->livei)) {
1380 INFO_DBG(prog->dbgFlags, REG_ALLOC, "(%%%i) X (%%%i): no overlap\n",
1381 vD->id, vd->id);
1382 continue;
1383 }
1384
1385 uint8_t mask = vD->compound ? vD->compMask : ~0;
1386 if (vd->compound) {
1387 assert(vB->compound);
1388 mask &= vd->compMask & vB->compMask;
1389 } else {
1390 mask &= intfMask;
1391 }
1392
1393 INFO_DBG(prog->dbgFlags, REG_ALLOC,
1394 "(%%%i)%02x X (%%%i)%02x & %02x: $r%i.%02x\n",
1395 vD->id,
1396 vD->compound ? vD->compMask : 0xff,
1397 vd->id,
1398 vd->compound ? vd->compMask : intfMask,
1399 vB->compMask, intf->reg & ~7, mask);
1400 if (mask)
1401 regs.occupyMask(node->f, intf->reg & ~7, mask);
1402 }
1403 }
1404 } else {
1405 INFO_DBG(prog->dbgFlags, REG_ALLOC,
1406 "(%%%i) X (%%%i): $r%i + %u\n",
1407 vA->id, vB->id, intf->reg, intf->colors);
1408 regs.occupy(node->f, intf->reg, intf->colors);
1409 }
1410 }
1411
1412 bool
1413 GCRA::selectRegisters()
1414 {
1415 INFO_DBG(prog->dbgFlags, REG_ALLOC, "\nSELECT phase\n");
1416
1417 while (!stack.empty()) {
1418 RIG_Node *node = &nodes[stack.top()];
1419 stack.pop();
1420
1421 regs.reset(node->f);
1422
1423 INFO_DBG(prog->dbgFlags, REG_ALLOC, "\nNODE[%%%i, %u colors]\n",
1424 node->getValue()->id, node->colors);
1425
1426 for (Graph::EdgeIterator ei = node->outgoing(); !ei.end(); ei.next())
1427 checkInterference(node, ei);
1428 for (Graph::EdgeIterator ei = node->incident(); !ei.end(); ei.next())
1429 checkInterference(node, ei);
1430
1431 if (!node->prefRegs.empty()) {
1432 for (std::list<RIG_Node *>::const_iterator it = node->prefRegs.begin();
1433 it != node->prefRegs.end();
1434 ++it) {
1435 if ((*it)->reg >= 0 &&
1436 regs.testOccupy(node->f, (*it)->reg, node->colors)) {
1437 node->reg = (*it)->reg;
1438 break;
1439 }
1440 }
1441 }
1442 if (node->reg >= 0)
1443 continue;
1444 LValue *lval = node->getValue();
1445 if (prog->dbgFlags & NV50_IR_DEBUG_REG_ALLOC)
1446 regs.print(node->f);
1447 bool ret = regs.assign(node->reg, node->f, node->colors, node->maxReg);
1448 if (ret) {
1449 INFO_DBG(prog->dbgFlags, REG_ALLOC, "assigned reg %i\n", node->reg);
1450 lval->compMask = node->getCompMask();
1451 } else {
1452 INFO_DBG(prog->dbgFlags, REG_ALLOC, "must spill: %%%i (size %u)\n",
1453 lval->id, lval->reg.size);
1454 Symbol *slot = NULL;
1455 if (lval->reg.file == FILE_GPR)
1456 slot = spill.assignSlot(node->livei, lval->reg.size);
1457 mustSpill.push_back(ValuePair(lval, slot));
1458 }
1459 }
1460 if (!mustSpill.empty())
1461 return false;
1462 for (unsigned int i = 0; i < nodeCount; ++i) {
1463 LValue *lval = nodes[i].getValue();
1464 if (nodes[i].reg >= 0 && nodes[i].colors > 0)
1465 lval->reg.data.id =
1466 regs.unitsToId(nodes[i].f, nodes[i].reg, lval->reg.size);
1467 }
1468 return true;
1469 }
1470
1471 bool
1472 GCRA::allocateRegisters(ArrayList& insns)
1473 {
1474 bool ret;
1475
1476 INFO_DBG(prog->dbgFlags, REG_ALLOC,
1477 "allocateRegisters to %u instructions\n", insns.getSize());
1478
1479 nodeCount = func->allLValues.getSize();
1480 nodes = new RIG_Node[nodeCount];
1481 if (!nodes)
1482 return false;
1483 for (unsigned int i = 0; i < nodeCount; ++i) {
1484 LValue *lval = reinterpret_cast<LValue *>(func->allLValues.get(i));
1485 if (lval) {
1486 nodes[i].init(regs, lval);
1487 RIG.insert(&nodes[i]);
1488
1489 if (lval->inFile(FILE_GPR) && lval->getInsn() != NULL) {
1490 Instruction *insn = lval->getInsn();
1491 if (insn->op != OP_MAD && insn->op != OP_FMA && insn->op != OP_SAD)
1492 continue;
1493 // For both of the cases below, we only want to add the preference
1494 // if all arguments are in registers.
1495 if (insn->src(0).getFile() != FILE_GPR ||
1496 insn->src(1).getFile() != FILE_GPR ||
1497 insn->src(2).getFile() != FILE_GPR)
1498 continue;
1499 if (prog->getTarget()->getChipset() < 0xc0) {
1500 // Outputting a flag is not supported with short encodings nor
1501 // with immediate arguments.
1502 // See handleMADforNV50.
1503 if (insn->flagsDef >= 0)
1504 continue;
1505 } else {
1506 // We can only fold immediate arguments if dst == src2. This
1507 // only matters if one of the first two arguments is an
1508 // immediate. This form is also only supported for floats.
1509 // See handleMADforNVC0.
1510 ImmediateValue imm;
1511 if (insn->dType != TYPE_F32)
1512 continue;
1513 if (!insn->src(0).getImmediate(imm) &&
1514 !insn->src(1).getImmediate(imm))
1515 continue;
1516 }
1517
1518 nodes[i].addRegPreference(getNode(insn->getSrc(2)->asLValue()));
1519 }
1520 }
1521 }
1522
1523 // coalesce first, we use only 1 RIG node for a group of joined values
1524 ret = coalesce(insns);
1525 if (!ret)
1526 goto out;
1527
1528 if (func->getProgram()->dbgFlags & NV50_IR_DEBUG_REG_ALLOC)
1529 func->printLiveIntervals();
1530
1531 buildRIG(insns);
1532 calculateSpillWeights();
1533 ret = simplify();
1534 if (!ret)
1535 goto out;
1536
1537 ret = selectRegisters();
1538 if (!ret) {
1539 INFO_DBG(prog->dbgFlags, REG_ALLOC,
1540 "selectRegisters failed, inserting spill code ...\n");
1541 regs.reset(FILE_GPR, true);
1542 spill.run(mustSpill);
1543 if (prog->dbgFlags & NV50_IR_DEBUG_REG_ALLOC)
1544 func->print();
1545 } else {
1546 prog->maxGPR = std::max(prog->maxGPR, regs.getMaxAssigned(FILE_GPR));
1547 }
1548
1549 out:
1550 cleanup(ret);
1551 return ret;
1552 }
1553
1554 void
1555 GCRA::cleanup(const bool success)
1556 {
1557 mustSpill.clear();
1558
1559 for (ArrayList::Iterator it = func->allLValues.iterator();
1560 !it.end(); it.next()) {
1561 LValue *lval = reinterpret_cast<LValue *>(it.get());
1562
1563 lval->livei.clear();
1564
1565 lval->compound = 0;
1566 lval->compMask = 0;
1567
1568 if (lval->join == lval)
1569 continue;
1570
1571 if (success) {
1572 lval->reg.data.id = lval->join->reg.data.id;
1573 } else {
1574 for (Value::DefIterator d = lval->defs.begin(); d != lval->defs.end();
1575 ++d)
1576 lval->join->defs.remove(*d);
1577 lval->join = lval;
1578 }
1579 }
1580
1581 if (success)
1582 resolveSplitsAndMerges();
1583 splits.clear(); // avoid duplicate entries on next coalesce pass
1584 merges.clear();
1585
1586 delete[] nodes;
1587 nodes = NULL;
1588 hi.next = hi.prev = &hi;
1589 lo[0].next = lo[0].prev = &lo[0];
1590 lo[1].next = lo[1].prev = &lo[1];
1591 }
1592
1593 Symbol *
1594 SpillCodeInserter::assignSlot(const Interval &livei, const unsigned int size)
1595 {
1596 SpillSlot slot;
1597 int32_t offsetBase = stackSize;
1598 int32_t offset;
1599 std::list<SpillSlot>::iterator pos = slots.end(), it = slots.begin();
1600
1601 if (offsetBase % size)
1602 offsetBase += size - (offsetBase % size);
1603
1604 slot.sym = NULL;
1605
1606 for (offset = offsetBase; offset < stackSize; offset += size) {
1607 const int32_t entryEnd = offset + size;
1608 while (it != slots.end() && it->offset < offset)
1609 ++it;
1610 if (it == slots.end()) // no slots left
1611 break;
1612 std::list<SpillSlot>::iterator bgn = it;
1613
1614 while (it != slots.end() && it->offset < entryEnd) {
1615 it->occup.print();
1616 if (it->occup.overlaps(livei))
1617 break;
1618 ++it;
1619 }
1620 if (it == slots.end() || it->offset >= entryEnd) {
1621 // fits
1622 for (; bgn != slots.end() && bgn->offset < entryEnd; ++bgn) {
1623 bgn->occup.insert(livei);
1624 if (bgn->size() == size)
1625 slot.sym = bgn->sym;
1626 }
1627 break;
1628 }
1629 }
1630 if (!slot.sym) {
1631 stackSize = offset + size;
1632 slot.offset = offset;
1633 slot.sym = new_Symbol(func->getProgram(), FILE_MEMORY_LOCAL);
1634 if (!func->stackPtr)
1635 offset += func->tlsBase;
1636 slot.sym->setAddress(NULL, offset);
1637 slot.sym->reg.size = size;
1638 slots.insert(pos, slot)->occup.insert(livei);
1639 }
1640 return slot.sym;
1641 }
1642
1643 Value *
1644 SpillCodeInserter::offsetSlot(Value *base, const LValue *lval)
1645 {
1646 if (!lval->compound || (lval->compMask & 0x1))
1647 return base;
1648 Value *slot = cloneShallow(func, base);
1649
1650 slot->reg.data.offset += (ffs(lval->compMask) - 1) * lval->reg.size;
1651 slot->reg.size = lval->reg.size;
1652
1653 return slot;
1654 }
1655
1656 void
1657 SpillCodeInserter::spill(Instruction *defi, Value *slot, LValue *lval)
1658 {
1659 const DataType ty = typeOfSize(lval->reg.size);
1660
1661 slot = offsetSlot(slot, lval);
1662
1663 Instruction *st;
1664 if (slot->reg.file == FILE_MEMORY_LOCAL) {
1665 lval->noSpill = 1;
1666 if (ty != TYPE_B96) {
1667 st = new_Instruction(func, OP_STORE, ty);
1668 st->setSrc(0, slot);
1669 st->setSrc(1, lval);
1670 } else {
1671 st = new_Instruction(func, OP_SPLIT, ty);
1672 st->setSrc(0, lval);
1673 for (int d = 0; d < lval->reg.size / 4; ++d)
1674 st->setDef(d, new_LValue(func, FILE_GPR));
1675
1676 for (int d = lval->reg.size / 4 - 1; d >= 0; --d) {
1677 Value *tmp = cloneShallow(func, slot);
1678 tmp->reg.size = 4;
1679 tmp->reg.data.offset += 4 * d;
1680
1681 Instruction *s = new_Instruction(func, OP_STORE, TYPE_U32);
1682 s->setSrc(0, tmp);
1683 s->setSrc(1, st->getDef(d));
1684 defi->bb->insertAfter(defi, s);
1685 }
1686 }
1687 } else {
1688 st = new_Instruction(func, OP_CVT, ty);
1689 st->setDef(0, slot);
1690 st->setSrc(0, lval);
1691 if (lval->reg.file == FILE_FLAGS)
1692 st->flagsSrc = 0;
1693 }
1694 defi->bb->insertAfter(defi, st);
1695 }
1696
1697 LValue *
1698 SpillCodeInserter::unspill(Instruction *usei, LValue *lval, Value *slot)
1699 {
1700 const DataType ty = typeOfSize(lval->reg.size);
1701
1702 slot = offsetSlot(slot, lval);
1703 lval = cloneShallow(func, lval);
1704
1705 Instruction *ld;
1706 if (slot->reg.file == FILE_MEMORY_LOCAL) {
1707 lval->noSpill = 1;
1708 if (ty != TYPE_B96) {
1709 ld = new_Instruction(func, OP_LOAD, ty);
1710 } else {
1711 ld = new_Instruction(func, OP_MERGE, ty);
1712 for (int d = 0; d < lval->reg.size / 4; ++d) {
1713 Value *tmp = cloneShallow(func, slot);
1714 LValue *val;
1715 tmp->reg.size = 4;
1716 tmp->reg.data.offset += 4 * d;
1717
1718 Instruction *l = new_Instruction(func, OP_LOAD, TYPE_U32);
1719 l->setDef(0, (val = new_LValue(func, FILE_GPR)));
1720 l->setSrc(0, tmp);
1721 usei->bb->insertBefore(usei, l);
1722 ld->setSrc(d, val);
1723 val->noSpill = 1;
1724 }
1725 ld->setDef(0, lval);
1726 usei->bb->insertBefore(usei, ld);
1727 return lval;
1728 }
1729 } else {
1730 ld = new_Instruction(func, OP_CVT, ty);
1731 }
1732 ld->setDef(0, lval);
1733 ld->setSrc(0, slot);
1734 if (lval->reg.file == FILE_FLAGS)
1735 ld->flagsDef = 0;
1736
1737 usei->bb->insertBefore(usei, ld);
1738 return lval;
1739 }
1740
1741 static bool
1742 value_cmp(ValueRef *a, ValueRef *b) {
1743 Instruction *ai = a->getInsn(), *bi = b->getInsn();
1744 if (ai->bb != bi->bb)
1745 return ai->bb->getId() < bi->bb->getId();
1746 return ai->serial < bi->serial;
1747 }
1748
1749 // For each value that is to be spilled, go through all its definitions.
1750 // A value can have multiple definitions if it has been coalesced before.
1751 // For each definition, first go through all its uses and insert an unspill
1752 // instruction before it, then replace the use with the temporary register.
1753 // Unspill can be either a load from memory or simply a move to another
1754 // register file.
1755 // For "Pseudo" instructions (like PHI, SPLIT, MERGE) we can erase the use
1756 // if we have spilled to a memory location, or simply with the new register.
1757 // No load or conversion instruction should be needed.
1758 bool
1759 SpillCodeInserter::run(const std::list<ValuePair>& lst)
1760 {
1761 for (std::list<ValuePair>::const_iterator it = lst.begin(); it != lst.end();
1762 ++it) {
1763 LValue *lval = it->first->asLValue();
1764 Symbol *mem = it->second ? it->second->asSym() : NULL;
1765
1766 // Keep track of which instructions to delete later. Deleting them
1767 // inside the loop is unsafe since a single instruction may have
1768 // multiple destinations that all need to be spilled (like OP_SPLIT).
1769 unordered_set<Instruction *> to_del;
1770
1771 for (Value::DefIterator d = lval->defs.begin(); d != lval->defs.end();
1772 ++d) {
1773 Value *slot = mem ?
1774 static_cast<Value *>(mem) : new_LValue(func, FILE_GPR);
1775 Value *tmp = NULL;
1776 Instruction *last = NULL;
1777
1778 LValue *dval = (*d)->get()->asLValue();
1779 Instruction *defi = (*d)->getInsn();
1780
1781 // Sort all the uses by BB/instruction so that we don't unspill
1782 // multiple times in a row, and also remove a source of
1783 // non-determinism.
1784 std::vector<ValueRef *> refs(dval->uses.begin(), dval->uses.end());
1785 std::sort(refs.begin(), refs.end(), value_cmp);
1786
1787 // Unspill at each use *before* inserting spill instructions,
1788 // we don't want to have the spill instructions in the use list here.
1789 for (std::vector<ValueRef*>::const_iterator it = refs.begin();
1790 it != refs.end(); ++it) {
1791 ValueRef *u = *it;
1792 Instruction *usei = u->getInsn();
1793 assert(usei);
1794 if (usei->isPseudo()) {
1795 tmp = (slot->reg.file == FILE_MEMORY_LOCAL) ? NULL : slot;
1796 last = NULL;
1797 } else {
1798 if (!last || (usei != last->next && usei != last))
1799 tmp = unspill(usei, dval, slot);
1800 last = usei;
1801 }
1802 u->set(tmp);
1803 }
1804
1805 assert(defi);
1806 if (defi->isPseudo()) {
1807 d = lval->defs.erase(d);
1808 --d;
1809 if (slot->reg.file == FILE_MEMORY_LOCAL)
1810 to_del.insert(defi);
1811 else
1812 defi->setDef(0, slot);
1813 } else {
1814 spill(defi, slot, dval);
1815 }
1816 }
1817
1818 for (unordered_set<Instruction *>::const_iterator it = to_del.begin();
1819 it != to_del.end(); ++it)
1820 delete_Instruction(func->getProgram(), *it);
1821 }
1822
1823 // TODO: We're not trying to reuse old slots in a potential next iteration.
1824 // We have to update the slots' livei intervals to be able to do that.
1825 stackBase = stackSize;
1826 slots.clear();
1827 return true;
1828 }
1829
1830 bool
1831 RegAlloc::exec()
1832 {
1833 for (IteratorRef it = prog->calls.iteratorDFS(false);
1834 !it->end(); it->next()) {
1835 func = Function::get(reinterpret_cast<Graph::Node *>(it->get()));
1836
1837 func->tlsBase = prog->tlsSize;
1838 if (!execFunc())
1839 return false;
1840 prog->tlsSize += func->tlsSize;
1841 }
1842 return true;
1843 }
1844
1845 bool
1846 RegAlloc::execFunc()
1847 {
1848 InsertConstraintsPass insertConstr;
1849 PhiMovesPass insertPhiMoves;
1850 ArgumentMovesPass insertArgMoves;
1851 BuildIntervalsPass buildIntervals;
1852 SpillCodeInserter insertSpills(func);
1853
1854 GCRA gcra(func, insertSpills);
1855
1856 unsigned int i, retries;
1857 bool ret;
1858
1859 if (!func->ins.empty()) {
1860 // Insert a nop at the entry so inputs only used by the first instruction
1861 // don't count as having an empty live range.
1862 Instruction *nop = new_Instruction(func, OP_NOP, TYPE_NONE);
1863 BasicBlock::get(func->cfg.getRoot())->insertHead(nop);
1864 }
1865
1866 ret = insertConstr.exec(func);
1867 if (!ret)
1868 goto out;
1869
1870 ret = insertPhiMoves.run(func);
1871 if (!ret)
1872 goto out;
1873
1874 ret = insertArgMoves.run(func);
1875 if (!ret)
1876 goto out;
1877
1878 // TODO: need to fix up spill slot usage ranges to support > 1 retry
1879 for (retries = 0; retries < 3; ++retries) {
1880 if (retries && (prog->dbgFlags & NV50_IR_DEBUG_REG_ALLOC))
1881 INFO("Retry: %i\n", retries);
1882 if (prog->dbgFlags & NV50_IR_DEBUG_REG_ALLOC)
1883 func->print();
1884
1885 // spilling to registers may add live ranges, need to rebuild everything
1886 ret = true;
1887 for (sequence = func->cfg.nextSequence(), i = 0;
1888 ret && i <= func->loopNestingBound;
1889 sequence = func->cfg.nextSequence(), ++i)
1890 ret = buildLiveSets(BasicBlock::get(func->cfg.getRoot()));
1891 // reset marker
1892 for (ArrayList::Iterator bi = func->allBBlocks.iterator();
1893 !bi.end(); bi.next())
1894 BasicBlock::get(bi)->liveSet.marker = false;
1895 if (!ret)
1896 break;
1897 func->orderInstructions(this->insns);
1898
1899 ret = buildIntervals.run(func);
1900 if (!ret)
1901 break;
1902 ret = gcra.allocateRegisters(insns);
1903 if (ret)
1904 break; // success
1905 }
1906 INFO_DBG(prog->dbgFlags, REG_ALLOC, "RegAlloc done: %i\n", ret);
1907
1908 func->tlsSize = insertSpills.getStackSize();
1909 out:
1910 return ret;
1911 }
1912
1913 // TODO: check if modifying Instruction::join here breaks anything
1914 void
1915 GCRA::resolveSplitsAndMerges()
1916 {
1917 for (std::list<Instruction *>::iterator it = splits.begin();
1918 it != splits.end();
1919 ++it) {
1920 Instruction *split = *it;
1921 unsigned int reg = regs.idToBytes(split->getSrc(0));
1922 for (int d = 0; split->defExists(d); ++d) {
1923 Value *v = split->getDef(d);
1924 v->reg.data.id = regs.bytesToId(v, reg);
1925 v->join = v;
1926 reg += v->reg.size;
1927 }
1928 }
1929 splits.clear();
1930
1931 for (std::list<Instruction *>::iterator it = merges.begin();
1932 it != merges.end();
1933 ++it) {
1934 Instruction *merge = *it;
1935 unsigned int reg = regs.idToBytes(merge->getDef(0));
1936 for (int s = 0; merge->srcExists(s); ++s) {
1937 Value *v = merge->getSrc(s);
1938 v->reg.data.id = regs.bytesToId(v, reg);
1939 v->join = v;
1940 // If the value is defined by a phi/union node, we also need to
1941 // perform the same fixup on that node's sources, since after RA
1942 // their registers should be identical.
1943 if (v->getInsn()->op == OP_PHI || v->getInsn()->op == OP_UNION) {
1944 Instruction *phi = v->getInsn();
1945 for (int phis = 0; phi->srcExists(phis); ++phis) {
1946 phi->getSrc(phis)->join = v;
1947 phi->getSrc(phis)->reg.data.id = v->reg.data.id;
1948 }
1949 }
1950 reg += v->reg.size;
1951 }
1952 }
1953 merges.clear();
1954 }
1955
1956 bool Program::registerAllocation()
1957 {
1958 RegAlloc ra(this);
1959 return ra.exec();
1960 }
1961
1962 bool
1963 RegAlloc::InsertConstraintsPass::exec(Function *ir)
1964 {
1965 constrList.clear();
1966
1967 bool ret = run(ir, true, true);
1968 if (ret)
1969 ret = insertConstraintMoves();
1970 return ret;
1971 }
1972
1973 // TODO: make part of texture insn
1974 void
1975 RegAlloc::InsertConstraintsPass::textureMask(TexInstruction *tex)
1976 {
1977 Value *def[4];
1978 int c, k, d;
1979 uint8_t mask = 0;
1980
1981 for (d = 0, k = 0, c = 0; c < 4; ++c) {
1982 if (!(tex->tex.mask & (1 << c)))
1983 continue;
1984 if (tex->getDef(k)->refCount()) {
1985 mask |= 1 << c;
1986 def[d++] = tex->getDef(k);
1987 }
1988 ++k;
1989 }
1990 tex->tex.mask = mask;
1991
1992 for (c = 0; c < d; ++c)
1993 tex->setDef(c, def[c]);
1994 for (; c < 4; ++c)
1995 tex->setDef(c, NULL);
1996 }
1997
1998 bool
1999 RegAlloc::InsertConstraintsPass::detectConflict(Instruction *cst, int s)
2000 {
2001 Value *v = cst->getSrc(s);
2002
2003 // current register allocation can't handle it if a value participates in
2004 // multiple constraints
2005 for (Value::UseIterator it = v->uses.begin(); it != v->uses.end(); ++it) {
2006 if (cst != (*it)->getInsn())
2007 return true;
2008 }
2009
2010 // can start at s + 1 because detectConflict is called on all sources
2011 for (int c = s + 1; cst->srcExists(c); ++c)
2012 if (v == cst->getSrc(c))
2013 return true;
2014
2015 Instruction *defi = v->getInsn();
2016
2017 return (!defi || defi->constrainedDefs());
2018 }
2019
2020 void
2021 RegAlloc::InsertConstraintsPass::addConstraint(Instruction *i, int s, int n)
2022 {
2023 Instruction *cst;
2024 int d;
2025
2026 // first, look for an existing identical constraint op
2027 for (std::list<Instruction *>::iterator it = constrList.begin();
2028 it != constrList.end();
2029 ++it) {
2030 cst = (*it);
2031 if (!i->bb->dominatedBy(cst->bb))
2032 break;
2033 for (d = 0; d < n; ++d)
2034 if (cst->getSrc(d) != i->getSrc(d + s))
2035 break;
2036 if (d >= n) {
2037 for (d = 0; d < n; ++d, ++s)
2038 i->setSrc(s, cst->getDef(d));
2039 return;
2040 }
2041 }
2042 cst = new_Instruction(func, OP_CONSTRAINT, i->dType);
2043
2044 for (d = 0; d < n; ++s, ++d) {
2045 cst->setDef(d, new_LValue(func, FILE_GPR));
2046 cst->setSrc(d, i->getSrc(s));
2047 i->setSrc(s, cst->getDef(d));
2048 }
2049 i->bb->insertBefore(i, cst);
2050
2051 constrList.push_back(cst);
2052 }
2053
2054 // Add a dummy use of the pointer source of >= 8 byte loads after the load
2055 // to prevent it from being assigned a register which overlapping the load's
2056 // destination, which would produce random corruptions.
2057 void
2058 RegAlloc::InsertConstraintsPass::addHazard(Instruction *i, const ValueRef *src)
2059 {
2060 Instruction *hzd = new_Instruction(func, OP_NOP, TYPE_NONE);
2061 hzd->setSrc(0, src->get());
2062 i->bb->insertAfter(i, hzd);
2063
2064 }
2065
2066 // b32 { %r0 %r1 %r2 %r3 } -> b128 %r0q
2067 void
2068 RegAlloc::InsertConstraintsPass::condenseDefs(Instruction *insn)
2069 {
2070 int n;
2071 for (n = 0; insn->defExists(n) && insn->def(n).getFile() == FILE_GPR; ++n);
2072 condenseDefs(insn, 0, n - 1);
2073 }
2074
2075 void
2076 RegAlloc::InsertConstraintsPass::condenseDefs(Instruction *insn,
2077 const int a, const int b)
2078 {
2079 uint8_t size = 0;
2080 if (a >= b)
2081 return;
2082 for (int s = a; s <= b; ++s)
2083 size += insn->getDef(s)->reg.size;
2084 if (!size)
2085 return;
2086
2087 LValue *lval = new_LValue(func, FILE_GPR);
2088 lval->reg.size = size;
2089
2090 Instruction *split = new_Instruction(func, OP_SPLIT, typeOfSize(size));
2091 split->setSrc(0, lval);
2092 for (int d = a; d <= b; ++d) {
2093 split->setDef(d - a, insn->getDef(d));
2094 insn->setDef(d, NULL);
2095 }
2096 insn->setDef(a, lval);
2097
2098 for (int k = a + 1, d = b + 1; insn->defExists(d); ++d, ++k) {
2099 insn->setDef(k, insn->getDef(d));
2100 insn->setDef(d, NULL);
2101 }
2102 // carry over predicate if any (mainly for OP_UNION uses)
2103 split->setPredicate(insn->cc, insn->getPredicate());
2104
2105 insn->bb->insertAfter(insn, split);
2106 constrList.push_back(split);
2107 }
2108
2109 void
2110 RegAlloc::InsertConstraintsPass::condenseSrcs(Instruction *insn,
2111 const int a, const int b)
2112 {
2113 uint8_t size = 0;
2114 if (a >= b)
2115 return;
2116 for (int s = a; s <= b; ++s)
2117 size += insn->getSrc(s)->reg.size;
2118 if (!size)
2119 return;
2120 LValue *lval = new_LValue(func, FILE_GPR);
2121 lval->reg.size = size;
2122
2123 Value *save[3];
2124 insn->takeExtraSources(0, save);
2125
2126 Instruction *merge = new_Instruction(func, OP_MERGE, typeOfSize(size));
2127 merge->setDef(0, lval);
2128 for (int s = a, i = 0; s <= b; ++s, ++i) {
2129 merge->setSrc(i, insn->getSrc(s));
2130 }
2131 insn->moveSources(b + 1, a - b);
2132 insn->setSrc(a, lval);
2133 insn->bb->insertBefore(insn, merge);
2134
2135 insn->putExtraSources(0, save);
2136
2137 constrList.push_back(merge);
2138 }
2139
2140 bool
2141 RegAlloc::InsertConstraintsPass::isScalarTexGM107(TexInstruction *tex)
2142 {
2143 if (tex->tex.sIndirectSrc >= 0 ||
2144 tex->tex.rIndirectSrc >= 0 ||
2145 tex->tex.derivAll)
2146 return false;
2147
2148 if (tex->tex.mask == 5 || tex->tex.mask == 6)
2149 return false;
2150
2151 switch (tex->op) {
2152 case OP_TEX:
2153 case OP_TXF:
2154 case OP_TXG:
2155 case OP_TXL:
2156 break;
2157 default:
2158 return false;
2159 }
2160
2161 // legal variants:
2162 // TEXS.1D.LZ
2163 // TEXS.2D
2164 // TEXS.2D.LZ
2165 // TEXS.2D.LL
2166 // TEXS.2D.DC
2167 // TEXS.2D.LL.DC
2168 // TEXS.2D.LZ.DC
2169 // TEXS.A2D
2170 // TEXS.A2D.LZ
2171 // TEXS.A2D.LZ.DC
2172 // TEXS.3D
2173 // TEXS.3D.LZ
2174 // TEXS.CUBE
2175 // TEXS.CUBE.LL
2176
2177 // TLDS.1D.LZ
2178 // TLDS.1D.LL
2179 // TLDS.2D.LZ
2180 // TLSD.2D.LZ.AOFFI
2181 // TLDS.2D.LZ.MZ
2182 // TLDS.2D.LL
2183 // TLDS.2D.LL.AOFFI
2184 // TLDS.A2D.LZ
2185 // TLDS.3D.LZ
2186
2187 // TLD4S: all 2D/RECT variants and only offset
2188
2189 switch (tex->op) {
2190 case OP_TEX:
2191 if (tex->tex.useOffsets)
2192 return false;
2193
2194 switch (tex->tex.target.getEnum()) {
2195 case TEX_TARGET_1D:
2196 case TEX_TARGET_2D_ARRAY_SHADOW:
2197 return tex->tex.levelZero;
2198 case TEX_TARGET_CUBE:
2199 return !tex->tex.levelZero;
2200 case TEX_TARGET_2D:
2201 case TEX_TARGET_2D_ARRAY:
2202 case TEX_TARGET_2D_SHADOW:
2203 case TEX_TARGET_3D:
2204 case TEX_TARGET_RECT:
2205 case TEX_TARGET_RECT_SHADOW:
2206 return true;
2207 default:
2208 return false;
2209 }
2210
2211 case OP_TXL:
2212 if (tex->tex.useOffsets)
2213 return false;
2214
2215 switch (tex->tex.target.getEnum()) {
2216 case TEX_TARGET_2D:
2217 case TEX_TARGET_2D_SHADOW:
2218 case TEX_TARGET_RECT:
2219 case TEX_TARGET_RECT_SHADOW:
2220 case TEX_TARGET_CUBE:
2221 return true;
2222 default:
2223 return false;
2224 }
2225
2226 case OP_TXF:
2227 switch (tex->tex.target.getEnum()) {
2228 case TEX_TARGET_1D:
2229 return !tex->tex.useOffsets;
2230 case TEX_TARGET_2D:
2231 case TEX_TARGET_RECT:
2232 return true;
2233 case TEX_TARGET_2D_ARRAY:
2234 case TEX_TARGET_2D_MS:
2235 case TEX_TARGET_3D:
2236 return !tex->tex.useOffsets && tex->tex.levelZero;
2237 default:
2238 return false;
2239 }
2240
2241 case OP_TXG:
2242 if (tex->tex.useOffsets > 1)
2243 return false;
2244 if (tex->tex.mask != 0x3 && tex->tex.mask != 0xf)
2245 return false;
2246
2247 switch (tex->tex.target.getEnum()) {
2248 case TEX_TARGET_2D:
2249 case TEX_TARGET_2D_MS:
2250 case TEX_TARGET_2D_SHADOW:
2251 case TEX_TARGET_RECT:
2252 case TEX_TARGET_RECT_SHADOW:
2253 return true;
2254 default:
2255 return false;
2256 }
2257
2258 default:
2259 return false;
2260 }
2261 }
2262
2263 void
2264 RegAlloc::InsertConstraintsPass::handleScalarTexGM107(TexInstruction *tex)
2265 {
2266 int defCount = tex->defCount(0xff);
2267 int srcCount = tex->srcCount(0xff);
2268
2269 tex->tex.scalar = true;
2270
2271 // 1. handle defs
2272 if (defCount > 3)
2273 condenseDefs(tex, 2, 3);
2274 if (defCount > 1)
2275 condenseDefs(tex, 0, 1);
2276
2277 // 2. handle srcs
2278 // special case for TXF.A2D
2279 if (tex->op == OP_TXF && tex->tex.target == TEX_TARGET_2D_ARRAY) {
2280 assert(srcCount >= 3);
2281 condenseSrcs(tex, 1, 2);
2282 } else {
2283 if (srcCount > 3)
2284 condenseSrcs(tex, 2, 3);
2285 // only if we have more than 2 sources
2286 if (srcCount > 2)
2287 condenseSrcs(tex, 0, 1);
2288 }
2289
2290 assert(!tex->defExists(2) && !tex->srcExists(2));
2291 }
2292
2293 void
2294 RegAlloc::InsertConstraintsPass::texConstraintGM107(TexInstruction *tex)
2295 {
2296 int n, s;
2297
2298 if (isTextureOp(tex->op))
2299 textureMask(tex);
2300
2301 if (targ->getChipset() < NVISA_GV100_CHIPSET) {
2302 if (isScalarTexGM107(tex)) {
2303 handleScalarTexGM107(tex);
2304 return;
2305 }
2306
2307 assert(!tex->tex.scalar);
2308 condenseDefs(tex);
2309 } else {
2310 if (isTextureOp(tex->op)) {
2311 int defCount = tex->defCount(0xff);
2312 if (defCount > 3)
2313 condenseDefs(tex, 2, 3);
2314 if (defCount > 1)
2315 condenseDefs(tex, 0, 1);
2316 } else {
2317 condenseDefs(tex);
2318 }
2319 }
2320
2321 if (isSurfaceOp(tex->op)) {
2322 int s = tex->tex.target.getDim() +
2323 (tex->tex.target.isArray() || tex->tex.target.isCube());
2324 int n = 0;
2325
2326 switch (tex->op) {
2327 case OP_SUSTB:
2328 case OP_SUSTP:
2329 n = 4;
2330 break;
2331 case OP_SUREDB:
2332 case OP_SUREDP:
2333 if (tex->subOp == NV50_IR_SUBOP_ATOM_CAS)
2334 n = 2;
2335 break;
2336 default:
2337 break;
2338 }
2339
2340 if (s > 1)
2341 condenseSrcs(tex, 0, s - 1);
2342 if (n > 1)
2343 condenseSrcs(tex, 1, n); // do not condense the tex handle
2344 } else
2345 if (isTextureOp(tex->op)) {
2346 if (tex->op != OP_TXQ) {
2347 s = tex->tex.target.getArgCount() - tex->tex.target.isMS();
2348 if (tex->op == OP_TXD) {
2349 // Indirect handle belongs in the first arg
2350 if (tex->tex.rIndirectSrc >= 0)
2351 s++;
2352 if (!tex->tex.target.isArray() && tex->tex.useOffsets)
2353 s++;
2354 }
2355 n = tex->srcCount(0xff, true) - s;
2356 // TODO: Is this necessary? Perhaps just has to be aligned to the
2357 // level that the first arg is, not necessarily to 4. This
2358 // requirement has not been rigorously verified, as it has been on
2359 // Kepler.
2360 if (n > 0 && n < 3) {
2361 if (tex->srcExists(n + s)) // move potential predicate out of the way
2362 tex->moveSources(n + s, 3 - n);
2363 while (n < 3)
2364 tex->setSrc(s + n++, new_LValue(func, FILE_GPR));
2365 }
2366 } else {
2367 s = tex->srcCount(0xff, true);
2368 n = 0;
2369 }
2370
2371 if (s > 1)
2372 condenseSrcs(tex, 0, s - 1);
2373 if (n > 1) // NOTE: first call modified positions already
2374 condenseSrcs(tex, 1, n);
2375 }
2376 }
2377
2378 void
2379 RegAlloc::InsertConstraintsPass::texConstraintNVE0(TexInstruction *tex)
2380 {
2381 if (isTextureOp(tex->op))
2382 textureMask(tex);
2383 condenseDefs(tex);
2384
2385 if (tex->op == OP_SUSTB || tex->op == OP_SUSTP) {
2386 condenseSrcs(tex, 3, 6);
2387 } else
2388 if (isTextureOp(tex->op)) {
2389 int n = tex->srcCount(0xff, true);
2390 int s = n > 4 ? 4 : n;
2391 if (n > 4 && n < 7) {
2392 if (tex->srcExists(n)) // move potential predicate out of the way
2393 tex->moveSources(n, 7 - n);
2394
2395 while (n < 7)
2396 tex->setSrc(n++, new_LValue(func, FILE_GPR));
2397 }
2398 if (s > 1)
2399 condenseSrcs(tex, 0, s - 1);
2400 if (n > 4)
2401 condenseSrcs(tex, 1, n - s);
2402 }
2403 }
2404
2405 void
2406 RegAlloc::InsertConstraintsPass::texConstraintNVC0(TexInstruction *tex)
2407 {
2408 int n, s;
2409
2410 if (isTextureOp(tex->op))
2411 textureMask(tex);
2412
2413 if (tex->op == OP_TXQ) {
2414 s = tex->srcCount(0xff);
2415 n = 0;
2416 } else if (isSurfaceOp(tex->op)) {
2417 s = tex->tex.target.getDim() + (tex->tex.target.isArray() || tex->tex.target.isCube());
2418 if (tex->op == OP_SUSTB || tex->op == OP_SUSTP)
2419 n = 4;
2420 else
2421 n = 0;
2422 } else {
2423 s = tex->tex.target.getArgCount() - tex->tex.target.isMS();
2424 if (!tex->tex.target.isArray() &&
2425 (tex->tex.rIndirectSrc >= 0 || tex->tex.sIndirectSrc >= 0))
2426 ++s;
2427 if (tex->op == OP_TXD && tex->tex.useOffsets)
2428 ++s;
2429 n = tex->srcCount(0xff) - s;
2430 assert(n <= 4);
2431 }
2432
2433 if (s > 1)
2434 condenseSrcs(tex, 0, s - 1);
2435 if (n > 1) // NOTE: first call modified positions already
2436 condenseSrcs(tex, 1, n);
2437
2438 condenseDefs(tex);
2439 }
2440
2441 void
2442 RegAlloc::InsertConstraintsPass::texConstraintNV50(TexInstruction *tex)
2443 {
2444 Value *pred = tex->getPredicate();
2445 if (pred)
2446 tex->setPredicate(tex->cc, NULL);
2447
2448 textureMask(tex);
2449
2450 assert(tex->defExists(0) && tex->srcExists(0));
2451 // make src and def count match
2452 int c;
2453 for (c = 0; tex->srcExists(c) || tex->defExists(c); ++c) {
2454 if (!tex->srcExists(c))
2455 tex->setSrc(c, new_LValue(func, tex->getSrc(0)->asLValue()));
2456 else
2457 insertConstraintMove(tex, c);
2458 if (!tex->defExists(c))
2459 tex->setDef(c, new_LValue(func, tex->getDef(0)->asLValue()));
2460 }
2461 if (pred)
2462 tex->setPredicate(tex->cc, pred);
2463 condenseDefs(tex);
2464 condenseSrcs(tex, 0, c - 1);
2465 }
2466
2467 // Insert constraint markers for instructions whose multiple sources must be
2468 // located in consecutive registers.
2469 bool
2470 RegAlloc::InsertConstraintsPass::visit(BasicBlock *bb)
2471 {
2472 TexInstruction *tex;
2473 Instruction *next;
2474 int s, size;
2475
2476 targ = bb->getProgram()->getTarget();
2477
2478 for (Instruction *i = bb->getEntry(); i; i = next) {
2479 next = i->next;
2480
2481 if ((tex = i->asTex())) {
2482 switch (targ->getChipset() & ~0xf) {
2483 case 0x50:
2484 case 0x80:
2485 case 0x90:
2486 case 0xa0:
2487 texConstraintNV50(tex);
2488 break;
2489 case 0xc0:
2490 case 0xd0:
2491 texConstraintNVC0(tex);
2492 break;
2493 case 0xe0:
2494 case 0xf0:
2495 case 0x100:
2496 texConstraintNVE0(tex);
2497 break;
2498 case 0x110:
2499 case 0x120:
2500 case 0x130:
2501 case 0x140:
2502 texConstraintGM107(tex);
2503 break;
2504 default:
2505 break;
2506 }
2507 } else
2508 if (i->op == OP_EXPORT || i->op == OP_STORE) {
2509 for (size = typeSizeof(i->dType), s = 1; size > 0; ++s) {
2510 assert(i->srcExists(s));
2511 size -= i->getSrc(s)->reg.size;
2512 }
2513 condenseSrcs(i, 1, s - 1);
2514 } else
2515 if (i->op == OP_LOAD || i->op == OP_VFETCH) {
2516 condenseDefs(i);
2517 if (i->src(0).isIndirect(0) && typeSizeof(i->dType) >= 8)
2518 addHazard(i, i->src(0).getIndirect(0));
2519 if (i->src(0).isIndirect(1) && typeSizeof(i->dType) >= 8)
2520 addHazard(i, i->src(0).getIndirect(1));
2521 } else
2522 if (i->op == OP_UNION ||
2523 i->op == OP_MERGE ||
2524 i->op == OP_SPLIT) {
2525 constrList.push_back(i);
2526 }
2527 }
2528 return true;
2529 }
2530
2531 void
2532 RegAlloc::InsertConstraintsPass::insertConstraintMove(Instruction *cst, int s)
2533 {
2534 const uint8_t size = cst->src(s).getSize();
2535
2536 assert(cst->getSrc(s)->defs.size() == 1); // still SSA
2537
2538 Instruction *defi = cst->getSrc(s)->defs.front()->getInsn();
2539
2540 bool imm = defi->op == OP_MOV &&
2541 defi->src(0).getFile() == FILE_IMMEDIATE;
2542 bool load = defi->op == OP_LOAD &&
2543 defi->src(0).getFile() == FILE_MEMORY_CONST &&
2544 !defi->src(0).isIndirect(0);
2545 // catch some cases where don't really need MOVs
2546 if (cst->getSrc(s)->refCount() == 1 && !defi->constrainedDefs()) {
2547 if (imm || load) {
2548 // Move the defi right before the cst. No point in expanding
2549 // the range.
2550 defi->bb->remove(defi);
2551 cst->bb->insertBefore(cst, defi);
2552 }
2553 return;
2554 }
2555
2556 LValue *lval = new_LValue(func, cst->src(s).getFile());
2557 lval->reg.size = size;
2558
2559 Instruction *mov = new_Instruction(func, OP_MOV, typeOfSize(size));
2560 mov->setDef(0, lval);
2561 mov->setSrc(0, cst->getSrc(s));
2562
2563 if (load) {
2564 mov->op = OP_LOAD;
2565 mov->setSrc(0, defi->getSrc(0));
2566 } else if (imm) {
2567 mov->setSrc(0, defi->getSrc(0));
2568 }
2569
2570 if (defi->getPredicate())
2571 mov->setPredicate(defi->cc, defi->getPredicate());
2572
2573 cst->setSrc(s, mov->getDef(0));
2574 cst->bb->insertBefore(cst, mov);
2575
2576 cst->getDef(0)->asLValue()->noSpill = 1; // doesn't help
2577 }
2578
2579 // Insert extra moves so that, if multiple register constraints on a value are
2580 // in conflict, these conflicts can be resolved.
2581 bool
2582 RegAlloc::InsertConstraintsPass::insertConstraintMoves()
2583 {
2584 for (std::list<Instruction *>::iterator it = constrList.begin();
2585 it != constrList.end();
2586 ++it) {
2587 Instruction *cst = *it;
2588 Instruction *mov;
2589
2590 if (cst->op == OP_SPLIT && 0) {
2591 // spilling splits is annoying, just make sure they're separate
2592 for (int d = 0; cst->defExists(d); ++d) {
2593 if (!cst->getDef(d)->refCount())
2594 continue;
2595 LValue *lval = new_LValue(func, cst->def(d).getFile());
2596 const uint8_t size = cst->def(d).getSize();
2597 lval->reg.size = size;
2598
2599 mov = new_Instruction(func, OP_MOV, typeOfSize(size));
2600 mov->setSrc(0, lval);
2601 mov->setDef(0, cst->getDef(d));
2602 cst->setDef(d, mov->getSrc(0));
2603 cst->bb->insertAfter(cst, mov);
2604
2605 cst->getSrc(0)->asLValue()->noSpill = 1;
2606 mov->getSrc(0)->asLValue()->noSpill = 1;
2607 }
2608 } else
2609 if (cst->op == OP_MERGE || cst->op == OP_UNION) {
2610 for (int s = 0; cst->srcExists(s); ++s) {
2611 const uint8_t size = cst->src(s).getSize();
2612
2613 if (!cst->getSrc(s)->defs.size()) {
2614 mov = new_Instruction(func, OP_NOP, typeOfSize(size));
2615 mov->setDef(0, cst->getSrc(s));
2616 cst->bb->insertBefore(cst, mov);
2617 continue;
2618 }
2619
2620 insertConstraintMove(cst, s);
2621 }
2622 }
2623 }
2624
2625 return true;
2626 }
2627
2628 } // namespace nv50_ir