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