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