nv50/ir: normalize cube coordinates after derivatives have been computed
[mesa.git] / src / gallium / drivers / nouveau / codegen / nv50_ir_lowering_nvc0.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_build_util.h"
25
26 #include "codegen/nv50_ir_target_nvc0.h"
27 #include "codegen/nv50_ir_lowering_nvc0.h"
28
29 #include <limits>
30
31 namespace nv50_ir {
32
33 #define QOP_ADD 0
34 #define QOP_SUBR 1
35 #define QOP_SUB 2
36 #define QOP_MOV2 3
37
38 // UL UR LL LR
39 #define QUADOP(q, r, s, t) \
40 ((QOP_##q << 6) | (QOP_##r << 4) | \
41 (QOP_##s << 2) | (QOP_##t << 0))
42
43 void
44 NVC0LegalizeSSA::handleDIV(Instruction *i)
45 {
46 FlowInstruction *call;
47 int builtin;
48 Value *def[2];
49
50 bld.setPosition(i, false);
51 def[0] = bld.mkMovToReg(0, i->getSrc(0))->getDef(0);
52 def[1] = bld.mkMovToReg(1, i->getSrc(1))->getDef(0);
53 switch (i->dType) {
54 case TYPE_U32: builtin = NVC0_BUILTIN_DIV_U32; break;
55 case TYPE_S32: builtin = NVC0_BUILTIN_DIV_S32; break;
56 default:
57 return;
58 }
59 call = bld.mkFlow(OP_CALL, NULL, CC_ALWAYS, NULL);
60 bld.mkMov(i->getDef(0), def[(i->op == OP_DIV) ? 0 : 1]);
61 bld.mkClobber(FILE_GPR, (i->op == OP_DIV) ? 0xe : 0xd, 2);
62 bld.mkClobber(FILE_PREDICATE, (i->dType == TYPE_S32) ? 0xf : 0x3, 0);
63
64 call->fixed = 1;
65 call->absolute = call->builtin = 1;
66 call->target.builtin = builtin;
67 delete_Instruction(prog, i);
68 }
69
70 void
71 NVC0LegalizeSSA::handleRCPRSQ(Instruction *i)
72 {
73 assert(i->dType == TYPE_F64);
74 // There are instructions that will compute the high 32 bits of the 64-bit
75 // float. We will just stick 0 in the bottom 32 bits.
76
77 bld.setPosition(i, false);
78
79 // 1. Take the source and it up.
80 Value *src[2], *dst[2], *def = i->getDef(0);
81 bld.mkSplit(src, 4, i->getSrc(0));
82
83 // 2. We don't care about the low 32 bits of the destination. Stick a 0 in.
84 dst[0] = bld.loadImm(NULL, 0);
85 dst[1] = bld.getSSA();
86
87 // 3. The new version of the instruction takes the high 32 bits of the
88 // source and outputs the high 32 bits of the destination.
89 i->setSrc(0, src[1]);
90 i->setDef(0, dst[1]);
91 i->setType(TYPE_F32);
92 i->subOp = NV50_IR_SUBOP_RCPRSQ_64H;
93
94 // 4. Recombine the two dst pieces back into the original destination.
95 bld.setPosition(i, true);
96 bld.mkOp2(OP_MERGE, TYPE_U64, def, dst[0], dst[1]);
97 }
98
99 void
100 NVC0LegalizeSSA::handleFTZ(Instruction *i)
101 {
102 // Only want to flush float inputs
103 assert(i->sType == TYPE_F32);
104
105 // If we're already flushing denorms (and NaN's) to zero, no need for this.
106 if (i->dnz)
107 return;
108
109 // Only certain classes of operations can flush
110 OpClass cls = prog->getTarget()->getOpClass(i->op);
111 if (cls != OPCLASS_ARITH && cls != OPCLASS_COMPARE &&
112 cls != OPCLASS_CONVERT)
113 return;
114
115 i->ftz = true;
116 }
117
118 bool
119 NVC0LegalizeSSA::visit(Function *fn)
120 {
121 bld.setProgram(fn->getProgram());
122 return true;
123 }
124
125 bool
126 NVC0LegalizeSSA::visit(BasicBlock *bb)
127 {
128 Instruction *next;
129 for (Instruction *i = bb->getEntry(); i; i = next) {
130 next = i->next;
131 if (i->sType == TYPE_F32) {
132 if (prog->getType() != Program::TYPE_COMPUTE)
133 handleFTZ(i);
134 continue;
135 }
136 switch (i->op) {
137 case OP_DIV:
138 case OP_MOD:
139 handleDIV(i);
140 break;
141 case OP_RCP:
142 case OP_RSQ:
143 if (i->dType == TYPE_F64)
144 handleRCPRSQ(i);
145 break;
146 default:
147 break;
148 }
149 }
150 return true;
151 }
152
153 NVC0LegalizePostRA::NVC0LegalizePostRA(const Program *prog)
154 : rZero(NULL),
155 carry(NULL),
156 needTexBar(prog->getTarget()->getChipset() >= 0xe0)
157 {
158 }
159
160 bool
161 NVC0LegalizePostRA::insnDominatedBy(const Instruction *later,
162 const Instruction *early) const
163 {
164 if (early->bb == later->bb)
165 return early->serial < later->serial;
166 return later->bb->dominatedBy(early->bb);
167 }
168
169 void
170 NVC0LegalizePostRA::addTexUse(std::list<TexUse> &uses,
171 Instruction *usei, const Instruction *texi)
172 {
173 bool add = true;
174 for (std::list<TexUse>::iterator it = uses.begin();
175 it != uses.end();) {
176 if (insnDominatedBy(usei, it->insn)) {
177 add = false;
178 break;
179 }
180 if (insnDominatedBy(it->insn, usei))
181 it = uses.erase(it);
182 else
183 ++it;
184 }
185 if (add)
186 uses.push_back(TexUse(usei, texi));
187 }
188
189 // While it might be tempting to use the an algorithm that just looks at tex
190 // uses, not all texture results are guaranteed to be used on all paths. In
191 // the case where along some control flow path a texture result is never used,
192 // we might reuse that register for something else, creating a
193 // write-after-write hazard. So we have to manually look through all
194 // instructions looking for ones that reference the registers in question.
195 void
196 NVC0LegalizePostRA::findFirstUses(
197 Instruction *texi, std::list<TexUse> &uses)
198 {
199 int minGPR = texi->def(0).rep()->reg.data.id;
200 int maxGPR = minGPR + texi->def(0).rep()->reg.size / 4 - 1;
201
202 unordered_set<const BasicBlock *> visited;
203 findFirstUsesBB(minGPR, maxGPR, texi->next, texi, uses, visited);
204 }
205
206 void
207 NVC0LegalizePostRA::findFirstUsesBB(
208 int minGPR, int maxGPR, Instruction *start,
209 const Instruction *texi, std::list<TexUse> &uses,
210 unordered_set<const BasicBlock *> &visited)
211 {
212 const BasicBlock *bb = start->bb;
213
214 // We don't process the whole bb the first time around. This is correct,
215 // however we might be in a loop and hit this BB again, and need to process
216 // the full thing. So only mark a bb as visited if we processed it from the
217 // beginning.
218 if (start == bb->getEntry()) {
219 if (visited.find(bb) != visited.end())
220 return;
221 visited.insert(bb);
222 }
223
224 for (Instruction *insn = start; insn != bb->getExit(); insn = insn->next) {
225 if (insn->isNop())
226 continue;
227
228 for (int d = 0; insn->defExists(d); ++d) {
229 if (insn->def(d).getFile() != FILE_GPR ||
230 insn->def(d).rep()->reg.data.id < minGPR ||
231 insn->def(d).rep()->reg.data.id > maxGPR)
232 continue;
233 addTexUse(uses, insn, texi);
234 return;
235 }
236
237 for (int s = 0; insn->srcExists(s); ++s) {
238 if (insn->src(s).getFile() != FILE_GPR ||
239 insn->src(s).rep()->reg.data.id < minGPR ||
240 insn->src(s).rep()->reg.data.id > maxGPR)
241 continue;
242 addTexUse(uses, insn, texi);
243 return;
244 }
245 }
246
247 for (Graph::EdgeIterator ei = bb->cfg.outgoing(); !ei.end(); ei.next()) {
248 findFirstUsesBB(minGPR, maxGPR, BasicBlock::get(ei.getNode())->getEntry(),
249 texi, uses, visited);
250 }
251 }
252
253 // Texture barriers:
254 // This pass is a bit long and ugly and can probably be optimized.
255 //
256 // 1. obtain a list of TEXes and their outputs' first use(s)
257 // 2. calculate the barrier level of each first use (minimal number of TEXes,
258 // over all paths, between the TEX and the use in question)
259 // 3. for each barrier, if all paths from the source TEX to that barrier
260 // contain a barrier of lesser level, it can be culled
261 bool
262 NVC0LegalizePostRA::insertTextureBarriers(Function *fn)
263 {
264 std::list<TexUse> *uses;
265 std::vector<Instruction *> texes;
266 std::vector<int> bbFirstTex;
267 std::vector<int> bbFirstUse;
268 std::vector<int> texCounts;
269 std::vector<TexUse> useVec;
270 ArrayList insns;
271
272 fn->orderInstructions(insns);
273
274 texCounts.resize(fn->allBBlocks.getSize(), 0);
275 bbFirstTex.resize(fn->allBBlocks.getSize(), insns.getSize());
276 bbFirstUse.resize(fn->allBBlocks.getSize(), insns.getSize());
277
278 // tag BB CFG nodes by their id for later
279 for (ArrayList::Iterator i = fn->allBBlocks.iterator(); !i.end(); i.next()) {
280 BasicBlock *bb = reinterpret_cast<BasicBlock *>(i.get());
281 if (bb)
282 bb->cfg.tag = bb->getId();
283 }
284
285 // gather the first uses for each TEX
286 for (int i = 0; i < insns.getSize(); ++i) {
287 Instruction *tex = reinterpret_cast<Instruction *>(insns.get(i));
288 if (isTextureOp(tex->op)) {
289 texes.push_back(tex);
290 if (!texCounts.at(tex->bb->getId()))
291 bbFirstTex[tex->bb->getId()] = texes.size() - 1;
292 texCounts[tex->bb->getId()]++;
293 }
294 }
295 insns.clear();
296 if (texes.empty())
297 return false;
298 uses = new std::list<TexUse>[texes.size()];
299 if (!uses)
300 return false;
301 for (size_t i = 0; i < texes.size(); ++i) {
302 findFirstUses(texes[i], uses[i]);
303 }
304
305 // determine the barrier level at each use
306 for (size_t i = 0; i < texes.size(); ++i) {
307 for (std::list<TexUse>::iterator u = uses[i].begin(); u != uses[i].end();
308 ++u) {
309 BasicBlock *tb = texes[i]->bb;
310 BasicBlock *ub = u->insn->bb;
311 if (tb == ub) {
312 u->level = 0;
313 for (size_t j = i + 1; j < texes.size() &&
314 texes[j]->bb == tb && texes[j]->serial < u->insn->serial;
315 ++j)
316 u->level++;
317 } else {
318 u->level = fn->cfg.findLightestPathWeight(&tb->cfg,
319 &ub->cfg, texCounts);
320 if (u->level < 0) {
321 WARN("Failed to find path TEX -> TEXBAR\n");
322 u->level = 0;
323 continue;
324 }
325 // this counted all TEXes in the origin block, correct that
326 u->level -= i - bbFirstTex.at(tb->getId()) + 1 /* this TEX */;
327 // and did not count the TEXes in the destination block, add those
328 for (size_t j = bbFirstTex.at(ub->getId()); j < texes.size() &&
329 texes[j]->bb == ub && texes[j]->serial < u->insn->serial;
330 ++j)
331 u->level++;
332 }
333 assert(u->level >= 0);
334 useVec.push_back(*u);
335 }
336 }
337 delete[] uses;
338
339 // insert the barriers
340 for (size_t i = 0; i < useVec.size(); ++i) {
341 Instruction *prev = useVec[i].insn->prev;
342 if (useVec[i].level < 0)
343 continue;
344 if (prev && prev->op == OP_TEXBAR) {
345 if (prev->subOp > useVec[i].level)
346 prev->subOp = useVec[i].level;
347 prev->setSrc(prev->srcCount(), useVec[i].tex->getDef(0));
348 } else {
349 Instruction *bar = new_Instruction(func, OP_TEXBAR, TYPE_NONE);
350 bar->fixed = 1;
351 bar->subOp = useVec[i].level;
352 // make use explicit to ease latency calculation
353 bar->setSrc(bar->srcCount(), useVec[i].tex->getDef(0));
354 useVec[i].insn->bb->insertBefore(useVec[i].insn, bar);
355 }
356 }
357
358 if (fn->getProgram()->optLevel < 3)
359 return true;
360
361 std::vector<Limits> limitT, limitB, limitS; // entry, exit, single
362
363 limitT.resize(fn->allBBlocks.getSize(), Limits(0, 0));
364 limitB.resize(fn->allBBlocks.getSize(), Limits(0, 0));
365 limitS.resize(fn->allBBlocks.getSize());
366
367 // cull unneeded barriers (should do that earlier, but for simplicity)
368 IteratorRef bi = fn->cfg.iteratorCFG();
369 // first calculate min/max outstanding TEXes for each BB
370 for (bi->reset(); !bi->end(); bi->next()) {
371 Graph::Node *n = reinterpret_cast<Graph::Node *>(bi->get());
372 BasicBlock *bb = BasicBlock::get(n);
373 int min = 0;
374 int max = std::numeric_limits<int>::max();
375 for (Instruction *i = bb->getFirst(); i; i = i->next) {
376 if (isTextureOp(i->op)) {
377 min++;
378 if (max < std::numeric_limits<int>::max())
379 max++;
380 } else
381 if (i->op == OP_TEXBAR) {
382 min = MIN2(min, i->subOp);
383 max = MIN2(max, i->subOp);
384 }
385 }
386 // limits when looking at an isolated block
387 limitS[bb->getId()].min = min;
388 limitS[bb->getId()].max = max;
389 }
390 // propagate the min/max values
391 for (unsigned int l = 0; l <= fn->loopNestingBound; ++l) {
392 for (bi->reset(); !bi->end(); bi->next()) {
393 Graph::Node *n = reinterpret_cast<Graph::Node *>(bi->get());
394 BasicBlock *bb = BasicBlock::get(n);
395 const int bbId = bb->getId();
396 for (Graph::EdgeIterator ei = n->incident(); !ei.end(); ei.next()) {
397 BasicBlock *in = BasicBlock::get(ei.getNode());
398 const int inId = in->getId();
399 limitT[bbId].min = MAX2(limitT[bbId].min, limitB[inId].min);
400 limitT[bbId].max = MAX2(limitT[bbId].max, limitB[inId].max);
401 }
402 // I just hope this is correct ...
403 if (limitS[bbId].max == std::numeric_limits<int>::max()) {
404 // no barrier
405 limitB[bbId].min = limitT[bbId].min + limitS[bbId].min;
406 limitB[bbId].max = limitT[bbId].max + limitS[bbId].min;
407 } else {
408 // block contained a barrier
409 limitB[bbId].min = MIN2(limitS[bbId].max,
410 limitT[bbId].min + limitS[bbId].min);
411 limitB[bbId].max = MIN2(limitS[bbId].max,
412 limitT[bbId].max + limitS[bbId].min);
413 }
414 }
415 }
416 // finally delete unnecessary barriers
417 for (bi->reset(); !bi->end(); bi->next()) {
418 Graph::Node *n = reinterpret_cast<Graph::Node *>(bi->get());
419 BasicBlock *bb = BasicBlock::get(n);
420 Instruction *prev = NULL;
421 Instruction *next;
422 int max = limitT[bb->getId()].max;
423 for (Instruction *i = bb->getFirst(); i; i = next) {
424 next = i->next;
425 if (i->op == OP_TEXBAR) {
426 if (i->subOp >= max) {
427 delete_Instruction(prog, i);
428 i = NULL;
429 } else {
430 max = i->subOp;
431 if (prev && prev->op == OP_TEXBAR && prev->subOp >= max) {
432 delete_Instruction(prog, prev);
433 prev = NULL;
434 }
435 }
436 } else
437 if (isTextureOp(i->op)) {
438 max++;
439 }
440 if (i && !i->isNop())
441 prev = i;
442 }
443 }
444 return true;
445 }
446
447 bool
448 NVC0LegalizePostRA::visit(Function *fn)
449 {
450 if (needTexBar)
451 insertTextureBarriers(fn);
452
453 rZero = new_LValue(fn, FILE_GPR);
454 carry = new_LValue(fn, FILE_FLAGS);
455
456 rZero->reg.data.id = prog->getTarget()->getFileSize(FILE_GPR);
457 carry->reg.data.id = 0;
458
459 return true;
460 }
461
462 void
463 NVC0LegalizePostRA::replaceZero(Instruction *i)
464 {
465 for (int s = 0; i->srcExists(s); ++s) {
466 if (s == 2 && i->op == OP_SUCLAMP)
467 continue;
468 ImmediateValue *imm = i->getSrc(s)->asImm();
469 if (imm && imm->reg.data.u64 == 0)
470 i->setSrc(s, rZero);
471 }
472 }
473
474 // replace CONT with BRA for single unconditional continue
475 bool
476 NVC0LegalizePostRA::tryReplaceContWithBra(BasicBlock *bb)
477 {
478 if (bb->cfg.incidentCount() != 2 || bb->getEntry()->op != OP_PRECONT)
479 return false;
480 Graph::EdgeIterator ei = bb->cfg.incident();
481 if (ei.getType() != Graph::Edge::BACK)
482 ei.next();
483 if (ei.getType() != Graph::Edge::BACK)
484 return false;
485 BasicBlock *contBB = BasicBlock::get(ei.getNode());
486
487 if (!contBB->getExit() || contBB->getExit()->op != OP_CONT ||
488 contBB->getExit()->getPredicate())
489 return false;
490 contBB->getExit()->op = OP_BRA;
491 bb->remove(bb->getEntry()); // delete PRECONT
492
493 ei.next();
494 assert(ei.end() || ei.getType() != Graph::Edge::BACK);
495 return true;
496 }
497
498 // replace branches to join blocks with join ops
499 void
500 NVC0LegalizePostRA::propagateJoin(BasicBlock *bb)
501 {
502 if (bb->getEntry()->op != OP_JOIN || bb->getEntry()->asFlow()->limit)
503 return;
504 for (Graph::EdgeIterator ei = bb->cfg.incident(); !ei.end(); ei.next()) {
505 BasicBlock *in = BasicBlock::get(ei.getNode());
506 Instruction *exit = in->getExit();
507 if (!exit) {
508 in->insertTail(new FlowInstruction(func, OP_JOIN, bb));
509 // there should always be a terminator instruction
510 WARN("inserted missing terminator in BB:%i\n", in->getId());
511 } else
512 if (exit->op == OP_BRA) {
513 exit->op = OP_JOIN;
514 exit->asFlow()->limit = 1; // must-not-propagate marker
515 }
516 }
517 bb->remove(bb->getEntry());
518 }
519
520 bool
521 NVC0LegalizePostRA::visit(BasicBlock *bb)
522 {
523 Instruction *i, *next;
524
525 // remove pseudo operations and non-fixed no-ops, split 64 bit operations
526 for (i = bb->getFirst(); i; i = next) {
527 next = i->next;
528 if (i->op == OP_EMIT || i->op == OP_RESTART) {
529 if (!i->getDef(0)->refCount())
530 i->setDef(0, NULL);
531 if (i->src(0).getFile() == FILE_IMMEDIATE)
532 i->setSrc(0, rZero); // initial value must be 0
533 replaceZero(i);
534 } else
535 if (i->isNop()) {
536 bb->remove(i);
537 } else
538 if (i->op == OP_BAR && i->subOp == NV50_IR_SUBOP_BAR_SYNC &&
539 prog->getType() != Program::TYPE_COMPUTE) {
540 // It seems like barriers are never required for tessellation since
541 // the warp size is 32, and there are always at most 32 tcs threads.
542 bb->remove(i);
543 } else
544 if (i->op == OP_LOAD && i->subOp == NV50_IR_SUBOP_LDC_IS) {
545 int offset = i->src(0).get()->reg.data.offset;
546 if (abs(offset) > 0x10000)
547 i->src(0).get()->reg.fileIndex += offset >> 16;
548 i->src(0).get()->reg.data.offset = (int)(short)offset;
549 } else {
550 // TODO: Move this to before register allocation for operations that
551 // need the $c register !
552 if (typeSizeof(i->dType) == 8) {
553 Instruction *hi;
554 hi = BuildUtil::split64BitOpPostRA(func, i, rZero, carry);
555 if (hi)
556 next = hi;
557 }
558
559 if (i->op != OP_MOV && i->op != OP_PFETCH)
560 replaceZero(i);
561 }
562 }
563 if (!bb->getEntry())
564 return true;
565
566 if (!tryReplaceContWithBra(bb))
567 propagateJoin(bb);
568
569 return true;
570 }
571
572 NVC0LoweringPass::NVC0LoweringPass(Program *prog) : targ(prog->getTarget())
573 {
574 bld.setProgram(prog);
575 gMemBase = NULL;
576 }
577
578 bool
579 NVC0LoweringPass::visit(Function *fn)
580 {
581 if (prog->getType() == Program::TYPE_GEOMETRY) {
582 assert(!strncmp(fn->getName(), "MAIN", 4));
583 // TODO: when we generate actual functions pass this value along somehow
584 bld.setPosition(BasicBlock::get(fn->cfg.getRoot()), false);
585 gpEmitAddress = bld.loadImm(NULL, 0)->asLValue();
586 if (fn->cfgExit) {
587 bld.setPosition(BasicBlock::get(fn->cfgExit)->getExit(), false);
588 bld.mkMovToReg(0, gpEmitAddress);
589 }
590 }
591 return true;
592 }
593
594 bool
595 NVC0LoweringPass::visit(BasicBlock *bb)
596 {
597 return true;
598 }
599
600 inline Value *
601 NVC0LoweringPass::loadTexHandle(Value *ptr, unsigned int slot)
602 {
603 uint8_t b = prog->driver->io.auxCBSlot;
604 uint32_t off = prog->driver->io.texBindBase + slot * 4;
605 return bld.
606 mkLoadv(TYPE_U32, bld.mkSymbol(FILE_MEMORY_CONST, b, TYPE_U32, off), ptr);
607 }
608
609 // move array source to first slot, convert to u16, add indirections
610 bool
611 NVC0LoweringPass::handleTEX(TexInstruction *i)
612 {
613 const int dim = i->tex.target.getDim() + i->tex.target.isCube();
614 const int arg = i->tex.target.getArgCount();
615 const int lyr = arg - (i->tex.target.isMS() ? 2 : 1);
616 const int chipset = prog->getTarget()->getChipset();
617
618 /* Only normalize in the non-explicit derivatives case. For explicit
619 * derivatives, this is handled in handleManualTXD.
620 */
621 if (i->tex.target.isCube() && i->dPdx[0].get() == NULL) {
622 Value *src[3], *val;
623 int c;
624 for (c = 0; c < 3; ++c)
625 src[c] = bld.mkOp1v(OP_ABS, TYPE_F32, bld.getSSA(), i->getSrc(c));
626 val = bld.getScratch();
627 bld.mkOp2(OP_MAX, TYPE_F32, val, src[0], src[1]);
628 bld.mkOp2(OP_MAX, TYPE_F32, val, src[2], val);
629 bld.mkOp1(OP_RCP, TYPE_F32, val, val);
630 for (c = 0; c < 3; ++c) {
631 i->setSrc(c, bld.mkOp2v(OP_MUL, TYPE_F32, bld.getSSA(),
632 i->getSrc(c), val));
633 }
634 }
635
636 // Arguments to the TEX instruction are a little insane. Even though the
637 // encoding is identical between SM20 and SM30, the arguments mean
638 // different things between Fermi and Kepler+. A lot of arguments are
639 // optional based on flags passed to the instruction. This summarizes the
640 // order of things.
641 //
642 // Fermi:
643 // array/indirect
644 // coords
645 // sample
646 // lod bias
647 // depth compare
648 // offsets:
649 // - tg4: 8 bits each, either 2 (1 offset reg) or 8 (2 offset reg)
650 // - other: 4 bits each, single reg
651 //
652 // Kepler+:
653 // indirect handle
654 // array (+ offsets for txd in upper 16 bits)
655 // coords
656 // sample
657 // lod bias
658 // depth compare
659 // offsets (same as fermi, except txd which takes it with array)
660 //
661 // Maxwell (tex):
662 // array
663 // coords
664 // indirect handle
665 // sample
666 // lod bias
667 // depth compare
668 // offsets
669 //
670 // Maxwell (txd):
671 // indirect handle
672 // coords
673 // array + offsets
674 // derivatives
675
676 if (chipset >= NVISA_GK104_CHIPSET) {
677 if (i->tex.rIndirectSrc >= 0 || i->tex.sIndirectSrc >= 0) {
678 // XXX this ignores tsc, and assumes a 1:1 mapping
679 assert(i->tex.rIndirectSrc >= 0);
680 Value *hnd = loadTexHandle(
681 bld.mkOp2v(OP_SHL, TYPE_U32, bld.getSSA(),
682 i->getIndirectR(), bld.mkImm(2)),
683 i->tex.r);
684 i->tex.r = 0xff;
685 i->tex.s = 0x1f;
686 i->setIndirectR(hnd);
687 i->setIndirectS(NULL);
688 } else if (i->tex.r == i->tex.s || i->op == OP_TXF) {
689 i->tex.r += prog->driver->io.texBindBase / 4;
690 i->tex.s = 0; // only a single cX[] value possible here
691 } else {
692 Value *hnd = bld.getScratch();
693 Value *rHnd = loadTexHandle(NULL, i->tex.r);
694 Value *sHnd = loadTexHandle(NULL, i->tex.s);
695
696 bld.mkOp3(OP_INSBF, TYPE_U32, hnd, rHnd, bld.mkImm(0x1400), sHnd);
697
698 i->tex.r = 0; // not used for indirect tex
699 i->tex.s = 0;
700 i->setIndirectR(hnd);
701 }
702 if (i->tex.target.isArray()) {
703 LValue *layer = new_LValue(func, FILE_GPR);
704 Value *src = i->getSrc(lyr);
705 const int sat = (i->op == OP_TXF) ? 1 : 0;
706 DataType sTy = (i->op == OP_TXF) ? TYPE_U32 : TYPE_F32;
707 bld.mkCvt(OP_CVT, TYPE_U16, layer, sTy, src)->saturate = sat;
708 if (i->op != OP_TXD || chipset < NVISA_GM107_CHIPSET) {
709 for (int s = dim; s >= 1; --s)
710 i->setSrc(s, i->getSrc(s - 1));
711 i->setSrc(0, layer);
712 } else {
713 i->setSrc(dim, layer);
714 }
715 }
716 // Move the indirect reference to the first place
717 if (i->tex.rIndirectSrc >= 0 && (
718 i->op == OP_TXD || chipset < NVISA_GM107_CHIPSET)) {
719 Value *hnd = i->getIndirectR();
720
721 i->setIndirectR(NULL);
722 i->moveSources(0, 1);
723 i->setSrc(0, hnd);
724 i->tex.rIndirectSrc = 0;
725 i->tex.sIndirectSrc = -1;
726 }
727 } else
728 // (nvc0) generate and move the tsc/tic/array source to the front
729 if (i->tex.target.isArray() || i->tex.rIndirectSrc >= 0 || i->tex.sIndirectSrc >= 0) {
730 LValue *src = new_LValue(func, FILE_GPR); // 0xttxsaaaa
731
732 Value *ticRel = i->getIndirectR();
733 Value *tscRel = i->getIndirectS();
734
735 if (ticRel) {
736 i->setSrc(i->tex.rIndirectSrc, NULL);
737 if (i->tex.r)
738 ticRel = bld.mkOp2v(OP_ADD, TYPE_U32, bld.getScratch(),
739 ticRel, bld.mkImm(i->tex.r));
740 }
741 if (tscRel) {
742 i->setSrc(i->tex.sIndirectSrc, NULL);
743 if (i->tex.s)
744 tscRel = bld.mkOp2v(OP_ADD, TYPE_U32, bld.getScratch(),
745 tscRel, bld.mkImm(i->tex.s));
746 }
747
748 Value *arrayIndex = i->tex.target.isArray() ? i->getSrc(lyr) : NULL;
749 for (int s = dim; s >= 1; --s)
750 i->setSrc(s, i->getSrc(s - 1));
751 i->setSrc(0, arrayIndex);
752
753 if (arrayIndex) {
754 int sat = (i->op == OP_TXF) ? 1 : 0;
755 DataType sTy = (i->op == OP_TXF) ? TYPE_U32 : TYPE_F32;
756 bld.mkCvt(OP_CVT, TYPE_U16, src, sTy, arrayIndex)->saturate = sat;
757 } else {
758 bld.loadImm(src, 0);
759 }
760
761 if (ticRel)
762 bld.mkOp3(OP_INSBF, TYPE_U32, src, ticRel, bld.mkImm(0x0917), src);
763 if (tscRel)
764 bld.mkOp3(OP_INSBF, TYPE_U32, src, tscRel, bld.mkImm(0x0710), src);
765
766 i->setSrc(0, src);
767 }
768
769 // For nvc0, the sample id has to be in the second operand, as the offset
770 // does. Right now we don't know how to pass both in, and this case can't
771 // happen with OpenGL. On nve0, the sample id is part of the texture
772 // coordinate argument.
773 assert(chipset >= NVISA_GK104_CHIPSET ||
774 !i->tex.useOffsets || !i->tex.target.isMS());
775
776 // offset is between lod and dc
777 if (i->tex.useOffsets) {
778 int n, c;
779 int s = i->srcCount(0xff, true);
780 if (i->op != OP_TXD || chipset < NVISA_GK104_CHIPSET) {
781 if (i->tex.target.isShadow())
782 s--;
783 if (i->srcExists(s)) // move potential predicate out of the way
784 i->moveSources(s, 1);
785 if (i->tex.useOffsets == 4 && i->srcExists(s + 1))
786 i->moveSources(s + 1, 1);
787 }
788 if (i->op == OP_TXG) {
789 // Either there is 1 offset, which goes into the 2 low bytes of the
790 // first source, or there are 4 offsets, which go into 2 sources (8
791 // values, 1 byte each).
792 Value *offs[2] = {NULL, NULL};
793 for (n = 0; n < i->tex.useOffsets; n++) {
794 for (c = 0; c < 2; ++c) {
795 if ((n % 2) == 0 && c == 0)
796 offs[n / 2] = i->offset[n][c].get();
797 else
798 bld.mkOp3(OP_INSBF, TYPE_U32,
799 offs[n / 2],
800 i->offset[n][c].get(),
801 bld.mkImm(0x800 | ((n * 16 + c * 8) % 32)),
802 offs[n / 2]);
803 }
804 }
805 i->setSrc(s, offs[0]);
806 if (offs[1])
807 i->setSrc(s + 1, offs[1]);
808 } else {
809 unsigned imm = 0;
810 assert(i->tex.useOffsets == 1);
811 for (c = 0; c < 3; ++c) {
812 ImmediateValue val;
813 if (!i->offset[0][c].getImmediate(val))
814 assert(!"non-immediate offset passed to non-TXG");
815 imm |= (val.reg.data.u32 & 0xf) << (c * 4);
816 }
817 if (i->op == OP_TXD && chipset >= NVISA_GK104_CHIPSET) {
818 // The offset goes into the upper 16 bits of the array index. So
819 // create it if it's not already there, and INSBF it if it already
820 // is.
821 s = (i->tex.rIndirectSrc >= 0) ? 1 : 0;
822 if (chipset >= NVISA_GM107_CHIPSET)
823 s += dim;
824 if (i->tex.target.isArray()) {
825 bld.mkOp3(OP_INSBF, TYPE_U32, i->getSrc(s),
826 bld.loadImm(NULL, imm), bld.mkImm(0xc10),
827 i->getSrc(s));
828 } else {
829 i->moveSources(s, 1);
830 i->setSrc(s, bld.loadImm(NULL, imm << 16));
831 }
832 } else {
833 i->setSrc(s, bld.loadImm(NULL, imm));
834 }
835 }
836 }
837
838 if (chipset >= NVISA_GK104_CHIPSET) {
839 //
840 // If TEX requires more than 4 sources, the 2nd register tuple must be
841 // aligned to 4, even if it consists of just a single 4-byte register.
842 //
843 // XXX HACK: We insert 0 sources to avoid the 5 or 6 regs case.
844 //
845 int s = i->srcCount(0xff, true);
846 if (s > 4 && s < 7) {
847 if (i->srcExists(s)) // move potential predicate out of the way
848 i->moveSources(s, 7 - s);
849 while (s < 7)
850 i->setSrc(s++, bld.loadImm(NULL, 0));
851 }
852 }
853
854 return true;
855 }
856
857 bool
858 NVC0LoweringPass::handleManualTXD(TexInstruction *i)
859 {
860 static const uint8_t qOps[4][2] =
861 {
862 { QUADOP(MOV2, ADD, MOV2, ADD), QUADOP(MOV2, MOV2, ADD, ADD) }, // l0
863 { QUADOP(SUBR, MOV2, SUBR, MOV2), QUADOP(MOV2, MOV2, ADD, ADD) }, // l1
864 { QUADOP(MOV2, ADD, MOV2, ADD), QUADOP(SUBR, SUBR, MOV2, MOV2) }, // l2
865 { QUADOP(SUBR, MOV2, SUBR, MOV2), QUADOP(SUBR, SUBR, MOV2, MOV2) }, // l3
866 };
867 Value *def[4][4];
868 Value *crd[3];
869 Instruction *tex;
870 Value *zero = bld.loadImm(bld.getSSA(), 0);
871 int l, c;
872 const int dim = i->tex.target.getDim() + i->tex.target.isCube();
873 const int array = i->tex.target.isArray();
874
875 i->op = OP_TEX; // no need to clone dPdx/dPdy later
876
877 for (c = 0; c < dim; ++c)
878 crd[c] = bld.getScratch();
879
880 bld.mkOp(OP_QUADON, TYPE_NONE, NULL);
881 for (l = 0; l < 4; ++l) {
882 Value *src[3], *val;
883 // mov coordinates from lane l to all lanes
884 for (c = 0; c < dim; ++c)
885 bld.mkQuadop(0x00, crd[c], l, i->getSrc(c + array), zero);
886 // add dPdx from lane l to lanes dx
887 for (c = 0; c < dim; ++c)
888 bld.mkQuadop(qOps[l][0], crd[c], l, i->dPdx[c].get(), crd[c]);
889 // add dPdy from lane l to lanes dy
890 for (c = 0; c < dim; ++c)
891 bld.mkQuadop(qOps[l][1], crd[c], l, i->dPdy[c].get(), crd[c]);
892 // normalize cube coordinates
893 if (i->tex.target.isCube()) {
894 for (c = 0; c < 3; ++c)
895 src[c] = bld.mkOp1v(OP_ABS, TYPE_F32, bld.getSSA(), crd[c]);
896 val = bld.getScratch();
897 bld.mkOp2(OP_MAX, TYPE_F32, val, src[0], src[1]);
898 bld.mkOp2(OP_MAX, TYPE_F32, val, src[2], val);
899 bld.mkOp1(OP_RCP, TYPE_F32, val, val);
900 for (c = 0; c < 3; ++c)
901 src[c] = bld.mkOp2v(OP_MUL, TYPE_F32, bld.getSSA(), crd[c], val);
902 } else {
903 for (c = 0; c < dim; ++c)
904 src[c] = crd[c];
905 }
906 // texture
907 bld.insert(tex = cloneForward(func, i));
908 for (c = 0; c < dim; ++c)
909 tex->setSrc(c + array, src[c]);
910 // save results
911 for (c = 0; i->defExists(c); ++c) {
912 Instruction *mov;
913 def[c][l] = bld.getSSA();
914 mov = bld.mkMov(def[c][l], tex->getDef(c));
915 mov->fixed = 1;
916 mov->lanes = 1 << l;
917 }
918 }
919 bld.mkOp(OP_QUADPOP, TYPE_NONE, NULL);
920
921 for (c = 0; i->defExists(c); ++c) {
922 Instruction *u = bld.mkOp(OP_UNION, TYPE_U32, i->getDef(c));
923 for (l = 0; l < 4; ++l)
924 u->setSrc(l, def[c][l]);
925 }
926
927 i->bb->remove(i);
928 return true;
929 }
930
931 bool
932 NVC0LoweringPass::handleTXD(TexInstruction *txd)
933 {
934 int dim = txd->tex.target.getDim() + txd->tex.target.isCube();
935 unsigned arg = txd->tex.target.getArgCount();
936 unsigned expected_args = arg;
937 const int chipset = prog->getTarget()->getChipset();
938
939 if (chipset >= NVISA_GK104_CHIPSET) {
940 if (!txd->tex.target.isArray() && txd->tex.useOffsets)
941 expected_args++;
942 if (txd->tex.rIndirectSrc >= 0 || txd->tex.sIndirectSrc >= 0)
943 expected_args++;
944 } else {
945 if (txd->tex.useOffsets)
946 expected_args++;
947 if (!txd->tex.target.isArray() && (
948 txd->tex.rIndirectSrc >= 0 || txd->tex.sIndirectSrc >= 0))
949 expected_args++;
950 }
951
952 if (expected_args > 4 ||
953 dim > 2 ||
954 txd->tex.target.isShadow())
955 txd->op = OP_TEX;
956
957 handleTEX(txd);
958 while (txd->srcExists(arg))
959 ++arg;
960
961 txd->tex.derivAll = true;
962 if (txd->op == OP_TEX)
963 return handleManualTXD(txd);
964
965 assert(arg == expected_args);
966 for (int c = 0; c < dim; ++c) {
967 txd->setSrc(arg + c * 2 + 0, txd->dPdx[c]);
968 txd->setSrc(arg + c * 2 + 1, txd->dPdy[c]);
969 txd->dPdx[c].set(NULL);
970 txd->dPdy[c].set(NULL);
971 }
972 return true;
973 }
974
975 bool
976 NVC0LoweringPass::handleTXQ(TexInstruction *txq)
977 {
978 const int chipset = prog->getTarget()->getChipset();
979 if (chipset >= NVISA_GK104_CHIPSET && txq->tex.rIndirectSrc < 0)
980 txq->tex.r += prog->driver->io.texBindBase / 4;
981
982 if (txq->tex.rIndirectSrc < 0)
983 return true;
984
985 Value *ticRel = txq->getIndirectR();
986
987 txq->setIndirectS(NULL);
988 txq->tex.sIndirectSrc = -1;
989
990 assert(ticRel);
991
992 if (chipset < NVISA_GK104_CHIPSET) {
993 LValue *src = new_LValue(func, FILE_GPR); // 0xttxsaaaa
994
995 txq->setSrc(txq->tex.rIndirectSrc, NULL);
996 if (txq->tex.r)
997 ticRel = bld.mkOp2v(OP_ADD, TYPE_U32, bld.getScratch(),
998 ticRel, bld.mkImm(txq->tex.r));
999
1000 bld.mkOp2(OP_SHL, TYPE_U32, src, ticRel, bld.mkImm(0x17));
1001
1002 txq->moveSources(0, 1);
1003 txq->setSrc(0, src);
1004 } else {
1005 Value *hnd = loadTexHandle(
1006 bld.mkOp2v(OP_SHL, TYPE_U32, bld.getSSA(),
1007 txq->getIndirectR(), bld.mkImm(2)),
1008 txq->tex.r);
1009 txq->tex.r = 0xff;
1010 txq->tex.s = 0x1f;
1011
1012 txq->setIndirectR(NULL);
1013 txq->moveSources(0, 1);
1014 txq->setSrc(0, hnd);
1015 txq->tex.rIndirectSrc = 0;
1016 }
1017
1018 return true;
1019 }
1020
1021 bool
1022 NVC0LoweringPass::handleTXLQ(TexInstruction *i)
1023 {
1024 /* The outputs are inverted compared to what the TGSI instruction
1025 * expects. Take that into account in the mask.
1026 */
1027 assert((i->tex.mask & ~3) == 0);
1028 if (i->tex.mask == 1)
1029 i->tex.mask = 2;
1030 else if (i->tex.mask == 2)
1031 i->tex.mask = 1;
1032 handleTEX(i);
1033 bld.setPosition(i, true);
1034
1035 /* The returned values are not quite what we want:
1036 * (a) convert from s16/u16 to f32
1037 * (b) multiply by 1/256
1038 */
1039 for (int def = 0; def < 2; ++def) {
1040 if (!i->defExists(def))
1041 continue;
1042 enum DataType type = TYPE_S16;
1043 if (i->tex.mask == 2 || def > 0)
1044 type = TYPE_U16;
1045 bld.mkCvt(OP_CVT, TYPE_F32, i->getDef(def), type, i->getDef(def));
1046 bld.mkOp2(OP_MUL, TYPE_F32, i->getDef(def),
1047 i->getDef(def), bld.loadImm(NULL, 1.0f / 256));
1048 }
1049 if (i->tex.mask == 3) {
1050 LValue *t = new_LValue(func, FILE_GPR);
1051 bld.mkMov(t, i->getDef(0));
1052 bld.mkMov(i->getDef(0), i->getDef(1));
1053 bld.mkMov(i->getDef(1), t);
1054 }
1055 return true;
1056 }
1057
1058 bool
1059 NVC0LoweringPass::handleSUQ(Instruction *suq)
1060 {
1061 suq->op = OP_MOV;
1062 suq->setSrc(0, loadResLength32(suq->getIndirect(0, 1),
1063 suq->getSrc(0)->reg.fileIndex * 16));
1064 suq->setIndirect(0, 0, NULL);
1065 suq->setIndirect(0, 1, NULL);
1066 return true;
1067 }
1068
1069 void
1070 NVC0LoweringPass::handleSharedATOM(Instruction *atom)
1071 {
1072 assert(atom->src(0).getFile() == FILE_MEMORY_SHARED);
1073
1074 BasicBlock *currBB = atom->bb;
1075 BasicBlock *tryLockAndSetBB = atom->bb->splitBefore(atom, false);
1076 BasicBlock *joinBB = atom->bb->splitAfter(atom);
1077
1078 bld.setPosition(currBB, true);
1079 assert(!currBB->joinAt);
1080 currBB->joinAt = bld.mkFlow(OP_JOINAT, joinBB, CC_ALWAYS, NULL);
1081
1082 bld.mkFlow(OP_BRA, tryLockAndSetBB, CC_ALWAYS, NULL);
1083 currBB->cfg.attach(&tryLockAndSetBB->cfg, Graph::Edge::TREE);
1084
1085 bld.setPosition(tryLockAndSetBB, true);
1086
1087 Instruction *ld =
1088 bld.mkLoad(TYPE_U32, atom->getDef(0),
1089 bld.mkSymbol(FILE_MEMORY_SHARED, 0, TYPE_U32, 0), NULL);
1090 ld->setDef(1, bld.getSSA(1, FILE_PREDICATE));
1091 ld->subOp = NV50_IR_SUBOP_LOAD_LOCKED;
1092
1093 Value *stVal;
1094 if (atom->subOp == NV50_IR_SUBOP_ATOM_EXCH) {
1095 // Read the old value, and write the new one.
1096 stVal = atom->getSrc(1);
1097 } else if (atom->subOp == NV50_IR_SUBOP_ATOM_CAS) {
1098 CmpInstruction *set =
1099 bld.mkCmp(OP_SET, CC_EQ, TYPE_U32, bld.getSSA(1, FILE_PREDICATE),
1100 TYPE_U32, ld->getDef(0), atom->getSrc(1));
1101 set->setPredicate(CC_P, ld->getDef(1));
1102
1103 Instruction *selp =
1104 bld.mkOp3(OP_SELP, TYPE_U32, bld.getSSA(), ld->getDef(0),
1105 atom->getSrc(2), set->getDef(0));
1106 selp->src(2).mod = Modifier(NV50_IR_MOD_NOT);
1107 selp->setPredicate(CC_P, ld->getDef(1));
1108
1109 stVal = selp->getDef(0);
1110 } else {
1111 operation op;
1112
1113 switch (atom->subOp) {
1114 case NV50_IR_SUBOP_ATOM_ADD:
1115 op = OP_ADD;
1116 break;
1117 case NV50_IR_SUBOP_ATOM_AND:
1118 op = OP_AND;
1119 break;
1120 case NV50_IR_SUBOP_ATOM_OR:
1121 op = OP_OR;
1122 break;
1123 case NV50_IR_SUBOP_ATOM_XOR:
1124 op = OP_XOR;
1125 break;
1126 case NV50_IR_SUBOP_ATOM_MIN:
1127 op = OP_MIN;
1128 break;
1129 case NV50_IR_SUBOP_ATOM_MAX:
1130 op = OP_MAX;
1131 break;
1132 default:
1133 assert(0);
1134 return;
1135 }
1136
1137 Instruction *i =
1138 bld.mkOp2(op, atom->dType, bld.getSSA(), ld->getDef(0),
1139 atom->getSrc(1));
1140 i->setPredicate(CC_P, ld->getDef(1));
1141
1142 stVal = i->getDef(0);
1143 }
1144
1145 Instruction *st =
1146 bld.mkStore(OP_STORE, TYPE_U32,
1147 bld.mkSymbol(FILE_MEMORY_SHARED, 0, TYPE_U32, 0),
1148 NULL, stVal);
1149 st->setPredicate(CC_P, ld->getDef(1));
1150 st->subOp = NV50_IR_SUBOP_STORE_UNLOCKED;
1151
1152 // Loop until the lock is acquired.
1153 bld.mkFlow(OP_BRA, tryLockAndSetBB, CC_NOT_P, ld->getDef(1));
1154 tryLockAndSetBB->cfg.attach(&tryLockAndSetBB->cfg, Graph::Edge::BACK);
1155 tryLockAndSetBB->cfg.attach(&joinBB->cfg, Graph::Edge::CROSS);
1156 bld.mkFlow(OP_BRA, joinBB, CC_ALWAYS, NULL);
1157
1158 bld.remove(atom);
1159
1160 bld.setPosition(joinBB, false);
1161 bld.mkFlow(OP_JOIN, NULL, CC_ALWAYS, NULL)->fixed = 1;
1162 }
1163
1164 bool
1165 NVC0LoweringPass::handleATOM(Instruction *atom)
1166 {
1167 SVSemantic sv;
1168 Value *ptr = atom->getIndirect(0, 0), *ind = atom->getIndirect(0, 1), *base;
1169
1170 switch (atom->src(0).getFile()) {
1171 case FILE_MEMORY_LOCAL:
1172 sv = SV_LBASE;
1173 break;
1174 case FILE_MEMORY_SHARED:
1175 handleSharedATOM(atom);
1176 return true;
1177 default:
1178 assert(atom->src(0).getFile() == FILE_MEMORY_GLOBAL);
1179 base = loadResInfo64(ind, atom->getSrc(0)->reg.fileIndex * 16);
1180 assert(base->reg.size == 8);
1181 if (ptr)
1182 base = bld.mkOp2v(OP_ADD, TYPE_U64, base, base, ptr);
1183 assert(base->reg.size == 8);
1184 atom->setIndirect(0, 0, base);
1185 return true;
1186 }
1187 base =
1188 bld.mkOp1v(OP_RDSV, TYPE_U32, bld.getScratch(), bld.mkSysVal(sv, 0));
1189
1190 atom->setSrc(0, cloneShallow(func, atom->getSrc(0)));
1191 atom->getSrc(0)->reg.file = FILE_MEMORY_GLOBAL;
1192 if (ptr)
1193 base = bld.mkOp2v(OP_ADD, TYPE_U32, base, base, ptr);
1194 atom->setIndirect(0, 1, NULL);
1195 atom->setIndirect(0, 0, base);
1196
1197 return true;
1198 }
1199
1200 bool
1201 NVC0LoweringPass::handleCasExch(Instruction *cas, bool needCctl)
1202 {
1203 if (cas->src(0).getFile() == FILE_MEMORY_SHARED) {
1204 // ATOM_CAS and ATOM_EXCH are handled in handleSharedATOM().
1205 return false;
1206 }
1207
1208 if (cas->subOp != NV50_IR_SUBOP_ATOM_CAS &&
1209 cas->subOp != NV50_IR_SUBOP_ATOM_EXCH)
1210 return false;
1211 bld.setPosition(cas, true);
1212
1213 if (needCctl) {
1214 Instruction *cctl = bld.mkOp1(OP_CCTL, TYPE_NONE, NULL, cas->getSrc(0));
1215 cctl->setIndirect(0, 0, cas->getIndirect(0, 0));
1216 cctl->fixed = 1;
1217 cctl->subOp = NV50_IR_SUBOP_CCTL_IV;
1218 if (cas->isPredicated())
1219 cctl->setPredicate(cas->cc, cas->getPredicate());
1220 }
1221
1222 if (cas->subOp == NV50_IR_SUBOP_ATOM_CAS) {
1223 // CAS is crazy. It's 2nd source is a double reg, and the 3rd source
1224 // should be set to the high part of the double reg or bad things will
1225 // happen elsewhere in the universe.
1226 // Also, it sometimes returns the new value instead of the old one
1227 // under mysterious circumstances.
1228 Value *dreg = bld.getSSA(8);
1229 bld.setPosition(cas, false);
1230 bld.mkOp2(OP_MERGE, TYPE_U64, dreg, cas->getSrc(1), cas->getSrc(2));
1231 cas->setSrc(1, dreg);
1232 cas->setSrc(2, dreg);
1233 }
1234
1235 return true;
1236 }
1237
1238 inline Value *
1239 NVC0LoweringPass::loadResInfo32(Value *ptr, uint32_t off)
1240 {
1241 uint8_t b = prog->driver->io.auxCBSlot;
1242 off += prog->driver->io.suInfoBase;
1243 return bld.
1244 mkLoadv(TYPE_U32, bld.mkSymbol(FILE_MEMORY_CONST, b, TYPE_U32, off), ptr);
1245 }
1246
1247 inline Value *
1248 NVC0LoweringPass::loadResInfo64(Value *ptr, uint32_t off)
1249 {
1250 uint8_t b = prog->driver->io.auxCBSlot;
1251 off += prog->driver->io.suInfoBase;
1252
1253 if (ptr)
1254 ptr = bld.mkOp2v(OP_SHL, TYPE_U32, bld.getScratch(), ptr, bld.mkImm(4));
1255
1256 return bld.
1257 mkLoadv(TYPE_U64, bld.mkSymbol(FILE_MEMORY_CONST, b, TYPE_U64, off), ptr);
1258 }
1259
1260 inline Value *
1261 NVC0LoweringPass::loadResLength32(Value *ptr, uint32_t off)
1262 {
1263 uint8_t b = prog->driver->io.auxCBSlot;
1264 off += prog->driver->io.suInfoBase;
1265
1266 if (ptr)
1267 ptr = bld.mkOp2v(OP_SHL, TYPE_U32, bld.getScratch(), ptr, bld.mkImm(4));
1268
1269 return bld.
1270 mkLoadv(TYPE_U32, bld.mkSymbol(FILE_MEMORY_CONST, b, TYPE_U64, off + 8), ptr);
1271 }
1272
1273 inline Value *
1274 NVC0LoweringPass::loadMsInfo32(Value *ptr, uint32_t off)
1275 {
1276 uint8_t b = prog->driver->io.msInfoCBSlot;
1277 off += prog->driver->io.msInfoBase;
1278 return bld.
1279 mkLoadv(TYPE_U32, bld.mkSymbol(FILE_MEMORY_CONST, b, TYPE_U32, off), ptr);
1280 }
1281
1282 /* On nvc0, surface info is obtained via the surface binding points passed
1283 * to the SULD/SUST instructions.
1284 * On nve4, surface info is stored in c[] and is used by various special
1285 * instructions, e.g. for clamping coordiantes or generating an address.
1286 * They couldn't just have added an equivalent to TIC now, couldn't they ?
1287 */
1288 #define NVE4_SU_INFO_ADDR 0x00
1289 #define NVE4_SU_INFO_FMT 0x04
1290 #define NVE4_SU_INFO_DIM_X 0x08
1291 #define NVE4_SU_INFO_PITCH 0x0c
1292 #define NVE4_SU_INFO_DIM_Y 0x10
1293 #define NVE4_SU_INFO_ARRAY 0x14
1294 #define NVE4_SU_INFO_DIM_Z 0x18
1295 #define NVE4_SU_INFO_UNK1C 0x1c
1296 #define NVE4_SU_INFO_WIDTH 0x20
1297 #define NVE4_SU_INFO_HEIGHT 0x24
1298 #define NVE4_SU_INFO_DEPTH 0x28
1299 #define NVE4_SU_INFO_TARGET 0x2c
1300 #define NVE4_SU_INFO_CALL 0x30
1301 #define NVE4_SU_INFO_RAW_X 0x34
1302 #define NVE4_SU_INFO_MS_X 0x38
1303 #define NVE4_SU_INFO_MS_Y 0x3c
1304
1305 #define NVE4_SU_INFO__STRIDE 0x40
1306
1307 #define NVE4_SU_INFO_DIM(i) (0x08 + (i) * 8)
1308 #define NVE4_SU_INFO_SIZE(i) (0x20 + (i) * 4)
1309 #define NVE4_SU_INFO_MS(i) (0x38 + (i) * 4)
1310
1311 static inline uint16_t getSuClampSubOp(const TexInstruction *su, int c)
1312 {
1313 switch (su->tex.target.getEnum()) {
1314 case TEX_TARGET_BUFFER: return NV50_IR_SUBOP_SUCLAMP_PL(0, 1);
1315 case TEX_TARGET_RECT: return NV50_IR_SUBOP_SUCLAMP_SD(0, 2);
1316 case TEX_TARGET_1D: return NV50_IR_SUBOP_SUCLAMP_SD(0, 2);
1317 case TEX_TARGET_1D_ARRAY: return (c == 1) ?
1318 NV50_IR_SUBOP_SUCLAMP_PL(0, 2) :
1319 NV50_IR_SUBOP_SUCLAMP_SD(0, 2);
1320 case TEX_TARGET_2D: return NV50_IR_SUBOP_SUCLAMP_BL(0, 2);
1321 case TEX_TARGET_2D_MS: return NV50_IR_SUBOP_SUCLAMP_BL(0, 2);
1322 case TEX_TARGET_2D_ARRAY: return NV50_IR_SUBOP_SUCLAMP_SD(0, 2);
1323 case TEX_TARGET_2D_MS_ARRAY: return NV50_IR_SUBOP_SUCLAMP_SD(0, 2);
1324 case TEX_TARGET_3D: return NV50_IR_SUBOP_SUCLAMP_SD(0, 2);
1325 case TEX_TARGET_CUBE: return NV50_IR_SUBOP_SUCLAMP_SD(0, 2);
1326 case TEX_TARGET_CUBE_ARRAY: return NV50_IR_SUBOP_SUCLAMP_SD(0, 2);
1327 default:
1328 assert(0);
1329 return 0;
1330 }
1331 }
1332
1333 void
1334 NVC0LoweringPass::adjustCoordinatesMS(TexInstruction *tex)
1335 {
1336 const uint16_t base = tex->tex.r * NVE4_SU_INFO__STRIDE;
1337 const int arg = tex->tex.target.getArgCount();
1338
1339 if (tex->tex.target == TEX_TARGET_2D_MS)
1340 tex->tex.target = TEX_TARGET_2D;
1341 else
1342 if (tex->tex.target == TEX_TARGET_2D_MS_ARRAY)
1343 tex->tex.target = TEX_TARGET_2D_ARRAY;
1344 else
1345 return;
1346
1347 Value *x = tex->getSrc(0);
1348 Value *y = tex->getSrc(1);
1349 Value *s = tex->getSrc(arg - 1);
1350
1351 Value *tx = bld.getSSA(), *ty = bld.getSSA(), *ts = bld.getSSA();
1352
1353 Value *ms_x = loadResInfo32(NULL, base + NVE4_SU_INFO_MS(0));
1354 Value *ms_y = loadResInfo32(NULL, base + NVE4_SU_INFO_MS(1));
1355
1356 bld.mkOp2(OP_SHL, TYPE_U32, tx, x, ms_x);
1357 bld.mkOp2(OP_SHL, TYPE_U32, ty, y, ms_y);
1358
1359 s = bld.mkOp2v(OP_AND, TYPE_U32, ts, s, bld.loadImm(NULL, 0x7));
1360 s = bld.mkOp2v(OP_SHL, TYPE_U32, ts, ts, bld.mkImm(3));
1361
1362 Value *dx = loadMsInfo32(ts, 0x0);
1363 Value *dy = loadMsInfo32(ts, 0x4);
1364
1365 bld.mkOp2(OP_ADD, TYPE_U32, tx, tx, dx);
1366 bld.mkOp2(OP_ADD, TYPE_U32, ty, ty, dy);
1367
1368 tex->setSrc(0, tx);
1369 tex->setSrc(1, ty);
1370 tex->moveSources(arg, -1);
1371 }
1372
1373 // Sets 64-bit "generic address", predicate and format sources for SULD/SUST.
1374 // They're computed from the coordinates using the surface info in c[] space.
1375 void
1376 NVC0LoweringPass::processSurfaceCoordsNVE4(TexInstruction *su)
1377 {
1378 Instruction *insn;
1379 const bool atom = su->op == OP_SUREDB || su->op == OP_SUREDP;
1380 const bool raw =
1381 su->op == OP_SULDB || su->op == OP_SUSTB || su->op == OP_SUREDB;
1382 const int idx = su->tex.r;
1383 const int dim = su->tex.target.getDim();
1384 const int arg = dim + (su->tex.target.isArray() ? 1 : 0);
1385 const uint16_t base = idx * NVE4_SU_INFO__STRIDE;
1386 int c;
1387 Value *zero = bld.mkImm(0);
1388 Value *p1 = NULL;
1389 Value *v;
1390 Value *src[3];
1391 Value *bf, *eau, *off;
1392 Value *addr, *pred;
1393
1394 off = bld.getScratch(4);
1395 bf = bld.getScratch(4);
1396 addr = bld.getSSA(8);
1397 pred = bld.getScratch(1, FILE_PREDICATE);
1398
1399 bld.setPosition(su, false);
1400
1401 adjustCoordinatesMS(su);
1402
1403 // calculate clamped coordinates
1404 for (c = 0; c < arg; ++c) {
1405 src[c] = bld.getScratch();
1406 if (c == 0 && raw)
1407 v = loadResInfo32(NULL, base + NVE4_SU_INFO_RAW_X);
1408 else
1409 v = loadResInfo32(NULL, base + NVE4_SU_INFO_DIM(c));
1410 bld.mkOp3(OP_SUCLAMP, TYPE_S32, src[c], su->getSrc(c), v, zero)
1411 ->subOp = getSuClampSubOp(su, c);
1412 }
1413 for (; c < 3; ++c)
1414 src[c] = zero;
1415
1416 // set predicate output
1417 if (su->tex.target == TEX_TARGET_BUFFER) {
1418 src[0]->getInsn()->setFlagsDef(1, pred);
1419 } else
1420 if (su->tex.target.isArray()) {
1421 p1 = bld.getSSA(1, FILE_PREDICATE);
1422 src[dim]->getInsn()->setFlagsDef(1, p1);
1423 }
1424
1425 // calculate pixel offset
1426 if (dim == 1) {
1427 if (su->tex.target != TEX_TARGET_BUFFER)
1428 bld.mkOp2(OP_AND, TYPE_U32, off, src[0], bld.loadImm(NULL, 0xffff));
1429 } else
1430 if (dim == 3) {
1431 v = loadResInfo32(NULL, base + NVE4_SU_INFO_UNK1C);
1432 bld.mkOp3(OP_MADSP, TYPE_U32, off, src[2], v, src[1])
1433 ->subOp = NV50_IR_SUBOP_MADSP(4,2,8); // u16l u16l u16l
1434
1435 v = loadResInfo32(NULL, base + NVE4_SU_INFO_PITCH);
1436 bld.mkOp3(OP_MADSP, TYPE_U32, off, off, v, src[0])
1437 ->subOp = NV50_IR_SUBOP_MADSP(0,2,8); // u32 u16l u16l
1438 } else {
1439 assert(dim == 2);
1440 v = loadResInfo32(NULL, base + NVE4_SU_INFO_PITCH);
1441 bld.mkOp3(OP_MADSP, TYPE_U32, off, src[1], v, src[0])
1442 ->subOp = su->tex.target.isArray() ?
1443 NV50_IR_SUBOP_MADSP_SD : NV50_IR_SUBOP_MADSP(4,2,8); // u16l u16l u16l
1444 }
1445
1446 // calculate effective address part 1
1447 if (su->tex.target == TEX_TARGET_BUFFER) {
1448 if (raw) {
1449 bf = src[0];
1450 } else {
1451 v = loadResInfo32(NULL, base + NVE4_SU_INFO_FMT);
1452 bld.mkOp3(OP_VSHL, TYPE_U32, bf, src[0], v, zero)
1453 ->subOp = NV50_IR_SUBOP_V1(7,6,8|2);
1454 }
1455 } else {
1456 Value *y = src[1];
1457 Value *z = src[2];
1458 uint16_t subOp = 0;
1459
1460 switch (dim) {
1461 case 1:
1462 y = zero;
1463 z = zero;
1464 break;
1465 case 2:
1466 z = off;
1467 if (!su->tex.target.isArray()) {
1468 z = loadResInfo32(NULL, base + NVE4_SU_INFO_UNK1C);
1469 subOp = NV50_IR_SUBOP_SUBFM_3D;
1470 }
1471 break;
1472 default:
1473 subOp = NV50_IR_SUBOP_SUBFM_3D;
1474 assert(dim == 3);
1475 break;
1476 }
1477 insn = bld.mkOp3(OP_SUBFM, TYPE_U32, bf, src[0], y, z);
1478 insn->subOp = subOp;
1479 insn->setFlagsDef(1, pred);
1480 }
1481
1482 // part 2
1483 v = loadResInfo32(NULL, base + NVE4_SU_INFO_ADDR);
1484
1485 if (su->tex.target == TEX_TARGET_BUFFER) {
1486 eau = v;
1487 } else {
1488 eau = bld.mkOp3v(OP_SUEAU, TYPE_U32, bld.getScratch(4), off, bf, v);
1489 }
1490 // add array layer offset
1491 if (su->tex.target.isArray()) {
1492 v = loadResInfo32(NULL, base + NVE4_SU_INFO_ARRAY);
1493 if (dim == 1)
1494 bld.mkOp3(OP_MADSP, TYPE_U32, eau, src[1], v, eau)
1495 ->subOp = NV50_IR_SUBOP_MADSP(4,0,0); // u16 u24 u32
1496 else
1497 bld.mkOp3(OP_MADSP, TYPE_U32, eau, v, src[2], eau)
1498 ->subOp = NV50_IR_SUBOP_MADSP(0,0,0); // u32 u24 u32
1499 // combine predicates
1500 assert(p1);
1501 bld.mkOp2(OP_OR, TYPE_U8, pred, pred, p1);
1502 }
1503
1504 if (atom) {
1505 Value *lo = bf;
1506 if (su->tex.target == TEX_TARGET_BUFFER) {
1507 lo = zero;
1508 bld.mkMov(off, bf);
1509 }
1510 // bf == g[] address & 0xff
1511 // eau == g[] address >> 8
1512 bld.mkOp3(OP_PERMT, TYPE_U32, bf, lo, bld.loadImm(NULL, 0x6540), eau);
1513 bld.mkOp3(OP_PERMT, TYPE_U32, eau, zero, bld.loadImm(NULL, 0x0007), eau);
1514 } else
1515 if (su->op == OP_SULDP && su->tex.target == TEX_TARGET_BUFFER) {
1516 // Convert from u32 to u8 address format, which is what the library code
1517 // doing SULDP currently uses.
1518 // XXX: can SUEAU do this ?
1519 // XXX: does it matter that we don't mask high bytes in bf ?
1520 // Grrr.
1521 bld.mkOp2(OP_SHR, TYPE_U32, off, bf, bld.mkImm(8));
1522 bld.mkOp2(OP_ADD, TYPE_U32, eau, eau, off);
1523 }
1524
1525 bld.mkOp2(OP_MERGE, TYPE_U64, addr, bf, eau);
1526
1527 if (atom && su->tex.target == TEX_TARGET_BUFFER)
1528 bld.mkOp2(OP_ADD, TYPE_U64, addr, addr, off);
1529
1530 // let's just set it 0 for raw access and hope it works
1531 v = raw ?
1532 bld.mkImm(0) : loadResInfo32(NULL, base + NVE4_SU_INFO_FMT);
1533
1534 // get rid of old coordinate sources, make space for fmt info and predicate
1535 su->moveSources(arg, 3 - arg);
1536 // set 64 bit address and 32-bit format sources
1537 su->setSrc(0, addr);
1538 su->setSrc(1, v);
1539 su->setSrc(2, pred);
1540 }
1541
1542 void
1543 NVC0LoweringPass::handleSurfaceOpNVE4(TexInstruction *su)
1544 {
1545 processSurfaceCoordsNVE4(su);
1546
1547 // Who do we hate more ? The person who decided that nvc0's SULD doesn't
1548 // have to support conversion or the person who decided that, in OpenCL,
1549 // you don't have to specify the format here like you do in OpenGL ?
1550
1551 if (su->op == OP_SULDP) {
1552 // We don't patch shaders. Ever.
1553 // You get an indirect call to our library blob here.
1554 // But at least it's uniform.
1555 FlowInstruction *call;
1556 LValue *p[3];
1557 LValue *r[5];
1558 uint16_t base = su->tex.r * NVE4_SU_INFO__STRIDE + NVE4_SU_INFO_CALL;
1559
1560 for (int i = 0; i < 4; ++i)
1561 (r[i] = bld.getScratch(4, FILE_GPR))->reg.data.id = i;
1562 for (int i = 0; i < 3; ++i)
1563 (p[i] = bld.getScratch(1, FILE_PREDICATE))->reg.data.id = i;
1564 (r[4] = bld.getScratch(8, FILE_GPR))->reg.data.id = 4;
1565
1566 bld.mkMov(p[1], bld.mkImm((su->cache == CACHE_CA) ? 1 : 0), TYPE_U8);
1567 bld.mkMov(p[2], bld.mkImm((su->cache == CACHE_CG) ? 1 : 0), TYPE_U8);
1568 bld.mkMov(p[0], su->getSrc(2), TYPE_U8);
1569 bld.mkMov(r[4], su->getSrc(0), TYPE_U64);
1570 bld.mkMov(r[2], su->getSrc(1), TYPE_U32);
1571
1572 call = bld.mkFlow(OP_CALL, NULL, su->cc, su->getPredicate());
1573
1574 call->indirect = 1;
1575 call->absolute = 1;
1576 call->setSrc(0, bld.mkSymbol(FILE_MEMORY_CONST,
1577 prog->driver->io.auxCBSlot, TYPE_U32,
1578 prog->driver->io.suInfoBase + base));
1579 call->setSrc(1, r[2]);
1580 call->setSrc(2, r[4]);
1581 for (int i = 0; i < 3; ++i)
1582 call->setSrc(3 + i, p[i]);
1583 for (int i = 0; i < 4; ++i) {
1584 call->setDef(i, r[i]);
1585 bld.mkMov(su->getDef(i), r[i]);
1586 }
1587 call->setDef(4, p[1]);
1588 delete_Instruction(bld.getProgram(), su);
1589 }
1590
1591 if (su->op == OP_SUREDB || su->op == OP_SUREDP) {
1592 // FIXME: for out of bounds access, destination value will be undefined !
1593 Value *pred = su->getSrc(2);
1594 CondCode cc = CC_NOT_P;
1595 if (su->getPredicate()) {
1596 pred = bld.getScratch(1, FILE_PREDICATE);
1597 cc = su->cc;
1598 if (cc == CC_NOT_P) {
1599 bld.mkOp2(OP_OR, TYPE_U8, pred, su->getPredicate(), su->getSrc(2));
1600 } else {
1601 bld.mkOp2(OP_AND, TYPE_U8, pred, su->getPredicate(), su->getSrc(2));
1602 pred->getInsn()->src(1).mod = Modifier(NV50_IR_MOD_NOT);
1603 }
1604 }
1605 Instruction *red = bld.mkOp(OP_ATOM, su->dType, su->getDef(0));
1606 red->subOp = su->subOp;
1607 if (!gMemBase)
1608 gMemBase = bld.mkSymbol(FILE_MEMORY_GLOBAL, 0, TYPE_U32, 0);
1609 red->setSrc(0, gMemBase);
1610 red->setSrc(1, su->getSrc(3));
1611 if (su->subOp == NV50_IR_SUBOP_ATOM_CAS)
1612 red->setSrc(2, su->getSrc(4));
1613 red->setIndirect(0, 0, su->getSrc(0));
1614 red->setPredicate(cc, pred);
1615 delete_Instruction(bld.getProgram(), su);
1616 handleCasExch(red, true);
1617 } else {
1618 su->sType = (su->tex.target == TEX_TARGET_BUFFER) ? TYPE_U32 : TYPE_U8;
1619 }
1620 }
1621
1622 bool
1623 NVC0LoweringPass::handleWRSV(Instruction *i)
1624 {
1625 Instruction *st;
1626 Symbol *sym;
1627 uint32_t addr;
1628
1629 // must replace, $sreg are not writeable
1630 addr = targ->getSVAddress(FILE_SHADER_OUTPUT, i->getSrc(0)->asSym());
1631 if (addr >= 0x400)
1632 return false;
1633 sym = bld.mkSymbol(FILE_SHADER_OUTPUT, 0, i->sType, addr);
1634
1635 st = bld.mkStore(OP_EXPORT, i->dType, sym, i->getIndirect(0, 0),
1636 i->getSrc(1));
1637 st->perPatch = i->perPatch;
1638
1639 bld.getBB()->remove(i);
1640 return true;
1641 }
1642
1643 void
1644 NVC0LoweringPass::readTessCoord(LValue *dst, int c)
1645 {
1646 Value *laneid = bld.getSSA();
1647 Value *x, *y;
1648
1649 bld.mkOp1(OP_RDSV, TYPE_U32, laneid, bld.mkSysVal(SV_LANEID, 0));
1650
1651 if (c == 0) {
1652 x = dst;
1653 y = NULL;
1654 } else
1655 if (c == 1) {
1656 x = NULL;
1657 y = dst;
1658 } else {
1659 assert(c == 2);
1660 x = bld.getSSA();
1661 y = bld.getSSA();
1662 }
1663 if (x)
1664 bld.mkFetch(x, TYPE_F32, FILE_SHADER_OUTPUT, 0x2f0, NULL, laneid);
1665 if (y)
1666 bld.mkFetch(y, TYPE_F32, FILE_SHADER_OUTPUT, 0x2f4, NULL, laneid);
1667
1668 if (c == 2) {
1669 bld.mkOp2(OP_ADD, TYPE_F32, dst, x, y);
1670 bld.mkOp2(OP_SUB, TYPE_F32, dst, bld.loadImm(NULL, 1.0f), dst);
1671 }
1672 }
1673
1674 bool
1675 NVC0LoweringPass::handleRDSV(Instruction *i)
1676 {
1677 Symbol *sym = i->getSrc(0)->asSym();
1678 const SVSemantic sv = sym->reg.data.sv.sv;
1679 Value *vtx = NULL;
1680 Instruction *ld;
1681 uint32_t addr = targ->getSVAddress(FILE_SHADER_INPUT, sym);
1682
1683 if (addr >= 0x400) {
1684 // mov $sreg
1685 if (sym->reg.data.sv.index == 3) {
1686 // TGSI backend may use 4th component of TID,NTID,CTAID,NCTAID
1687 i->op = OP_MOV;
1688 i->setSrc(0, bld.mkImm((sv == SV_NTID || sv == SV_NCTAID) ? 1 : 0));
1689 }
1690 if (sv == SV_VERTEX_COUNT) {
1691 bld.setPosition(i, true);
1692 bld.mkOp2(OP_EXTBF, TYPE_U32, i->getDef(0), i->getDef(0), bld.mkImm(0x808));
1693 }
1694 return true;
1695 }
1696
1697 switch (sv) {
1698 case SV_POSITION:
1699 assert(prog->getType() == Program::TYPE_FRAGMENT);
1700 if (i->srcExists(1)) {
1701 // Pass offset through to the interpolation logic
1702 ld = bld.mkInterp(NV50_IR_INTERP_LINEAR | NV50_IR_INTERP_OFFSET,
1703 i->getDef(0), addr, NULL);
1704 ld->setSrc(1, i->getSrc(1));
1705 } else {
1706 bld.mkInterp(NV50_IR_INTERP_LINEAR, i->getDef(0), addr, NULL);
1707 }
1708 break;
1709 case SV_FACE:
1710 {
1711 Value *face = i->getDef(0);
1712 bld.mkInterp(NV50_IR_INTERP_FLAT, face, addr, NULL);
1713 if (i->dType == TYPE_F32) {
1714 bld.mkOp2(OP_OR, TYPE_U32, face, face, bld.mkImm(0x00000001));
1715 bld.mkOp1(OP_NEG, TYPE_S32, face, face);
1716 bld.mkCvt(OP_CVT, TYPE_F32, face, TYPE_S32, face);
1717 }
1718 }
1719 break;
1720 case SV_TESS_COORD:
1721 assert(prog->getType() == Program::TYPE_TESSELLATION_EVAL);
1722 readTessCoord(i->getDef(0)->asLValue(), i->getSrc(0)->reg.data.sv.index);
1723 break;
1724 case SV_NTID:
1725 case SV_NCTAID:
1726 case SV_GRIDID:
1727 assert(targ->getChipset() >= NVISA_GK104_CHIPSET); // mov $sreg otherwise
1728 if (sym->reg.data.sv.index == 3) {
1729 i->op = OP_MOV;
1730 i->setSrc(0, bld.mkImm(sv == SV_GRIDID ? 0 : 1));
1731 return true;
1732 }
1733 addr += prog->driver->prop.cp.gridInfoBase;
1734 bld.mkLoad(TYPE_U32, i->getDef(0),
1735 bld.mkSymbol(FILE_MEMORY_CONST, prog->driver->io.auxCBSlot,
1736 TYPE_U32, addr), NULL);
1737 break;
1738 case SV_SAMPLE_INDEX:
1739 // TODO: Properly pass source as an address in the PIX address space
1740 // (which can be of the form [r0+offset]). But this is currently
1741 // unnecessary.
1742 ld = bld.mkOp1(OP_PIXLD, TYPE_U32, i->getDef(0), bld.mkImm(0));
1743 ld->subOp = NV50_IR_SUBOP_PIXLD_SAMPLEID;
1744 break;
1745 case SV_SAMPLE_POS: {
1746 Value *off = new_LValue(func, FILE_GPR);
1747 ld = bld.mkOp1(OP_PIXLD, TYPE_U32, i->getDef(0), bld.mkImm(0));
1748 ld->subOp = NV50_IR_SUBOP_PIXLD_SAMPLEID;
1749 bld.mkOp2(OP_SHL, TYPE_U32, off, i->getDef(0), bld.mkImm(3));
1750 bld.mkLoad(TYPE_F32,
1751 i->getDef(0),
1752 bld.mkSymbol(
1753 FILE_MEMORY_CONST, prog->driver->io.auxCBSlot,
1754 TYPE_U32, prog->driver->io.sampleInfoBase +
1755 4 * sym->reg.data.sv.index),
1756 off);
1757 break;
1758 }
1759 case SV_SAMPLE_MASK:
1760 ld = bld.mkOp1(OP_PIXLD, TYPE_U32, i->getDef(0), bld.mkImm(0));
1761 ld->subOp = NV50_IR_SUBOP_PIXLD_COVMASK;
1762 break;
1763 case SV_BASEVERTEX:
1764 case SV_BASEINSTANCE:
1765 case SV_DRAWID:
1766 ld = bld.mkLoad(TYPE_U32, i->getDef(0),
1767 bld.mkSymbol(FILE_MEMORY_CONST,
1768 prog->driver->io.auxCBSlot,
1769 TYPE_U32,
1770 prog->driver->io.drawInfoBase +
1771 4 * (sv - SV_BASEVERTEX)),
1772 NULL);
1773 break;
1774 default:
1775 if (prog->getType() == Program::TYPE_TESSELLATION_EVAL && !i->perPatch)
1776 vtx = bld.mkOp1v(OP_PFETCH, TYPE_U32, bld.getSSA(), bld.mkImm(0));
1777 ld = bld.mkFetch(i->getDef(0), i->dType,
1778 FILE_SHADER_INPUT, addr, i->getIndirect(0, 0), vtx);
1779 ld->perPatch = i->perPatch;
1780 break;
1781 }
1782 bld.getBB()->remove(i);
1783 return true;
1784 }
1785
1786 bool
1787 NVC0LoweringPass::handleDIV(Instruction *i)
1788 {
1789 if (!isFloatType(i->dType))
1790 return true;
1791 bld.setPosition(i, false);
1792 Instruction *rcp = bld.mkOp1(OP_RCP, i->dType, bld.getSSA(typeSizeof(i->dType)), i->getSrc(1));
1793 i->op = OP_MUL;
1794 i->setSrc(1, rcp->getDef(0));
1795 return true;
1796 }
1797
1798 bool
1799 NVC0LoweringPass::handleMOD(Instruction *i)
1800 {
1801 if (!isFloatType(i->dType))
1802 return true;
1803 LValue *value = bld.getScratch(typeSizeof(i->dType));
1804 bld.mkOp1(OP_RCP, i->dType, value, i->getSrc(1));
1805 bld.mkOp2(OP_MUL, i->dType, value, i->getSrc(0), value);
1806 bld.mkOp1(OP_TRUNC, i->dType, value, value);
1807 bld.mkOp2(OP_MUL, i->dType, value, i->getSrc(1), value);
1808 i->op = OP_SUB;
1809 i->setSrc(1, value);
1810 return true;
1811 }
1812
1813 bool
1814 NVC0LoweringPass::handleSQRT(Instruction *i)
1815 {
1816 if (i->dType == TYPE_F64) {
1817 Value *pred = bld.getSSA(1, FILE_PREDICATE);
1818 Value *zero = bld.loadImm(NULL, 0.0);
1819 Value *dst = bld.getSSA(8);
1820 bld.mkOp1(OP_RSQ, i->dType, dst, i->getSrc(0));
1821 bld.mkCmp(OP_SET, CC_LE, i->dType, pred, i->dType, i->getSrc(0), zero);
1822 bld.mkOp3(OP_SELP, TYPE_U64, dst, zero, dst, pred);
1823 i->op = OP_MUL;
1824 i->setSrc(1, dst);
1825 // TODO: Handle this properly with a library function
1826 } else {
1827 bld.setPosition(i, true);
1828 i->op = OP_RSQ;
1829 bld.mkOp1(OP_RCP, i->dType, i->getDef(0), i->getDef(0));
1830 }
1831
1832 return true;
1833 }
1834
1835 bool
1836 NVC0LoweringPass::handlePOW(Instruction *i)
1837 {
1838 LValue *val = bld.getScratch();
1839
1840 bld.mkOp1(OP_LG2, TYPE_F32, val, i->getSrc(0));
1841 bld.mkOp2(OP_MUL, TYPE_F32, val, i->getSrc(1), val)->dnz = 1;
1842 bld.mkOp1(OP_PREEX2, TYPE_F32, val, val);
1843
1844 i->op = OP_EX2;
1845 i->setSrc(0, val);
1846 i->setSrc(1, NULL);
1847
1848 return true;
1849 }
1850
1851 bool
1852 NVC0LoweringPass::handleEXPORT(Instruction *i)
1853 {
1854 if (prog->getType() == Program::TYPE_FRAGMENT) {
1855 int id = i->getSrc(0)->reg.data.offset / 4;
1856
1857 if (i->src(0).isIndirect(0)) // TODO, ugly
1858 return false;
1859 i->op = OP_MOV;
1860 i->subOp = NV50_IR_SUBOP_MOV_FINAL;
1861 i->src(0).set(i->src(1));
1862 i->setSrc(1, NULL);
1863 i->setDef(0, new_LValue(func, FILE_GPR));
1864 i->getDef(0)->reg.data.id = id;
1865
1866 prog->maxGPR = MAX2(prog->maxGPR, id);
1867 } else
1868 if (prog->getType() == Program::TYPE_GEOMETRY) {
1869 i->setIndirect(0, 1, gpEmitAddress);
1870 }
1871 return true;
1872 }
1873
1874 bool
1875 NVC0LoweringPass::handleOUT(Instruction *i)
1876 {
1877 Instruction *prev = i->prev;
1878 ImmediateValue stream, prevStream;
1879
1880 // Only merge if the stream ids match. Also, note that the previous
1881 // instruction would have already been lowered, so we take arg1 from it.
1882 if (i->op == OP_RESTART && prev && prev->op == OP_EMIT &&
1883 i->src(0).getImmediate(stream) &&
1884 prev->src(1).getImmediate(prevStream) &&
1885 stream.reg.data.u32 == prevStream.reg.data.u32) {
1886 i->prev->subOp = NV50_IR_SUBOP_EMIT_RESTART;
1887 delete_Instruction(prog, i);
1888 } else {
1889 assert(gpEmitAddress);
1890 i->setDef(0, gpEmitAddress);
1891 i->setSrc(1, i->getSrc(0));
1892 i->setSrc(0, gpEmitAddress);
1893 }
1894 return true;
1895 }
1896
1897 // Generate a binary predicate if an instruction is predicated by
1898 // e.g. an f32 value.
1899 void
1900 NVC0LoweringPass::checkPredicate(Instruction *insn)
1901 {
1902 Value *pred = insn->getPredicate();
1903 Value *pdst;
1904
1905 if (!pred || pred->reg.file == FILE_PREDICATE)
1906 return;
1907 pdst = new_LValue(func, FILE_PREDICATE);
1908
1909 // CAUTION: don't use pdst->getInsn, the definition might not be unique,
1910 // delay turning PSET(FSET(x,y),0) into PSET(x,y) to a later pass
1911
1912 bld.mkCmp(OP_SET, CC_NEU, insn->dType, pdst, insn->dType, bld.mkImm(0), pred);
1913
1914 insn->setPredicate(insn->cc, pdst);
1915 }
1916
1917 //
1918 // - add quadop dance for texturing
1919 // - put FP outputs in GPRs
1920 // - convert instruction sequences
1921 //
1922 bool
1923 NVC0LoweringPass::visit(Instruction *i)
1924 {
1925 bool ret = true;
1926 bld.setPosition(i, false);
1927
1928 if (i->cc != CC_ALWAYS)
1929 checkPredicate(i);
1930
1931 switch (i->op) {
1932 case OP_TEX:
1933 case OP_TXB:
1934 case OP_TXL:
1935 case OP_TXF:
1936 case OP_TXG:
1937 return handleTEX(i->asTex());
1938 case OP_TXD:
1939 return handleTXD(i->asTex());
1940 case OP_TXLQ:
1941 return handleTXLQ(i->asTex());
1942 case OP_TXQ:
1943 return handleTXQ(i->asTex());
1944 case OP_EX2:
1945 bld.mkOp1(OP_PREEX2, TYPE_F32, i->getDef(0), i->getSrc(0));
1946 i->setSrc(0, i->getDef(0));
1947 break;
1948 case OP_POW:
1949 return handlePOW(i);
1950 case OP_DIV:
1951 return handleDIV(i);
1952 case OP_MOD:
1953 return handleMOD(i);
1954 case OP_SQRT:
1955 return handleSQRT(i);
1956 case OP_EXPORT:
1957 ret = handleEXPORT(i);
1958 break;
1959 case OP_EMIT:
1960 case OP_RESTART:
1961 return handleOUT(i);
1962 case OP_RDSV:
1963 return handleRDSV(i);
1964 case OP_WRSV:
1965 return handleWRSV(i);
1966 case OP_STORE:
1967 case OP_LOAD:
1968 if (i->src(0).getFile() == FILE_SHADER_INPUT) {
1969 if (prog->getType() == Program::TYPE_COMPUTE) {
1970 i->getSrc(0)->reg.file = FILE_MEMORY_CONST;
1971 i->getSrc(0)->reg.fileIndex = 0;
1972 } else
1973 if (prog->getType() == Program::TYPE_GEOMETRY &&
1974 i->src(0).isIndirect(0)) {
1975 // XXX: this assumes vec4 units
1976 Value *ptr = bld.mkOp2v(OP_SHL, TYPE_U32, bld.getSSA(),
1977 i->getIndirect(0, 0), bld.mkImm(4));
1978 i->setIndirect(0, 0, ptr);
1979 i->op = OP_VFETCH;
1980 } else {
1981 i->op = OP_VFETCH;
1982 assert(prog->getType() != Program::TYPE_FRAGMENT); // INTERP
1983 }
1984 } else if (i->src(0).getFile() == FILE_MEMORY_CONST) {
1985 if (i->src(0).isIndirect(1)) {
1986 Value *ptr;
1987 if (i->src(0).isIndirect(0))
1988 ptr = bld.mkOp3v(OP_INSBF, TYPE_U32, bld.getSSA(),
1989 i->getIndirect(0, 1), bld.mkImm(0x1010),
1990 i->getIndirect(0, 0));
1991 else
1992 ptr = bld.mkOp2v(OP_SHL, TYPE_U32, bld.getSSA(),
1993 i->getIndirect(0, 1), bld.mkImm(16));
1994 i->setIndirect(0, 1, NULL);
1995 i->setIndirect(0, 0, ptr);
1996 i->subOp = NV50_IR_SUBOP_LDC_IS;
1997 }
1998 } else if (i->src(0).getFile() == FILE_SHADER_OUTPUT) {
1999 assert(prog->getType() == Program::TYPE_TESSELLATION_CONTROL);
2000 i->op = OP_VFETCH;
2001 } else if (i->src(0).getFile() == FILE_MEMORY_GLOBAL) {
2002 Value *ind = i->getIndirect(0, 1);
2003 Value *ptr = loadResInfo64(ind, i->getSrc(0)->reg.fileIndex * 16);
2004 // XXX come up with a way not to do this for EVERY little access but
2005 // rather to batch these up somehow. Unfortunately we've lost the
2006 // information about the field width by the time we get here.
2007 Value *offset = bld.loadImm(NULL, i->getSrc(0)->reg.data.offset + typeSizeof(i->sType));
2008 Value *length = loadResLength32(ind, i->getSrc(0)->reg.fileIndex * 16);
2009 Value *pred = new_LValue(func, FILE_PREDICATE);
2010 if (i->src(0).isIndirect(0)) {
2011 bld.mkOp2(OP_ADD, TYPE_U64, ptr, ptr, i->getIndirect(0, 0));
2012 bld.mkOp2(OP_ADD, TYPE_U32, offset, offset, i->getIndirect(0, 0));
2013 }
2014 i->setIndirect(0, 1, NULL);
2015 i->setIndirect(0, 0, ptr);
2016 bld.mkCmp(OP_SET, CC_GT, TYPE_U32, pred, TYPE_U32, offset, length);
2017 i->setPredicate(CC_NOT_P, pred);
2018 if (i->defExists(0)) {
2019 bld.mkMov(i->getDef(0), bld.mkImm(0));
2020 }
2021 }
2022 break;
2023 case OP_ATOM:
2024 {
2025 const bool cctl = i->src(0).getFile() == FILE_MEMORY_GLOBAL;
2026 handleATOM(i);
2027 handleCasExch(i, cctl);
2028 }
2029 break;
2030 case OP_SULDB:
2031 case OP_SULDP:
2032 case OP_SUSTB:
2033 case OP_SUSTP:
2034 case OP_SUREDB:
2035 case OP_SUREDP:
2036 if (targ->getChipset() >= NVISA_GK104_CHIPSET)
2037 handleSurfaceOpNVE4(i->asTex());
2038 break;
2039 case OP_SUQ:
2040 handleSUQ(i);
2041 break;
2042 default:
2043 break;
2044 }
2045
2046 /* Kepler+ has a special opcode to compute a new base address to be used
2047 * for indirect loads.
2048 */
2049 if (targ->getChipset() >= NVISA_GK104_CHIPSET && !i->perPatch &&
2050 (i->op == OP_VFETCH || i->op == OP_EXPORT) && i->src(0).isIndirect(0)) {
2051 Instruction *afetch = bld.mkOp1(OP_AFETCH, TYPE_U32, bld.getSSA(),
2052 cloneShallow(func, i->getSrc(0)));
2053 afetch->setIndirect(0, 0, i->getIndirect(0, 0));
2054 i->src(0).get()->reg.data.offset = 0;
2055 i->setIndirect(0, 0, afetch->getDef(0));
2056 }
2057
2058 return ret;
2059 }
2060
2061 bool
2062 TargetNVC0::runLegalizePass(Program *prog, CGStage stage) const
2063 {
2064 if (stage == CG_STAGE_PRE_SSA) {
2065 NVC0LoweringPass pass(prog);
2066 return pass.run(prog, false, true);
2067 } else
2068 if (stage == CG_STAGE_POST_RA) {
2069 NVC0LegalizePostRA pass(prog);
2070 return pass.run(prog, false, true);
2071 } else
2072 if (stage == CG_STAGE_SSA) {
2073 NVC0LegalizeSSA pass;
2074 return pass.run(prog, false, true);
2075 }
2076 return false;
2077 }
2078
2079 } // namespace nv50_ir