nvc0/ir: replace cvt instructions with add to improve shader performance
[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
49 bld.setPosition(i, false);
50
51 // Generate movs to the input regs for the call we want to generate
52 for (int s = 0; i->srcExists(s); ++s) {
53 Instruction *ld = i->getSrc(s)->getInsn();
54 assert(ld->getSrc(0) != NULL);
55 // check if we are moving an immediate, propagate it in that case
56 if (!ld || ld->fixed || (ld->op != OP_LOAD && ld->op != OP_MOV) ||
57 !(ld->src(0).getFile() == FILE_IMMEDIATE))
58 bld.mkMovToReg(s, i->getSrc(s));
59 else {
60 bld.mkMovToReg(s, ld->getSrc(0));
61 // Clear the src, to make code elimination possible here before we
62 // delete the instruction i later
63 i->setSrc(s, NULL);
64 if (ld->isDead())
65 delete_Instruction(prog, ld);
66 }
67 }
68
69 switch (i->dType) {
70 case TYPE_U32: builtin = NVC0_BUILTIN_DIV_U32; break;
71 case TYPE_S32: builtin = NVC0_BUILTIN_DIV_S32; break;
72 default:
73 return;
74 }
75 call = bld.mkFlow(OP_CALL, NULL, CC_ALWAYS, NULL);
76 bld.mkMovFromReg(i->getDef(0), i->op == OP_DIV ? 0 : 1);
77 bld.mkClobber(FILE_GPR, (i->op == OP_DIV) ? 0xe : 0xd, 2);
78 bld.mkClobber(FILE_PREDICATE, (i->dType == TYPE_S32) ? 0xf : 0x3, 0);
79
80 call->fixed = 1;
81 call->absolute = call->builtin = 1;
82 call->target.builtin = builtin;
83 delete_Instruction(prog, i);
84 }
85
86 void
87 NVC0LegalizeSSA::handleRCPRSQ(Instruction *i)
88 {
89 assert(i->dType == TYPE_F64);
90 // There are instructions that will compute the high 32 bits of the 64-bit
91 // float. We will just stick 0 in the bottom 32 bits.
92
93 bld.setPosition(i, false);
94
95 // 1. Take the source and it up.
96 Value *src[2], *dst[2], *def = i->getDef(0);
97 bld.mkSplit(src, 4, i->getSrc(0));
98
99 // 2. We don't care about the low 32 bits of the destination. Stick a 0 in.
100 dst[0] = bld.loadImm(NULL, 0);
101 dst[1] = bld.getSSA();
102
103 // 3. The new version of the instruction takes the high 32 bits of the
104 // source and outputs the high 32 bits of the destination.
105 i->setSrc(0, src[1]);
106 i->setDef(0, dst[1]);
107 i->setType(TYPE_F32);
108 i->subOp = NV50_IR_SUBOP_RCPRSQ_64H;
109
110 // 4. Recombine the two dst pieces back into the original destination.
111 bld.setPosition(i, true);
112 bld.mkOp2(OP_MERGE, TYPE_U64, def, dst[0], dst[1]);
113 }
114
115 void
116 NVC0LegalizeSSA::handleFTZ(Instruction *i)
117 {
118 // Only want to flush float inputs
119 assert(i->sType == TYPE_F32);
120
121 // If we're already flushing denorms (and NaN's) to zero, no need for this.
122 if (i->dnz)
123 return;
124
125 // Only certain classes of operations can flush
126 OpClass cls = prog->getTarget()->getOpClass(i->op);
127 if (cls != OPCLASS_ARITH && cls != OPCLASS_COMPARE &&
128 cls != OPCLASS_CONVERT)
129 return;
130
131 i->ftz = true;
132 }
133
134 void
135 NVC0LegalizeSSA::handleTEXLOD(TexInstruction *i)
136 {
137 if (i->tex.levelZero)
138 return;
139
140 ImmediateValue lod;
141
142 // The LOD argument comes right after the coordinates (before depth bias,
143 // offsets, etc).
144 int arg = i->tex.target.getArgCount();
145
146 // SM30+ stores the indirect handle as a separate arg, which comes before
147 // the LOD.
148 if (prog->getTarget()->getChipset() >= NVISA_GK104_CHIPSET &&
149 i->tex.rIndirectSrc >= 0)
150 arg++;
151 // SM20 stores indirect handle combined with array coordinate
152 if (prog->getTarget()->getChipset() < NVISA_GK104_CHIPSET &&
153 !i->tex.target.isArray() &&
154 i->tex.rIndirectSrc >= 0)
155 arg++;
156
157 if (!i->src(arg).getImmediate(lod) || !lod.isInteger(0))
158 return;
159
160 if (i->op == OP_TXL)
161 i->op = OP_TEX;
162 i->tex.levelZero = true;
163 i->moveSources(arg + 1, -1);
164 }
165
166 void
167 NVC0LegalizeSSA::handleShift(Instruction *lo)
168 {
169 Value *shift = lo->getSrc(1);
170 Value *dst64 = lo->getDef(0);
171 Value *src[2], *dst[2];
172 operation op = lo->op;
173
174 bld.setPosition(lo, false);
175
176 bld.mkSplit(src, 4, lo->getSrc(0));
177
178 // SM30 and prior don't have the fancy new SHF.L/R ops. So the logic has to
179 // be completely emulated. For SM35+, we can use the more directed SHF
180 // operations.
181 if (prog->getTarget()->getChipset() < NVISA_GK20A_CHIPSET) {
182 // The strategy here is to handle shifts >= 32 and less than 32 as
183 // separate parts.
184 //
185 // For SHL:
186 // If the shift is <= 32, then
187 // (HI,LO) << x = (HI << x | (LO >> (32 - x)), LO << x)
188 // If the shift is > 32, then
189 // (HI,LO) << x = (LO << (x - 32), 0)
190 //
191 // For SHR:
192 // If the shift is <= 32, then
193 // (HI,LO) >> x = (HI >> x, (HI << (32 - x)) | LO >> x)
194 // If the shift is > 32, then
195 // (HI,LO) >> x = (0, HI >> (x - 32))
196 //
197 // Note that on NVIDIA hardware, a shift > 32 yields a 0 value, which we
198 // can use to our advantage. Also note the structural similarities
199 // between the right/left cases. The main difference is swapping hi/lo
200 // on input and output.
201
202 Value *x32_minus_shift, *pred, *hi1, *hi2;
203 DataType type = isSignedIntType(lo->dType) ? TYPE_S32 : TYPE_U32;
204 operation antiop = op == OP_SHR ? OP_SHL : OP_SHR;
205 if (op == OP_SHR)
206 std::swap(src[0], src[1]);
207 bld.mkOp2(OP_ADD, TYPE_U32, (x32_minus_shift = bld.getSSA()), shift, bld.mkImm(0x20))
208 ->src(0).mod = Modifier(NV50_IR_MOD_NEG);
209 bld.mkCmp(OP_SET, CC_LE, TYPE_U8, (pred = bld.getSSA(1, FILE_PREDICATE)),
210 TYPE_U32, shift, bld.mkImm(32));
211 // Compute HI (shift <= 32)
212 bld.mkOp2(OP_OR, TYPE_U32, (hi1 = bld.getSSA()),
213 bld.mkOp2v(op, TYPE_U32, bld.getSSA(), src[1], shift),
214 bld.mkOp2v(antiop, TYPE_U32, bld.getSSA(), src[0], x32_minus_shift))
215 ->setPredicate(CC_P, pred);
216 // Compute LO (all shift values)
217 bld.mkOp2(op, type, (dst[0] = bld.getSSA()), src[0], shift);
218 // Compute HI (shift > 32)
219 bld.mkOp2(op, type, (hi2 = bld.getSSA()), src[0],
220 bld.mkOp1v(OP_NEG, TYPE_S32, bld.getSSA(), x32_minus_shift))
221 ->setPredicate(CC_NOT_P, pred);
222 bld.mkOp2(OP_UNION, TYPE_U32, (dst[1] = bld.getSSA()), hi1, hi2);
223 if (op == OP_SHR)
224 std::swap(dst[0], dst[1]);
225 bld.mkOp2(OP_MERGE, TYPE_U64, dst64, dst[0], dst[1]);
226 delete_Instruction(prog, lo);
227 return;
228 }
229
230 Instruction *hi = new_Instruction(func, op, TYPE_U32);
231 lo->bb->insertAfter(lo, hi);
232
233 hi->sType = lo->sType;
234 lo->dType = TYPE_U32;
235
236 hi->setDef(0, (dst[1] = bld.getSSA()));
237 if (lo->op == OP_SHR)
238 hi->subOp |= NV50_IR_SUBOP_SHIFT_HIGH;
239 lo->setDef(0, (dst[0] = bld.getSSA()));
240
241 bld.setPosition(hi, true);
242
243 if (lo->op == OP_SHL)
244 std::swap(hi, lo);
245
246 hi->setSrc(0, new_ImmediateValue(prog, 0u));
247 hi->setSrc(1, shift);
248 hi->setSrc(2, lo->op == OP_SHL ? src[0] : src[1]);
249
250 lo->setSrc(0, src[0]);
251 lo->setSrc(1, shift);
252 lo->setSrc(2, src[1]);
253
254 bld.mkOp2(OP_MERGE, TYPE_U64, dst64, dst[0], dst[1]);
255 }
256
257 void
258 NVC0LegalizeSSA::handleSET(CmpInstruction *cmp)
259 {
260 DataType hTy = cmp->sType == TYPE_S64 ? TYPE_S32 : TYPE_U32;
261 Value *carry;
262 Value *src0[2], *src1[2];
263 bld.setPosition(cmp, false);
264
265 bld.mkSplit(src0, 4, cmp->getSrc(0));
266 bld.mkSplit(src1, 4, cmp->getSrc(1));
267 bld.mkOp2(OP_SUB, hTy, NULL, src0[0], src1[0])
268 ->setFlagsDef(0, (carry = bld.getSSA(1, FILE_FLAGS)));
269 cmp->setFlagsSrc(cmp->srcCount(), carry);
270 cmp->setSrc(0, src0[1]);
271 cmp->setSrc(1, src1[1]);
272 cmp->sType = hTy;
273 }
274
275 bool
276 NVC0LegalizeSSA::visit(Function *fn)
277 {
278 bld.setProgram(fn->getProgram());
279 return true;
280 }
281
282 bool
283 NVC0LegalizeSSA::visit(BasicBlock *bb)
284 {
285 Instruction *next;
286 for (Instruction *i = bb->getEntry(); i; i = next) {
287 next = i->next;
288
289 if (i->sType == TYPE_F32 && prog->getType() != Program::TYPE_COMPUTE)
290 handleFTZ(i);
291
292 switch (i->op) {
293 case OP_DIV:
294 case OP_MOD:
295 if (i->sType != TYPE_F32)
296 handleDIV(i);
297 break;
298 case OP_RCP:
299 case OP_RSQ:
300 if (i->dType == TYPE_F64)
301 handleRCPRSQ(i);
302 break;
303 case OP_TXL:
304 case OP_TXF:
305 handleTEXLOD(i->asTex());
306 break;
307 case OP_SHR:
308 case OP_SHL:
309 if (typeSizeof(i->sType) == 8)
310 handleShift(i);
311 break;
312 case OP_SET:
313 case OP_SET_AND:
314 case OP_SET_OR:
315 case OP_SET_XOR:
316 if (typeSizeof(i->sType) == 8 && i->sType != TYPE_F64)
317 handleSET(i->asCmp());
318 break;
319 default:
320 break;
321 }
322 }
323 return true;
324 }
325
326 NVC0LegalizePostRA::NVC0LegalizePostRA(const Program *prog)
327 : rZero(NULL),
328 carry(NULL),
329 pOne(NULL),
330 needTexBar(prog->getTarget()->getChipset() >= 0xe0 &&
331 prog->getTarget()->getChipset() < 0x110)
332 {
333 }
334
335 bool
336 NVC0LegalizePostRA::insnDominatedBy(const Instruction *later,
337 const Instruction *early) const
338 {
339 if (early->bb == later->bb)
340 return early->serial < later->serial;
341 return later->bb->dominatedBy(early->bb);
342 }
343
344 void
345 NVC0LegalizePostRA::addTexUse(std::list<TexUse> &uses,
346 Instruction *usei, const Instruction *texi)
347 {
348 bool add = true;
349 bool dominated = insnDominatedBy(usei, texi);
350 // Uses before the tex have to all be included. Just because an earlier
351 // instruction dominates another instruction doesn't mean that there's no
352 // way to get from the tex to the later instruction. For example you could
353 // have nested loops, with the tex in the inner loop, and uses before it in
354 // both loops - even though the outer loop's instruction would dominate the
355 // inner's, we still want a texbar before the inner loop's instruction.
356 //
357 // However we can still use the eliding logic between uses dominated by the
358 // tex instruction, as that is unambiguously correct.
359 if (dominated) {
360 for (std::list<TexUse>::iterator it = uses.begin(); it != uses.end();) {
361 if (it->after) {
362 if (insnDominatedBy(usei, it->insn)) {
363 add = false;
364 break;
365 }
366 if (insnDominatedBy(it->insn, usei)) {
367 it = uses.erase(it);
368 continue;
369 }
370 }
371 ++it;
372 }
373 }
374 if (add)
375 uses.push_back(TexUse(usei, texi, dominated));
376 }
377
378 // While it might be tempting to use the an algorithm that just looks at tex
379 // uses, not all texture results are guaranteed to be used on all paths. In
380 // the case where along some control flow path a texture result is never used,
381 // we might reuse that register for something else, creating a
382 // write-after-write hazard. So we have to manually look through all
383 // instructions looking for ones that reference the registers in question.
384 void
385 NVC0LegalizePostRA::findFirstUses(
386 Instruction *texi, std::list<TexUse> &uses)
387 {
388 int minGPR = texi->def(0).rep()->reg.data.id;
389 int maxGPR = minGPR + texi->def(0).rep()->reg.size / 4 - 1;
390
391 unordered_set<const BasicBlock *> visited;
392 findFirstUsesBB(minGPR, maxGPR, texi->next, texi, uses, visited);
393 }
394
395 void
396 NVC0LegalizePostRA::findFirstUsesBB(
397 int minGPR, int maxGPR, Instruction *start,
398 const Instruction *texi, std::list<TexUse> &uses,
399 unordered_set<const BasicBlock *> &visited)
400 {
401 const BasicBlock *bb = start->bb;
402
403 // We don't process the whole bb the first time around. This is correct,
404 // however we might be in a loop and hit this BB again, and need to process
405 // the full thing. So only mark a bb as visited if we processed it from the
406 // beginning.
407 if (start == bb->getEntry()) {
408 if (visited.find(bb) != visited.end())
409 return;
410 visited.insert(bb);
411 }
412
413 for (Instruction *insn = start; insn != bb->getExit(); insn = insn->next) {
414 if (insn->isNop())
415 continue;
416
417 for (int d = 0; insn->defExists(d); ++d) {
418 const Value *def = insn->def(d).rep();
419 if (insn->def(d).getFile() != FILE_GPR ||
420 def->reg.data.id + def->reg.size / 4 - 1 < minGPR ||
421 def->reg.data.id > maxGPR)
422 continue;
423 addTexUse(uses, insn, texi);
424 return;
425 }
426
427 for (int s = 0; insn->srcExists(s); ++s) {
428 const Value *src = insn->src(s).rep();
429 if (insn->src(s).getFile() != FILE_GPR ||
430 src->reg.data.id + src->reg.size / 4 - 1 < minGPR ||
431 src->reg.data.id > maxGPR)
432 continue;
433 addTexUse(uses, insn, texi);
434 return;
435 }
436 }
437
438 for (Graph::EdgeIterator ei = bb->cfg.outgoing(); !ei.end(); ei.next()) {
439 findFirstUsesBB(minGPR, maxGPR, BasicBlock::get(ei.getNode())->getEntry(),
440 texi, uses, visited);
441 }
442 }
443
444 // Texture barriers:
445 // This pass is a bit long and ugly and can probably be optimized.
446 //
447 // 1. obtain a list of TEXes and their outputs' first use(s)
448 // 2. calculate the barrier level of each first use (minimal number of TEXes,
449 // over all paths, between the TEX and the use in question)
450 // 3. for each barrier, if all paths from the source TEX to that barrier
451 // contain a barrier of lesser level, it can be culled
452 bool
453 NVC0LegalizePostRA::insertTextureBarriers(Function *fn)
454 {
455 std::list<TexUse> *uses;
456 std::vector<Instruction *> texes;
457 std::vector<int> bbFirstTex;
458 std::vector<int> bbFirstUse;
459 std::vector<int> texCounts;
460 std::vector<TexUse> useVec;
461 ArrayList insns;
462
463 fn->orderInstructions(insns);
464
465 texCounts.resize(fn->allBBlocks.getSize(), 0);
466 bbFirstTex.resize(fn->allBBlocks.getSize(), insns.getSize());
467 bbFirstUse.resize(fn->allBBlocks.getSize(), insns.getSize());
468
469 // tag BB CFG nodes by their id for later
470 for (ArrayList::Iterator i = fn->allBBlocks.iterator(); !i.end(); i.next()) {
471 BasicBlock *bb = reinterpret_cast<BasicBlock *>(i.get());
472 if (bb)
473 bb->cfg.tag = bb->getId();
474 }
475
476 // gather the first uses for each TEX
477 for (int i = 0; i < insns.getSize(); ++i) {
478 Instruction *tex = reinterpret_cast<Instruction *>(insns.get(i));
479 if (isTextureOp(tex->op)) {
480 texes.push_back(tex);
481 if (!texCounts.at(tex->bb->getId()))
482 bbFirstTex[tex->bb->getId()] = texes.size() - 1;
483 texCounts[tex->bb->getId()]++;
484 }
485 }
486 insns.clear();
487 if (texes.empty())
488 return false;
489 uses = new std::list<TexUse>[texes.size()];
490 if (!uses)
491 return false;
492 for (size_t i = 0; i < texes.size(); ++i) {
493 findFirstUses(texes[i], uses[i]);
494 }
495
496 // determine the barrier level at each use
497 for (size_t i = 0; i < texes.size(); ++i) {
498 for (std::list<TexUse>::iterator u = uses[i].begin(); u != uses[i].end();
499 ++u) {
500 BasicBlock *tb = texes[i]->bb;
501 BasicBlock *ub = u->insn->bb;
502 if (tb == ub) {
503 u->level = 0;
504 for (size_t j = i + 1; j < texes.size() &&
505 texes[j]->bb == tb && texes[j]->serial < u->insn->serial;
506 ++j)
507 u->level++;
508 } else {
509 u->level = fn->cfg.findLightestPathWeight(&tb->cfg,
510 &ub->cfg, texCounts);
511 if (u->level < 0) {
512 WARN("Failed to find path TEX -> TEXBAR\n");
513 u->level = 0;
514 continue;
515 }
516 // this counted all TEXes in the origin block, correct that
517 u->level -= i - bbFirstTex.at(tb->getId()) + 1 /* this TEX */;
518 // and did not count the TEXes in the destination block, add those
519 for (size_t j = bbFirstTex.at(ub->getId()); j < texes.size() &&
520 texes[j]->bb == ub && texes[j]->serial < u->insn->serial;
521 ++j)
522 u->level++;
523 }
524 assert(u->level >= 0);
525 useVec.push_back(*u);
526 }
527 }
528 delete[] uses;
529
530 // insert the barriers
531 for (size_t i = 0; i < useVec.size(); ++i) {
532 Instruction *prev = useVec[i].insn->prev;
533 if (useVec[i].level < 0)
534 continue;
535 if (prev && prev->op == OP_TEXBAR) {
536 if (prev->subOp > useVec[i].level)
537 prev->subOp = useVec[i].level;
538 prev->setSrc(prev->srcCount(), useVec[i].tex->getDef(0));
539 } else {
540 Instruction *bar = new_Instruction(func, OP_TEXBAR, TYPE_NONE);
541 bar->fixed = 1;
542 bar->subOp = useVec[i].level;
543 // make use explicit to ease latency calculation
544 bar->setSrc(bar->srcCount(), useVec[i].tex->getDef(0));
545 useVec[i].insn->bb->insertBefore(useVec[i].insn, bar);
546 }
547 }
548
549 if (fn->getProgram()->optLevel < 3)
550 return true;
551
552 std::vector<Limits> limitT, limitB, limitS; // entry, exit, single
553
554 limitT.resize(fn->allBBlocks.getSize(), Limits(0, 0));
555 limitB.resize(fn->allBBlocks.getSize(), Limits(0, 0));
556 limitS.resize(fn->allBBlocks.getSize());
557
558 // cull unneeded barriers (should do that earlier, but for simplicity)
559 IteratorRef bi = fn->cfg.iteratorCFG();
560 // first calculate min/max outstanding TEXes for each BB
561 for (bi->reset(); !bi->end(); bi->next()) {
562 Graph::Node *n = reinterpret_cast<Graph::Node *>(bi->get());
563 BasicBlock *bb = BasicBlock::get(n);
564 int min = 0;
565 int max = std::numeric_limits<int>::max();
566 for (Instruction *i = bb->getFirst(); i; i = i->next) {
567 if (isTextureOp(i->op)) {
568 min++;
569 if (max < std::numeric_limits<int>::max())
570 max++;
571 } else
572 if (i->op == OP_TEXBAR) {
573 min = MIN2(min, i->subOp);
574 max = MIN2(max, i->subOp);
575 }
576 }
577 // limits when looking at an isolated block
578 limitS[bb->getId()].min = min;
579 limitS[bb->getId()].max = max;
580 }
581 // propagate the min/max values
582 for (unsigned int l = 0; l <= fn->loopNestingBound; ++l) {
583 for (bi->reset(); !bi->end(); bi->next()) {
584 Graph::Node *n = reinterpret_cast<Graph::Node *>(bi->get());
585 BasicBlock *bb = BasicBlock::get(n);
586 const int bbId = bb->getId();
587 for (Graph::EdgeIterator ei = n->incident(); !ei.end(); ei.next()) {
588 BasicBlock *in = BasicBlock::get(ei.getNode());
589 const int inId = in->getId();
590 limitT[bbId].min = MAX2(limitT[bbId].min, limitB[inId].min);
591 limitT[bbId].max = MAX2(limitT[bbId].max, limitB[inId].max);
592 }
593 // I just hope this is correct ...
594 if (limitS[bbId].max == std::numeric_limits<int>::max()) {
595 // no barrier
596 limitB[bbId].min = limitT[bbId].min + limitS[bbId].min;
597 limitB[bbId].max = limitT[bbId].max + limitS[bbId].min;
598 } else {
599 // block contained a barrier
600 limitB[bbId].min = MIN2(limitS[bbId].max,
601 limitT[bbId].min + limitS[bbId].min);
602 limitB[bbId].max = MIN2(limitS[bbId].max,
603 limitT[bbId].max + limitS[bbId].min);
604 }
605 }
606 }
607 // finally delete unnecessary barriers
608 for (bi->reset(); !bi->end(); bi->next()) {
609 Graph::Node *n = reinterpret_cast<Graph::Node *>(bi->get());
610 BasicBlock *bb = BasicBlock::get(n);
611 Instruction *prev = NULL;
612 Instruction *next;
613 int max = limitT[bb->getId()].max;
614 for (Instruction *i = bb->getFirst(); i; i = next) {
615 next = i->next;
616 if (i->op == OP_TEXBAR) {
617 if (i->subOp >= max) {
618 delete_Instruction(prog, i);
619 i = NULL;
620 } else {
621 max = i->subOp;
622 if (prev && prev->op == OP_TEXBAR && prev->subOp >= max) {
623 delete_Instruction(prog, prev);
624 prev = NULL;
625 }
626 }
627 } else
628 if (isTextureOp(i->op)) {
629 max++;
630 }
631 if (i && !i->isNop())
632 prev = i;
633 }
634 }
635 return true;
636 }
637
638 bool
639 NVC0LegalizePostRA::visit(Function *fn)
640 {
641 if (needTexBar)
642 insertTextureBarriers(fn);
643
644 rZero = new_LValue(fn, FILE_GPR);
645 pOne = new_LValue(fn, FILE_PREDICATE);
646 carry = new_LValue(fn, FILE_FLAGS);
647
648 rZero->reg.data.id = (prog->getTarget()->getChipset() >= NVISA_GK20A_CHIPSET) ? 255 : 63;
649 carry->reg.data.id = 0;
650 pOne->reg.data.id = 7;
651
652 return true;
653 }
654
655 void
656 NVC0LegalizePostRA::replaceZero(Instruction *i)
657 {
658 for (int s = 0; i->srcExists(s); ++s) {
659 if (s == 2 && i->op == OP_SUCLAMP)
660 continue;
661 if (s == 1 && i->op == OP_SHLADD)
662 continue;
663 ImmediateValue *imm = i->getSrc(s)->asImm();
664 if (imm) {
665 if (i->op == OP_SELP && s == 2) {
666 i->setSrc(s, pOne);
667 if (imm->reg.data.u64 == 0)
668 i->src(s).mod = i->src(s).mod ^ Modifier(NV50_IR_MOD_NOT);
669 } else if (imm->reg.data.u64 == 0) {
670 i->setSrc(s, rZero);
671 }
672 }
673 }
674 }
675
676 // replace CONT with BRA for single unconditional continue
677 bool
678 NVC0LegalizePostRA::tryReplaceContWithBra(BasicBlock *bb)
679 {
680 if (bb->cfg.incidentCount() != 2 || bb->getEntry()->op != OP_PRECONT)
681 return false;
682 Graph::EdgeIterator ei = bb->cfg.incident();
683 if (ei.getType() != Graph::Edge::BACK)
684 ei.next();
685 if (ei.getType() != Graph::Edge::BACK)
686 return false;
687 BasicBlock *contBB = BasicBlock::get(ei.getNode());
688
689 if (!contBB->getExit() || contBB->getExit()->op != OP_CONT ||
690 contBB->getExit()->getPredicate())
691 return false;
692 contBB->getExit()->op = OP_BRA;
693 bb->remove(bb->getEntry()); // delete PRECONT
694
695 ei.next();
696 assert(ei.end() || ei.getType() != Graph::Edge::BACK);
697 return true;
698 }
699
700 // replace branches to join blocks with join ops
701 void
702 NVC0LegalizePostRA::propagateJoin(BasicBlock *bb)
703 {
704 if (bb->getEntry()->op != OP_JOIN || bb->getEntry()->asFlow()->limit)
705 return;
706 for (Graph::EdgeIterator ei = bb->cfg.incident(); !ei.end(); ei.next()) {
707 BasicBlock *in = BasicBlock::get(ei.getNode());
708 Instruction *exit = in->getExit();
709 if (!exit) {
710 in->insertTail(new FlowInstruction(func, OP_JOIN, bb));
711 // there should always be a terminator instruction
712 WARN("inserted missing terminator in BB:%i\n", in->getId());
713 } else
714 if (exit->op == OP_BRA) {
715 exit->op = OP_JOIN;
716 exit->asFlow()->limit = 1; // must-not-propagate marker
717 }
718 }
719 bb->remove(bb->getEntry());
720 }
721
722 // replaces instructions which would end up as f2f or i2i with faster
723 // alternatives:
724 // - fabs(a) -> fadd(0, abs a)
725 // - fneg(a) -> fadd(neg 0, neg a)
726 // - ineg(a) -> iadd(0, neg a)
727 // - fneg(abs a) -> fadd(neg 0, neg abs a)
728 // - sat(a) -> sat add(0, a)
729 void
730 NVC0LegalizePostRA::replaceCvt(Instruction *cvt)
731 {
732 if (!isFloatType(cvt->sType) && typeSizeof(cvt->sType) != 4)
733 return;
734 if (cvt->sType != cvt->dType)
735 return;
736 // we could make it work, but in this case we have optimizations disabled
737 // and we don't really care either way.
738 if (cvt->src(0).getFile() != FILE_GPR &&
739 cvt->src(0).getFile() != FILE_MEMORY_CONST)
740 return;
741
742 Modifier mod0, mod1;
743
744 switch (cvt->op) {
745 case OP_ABS:
746 if (cvt->src(0).mod)
747 return;
748 if (!isFloatType(cvt->sType))
749 return;
750 mod0 = 0;
751 mod1 = NV50_IR_MOD_ABS;
752 break;
753 case OP_NEG:
754 if (!isFloatType(cvt->sType) && cvt->src(0).mod)
755 return;
756 if (isFloatType(cvt->sType) &&
757 (cvt->src(0).mod && cvt->src(0).mod != Modifier(NV50_IR_MOD_ABS)))
758 return;
759
760 mod0 = isFloatType(cvt->sType) ? NV50_IR_MOD_NEG : 0;
761 mod1 = cvt->src(0).mod == Modifier(NV50_IR_MOD_ABS) ?
762 NV50_IR_MOD_NEG_ABS : NV50_IR_MOD_NEG;
763 break;
764 case OP_SAT:
765 if (!isFloatType(cvt->sType) && cvt->src(0).mod.abs())
766 return;
767 mod0 = 0;
768 mod1 = cvt->src(0).mod;
769 cvt->saturate = true;
770 break;
771 default:
772 return;
773 }
774
775 cvt->op = OP_ADD;
776 cvt->moveSources(0, 1);
777 cvt->setSrc(0, rZero);
778 cvt->src(0).mod = mod0;
779 cvt->src(1).mod = mod1;
780 }
781
782 bool
783 NVC0LegalizePostRA::visit(BasicBlock *bb)
784 {
785 Instruction *i, *next;
786
787 // remove pseudo operations and non-fixed no-ops, split 64 bit operations
788 for (i = bb->getFirst(); i; i = next) {
789 next = i->next;
790 if (i->op == OP_EMIT || i->op == OP_RESTART) {
791 if (!i->getDef(0)->refCount())
792 i->setDef(0, NULL);
793 if (i->src(0).getFile() == FILE_IMMEDIATE)
794 i->setSrc(0, rZero); // initial value must be 0
795 replaceZero(i);
796 } else
797 if (i->isNop()) {
798 bb->remove(i);
799 } else
800 if (i->op == OP_BAR && i->subOp == NV50_IR_SUBOP_BAR_SYNC &&
801 prog->getType() != Program::TYPE_COMPUTE) {
802 // It seems like barriers are never required for tessellation since
803 // the warp size is 32, and there are always at most 32 tcs threads.
804 bb->remove(i);
805 } else
806 if (i->op == OP_LOAD && i->subOp == NV50_IR_SUBOP_LDC_IS) {
807 int offset = i->src(0).get()->reg.data.offset;
808 if (abs(offset) >= 0x10000)
809 i->src(0).get()->reg.fileIndex += offset >> 16;
810 i->src(0).get()->reg.data.offset = (int)(short)offset;
811 } else {
812 // TODO: Move this to before register allocation for operations that
813 // need the $c register !
814 if (typeSizeof(i->sType) == 8 || typeSizeof(i->dType) == 8) {
815 Instruction *hi;
816 hi = BuildUtil::split64BitOpPostRA(func, i, rZero, carry);
817 if (hi)
818 next = hi;
819 }
820
821 if (i->op == OP_SAT || i->op == OP_NEG || i->op == OP_ABS)
822 replaceCvt(i);
823
824 if (i->op != OP_MOV && i->op != OP_PFETCH)
825 replaceZero(i);
826 }
827 }
828 if (!bb->getEntry())
829 return true;
830
831 if (!tryReplaceContWithBra(bb))
832 propagateJoin(bb);
833
834 return true;
835 }
836
837 NVC0LoweringPass::NVC0LoweringPass(Program *prog) : targ(prog->getTarget())
838 {
839 bld.setProgram(prog);
840 }
841
842 bool
843 NVC0LoweringPass::visit(Function *fn)
844 {
845 if (prog->getType() == Program::TYPE_GEOMETRY) {
846 assert(!strncmp(fn->getName(), "MAIN", 4));
847 // TODO: when we generate actual functions pass this value along somehow
848 bld.setPosition(BasicBlock::get(fn->cfg.getRoot()), false);
849 gpEmitAddress = bld.loadImm(NULL, 0)->asLValue();
850 if (fn->cfgExit) {
851 bld.setPosition(BasicBlock::get(fn->cfgExit)->getExit(), false);
852 bld.mkMovToReg(0, gpEmitAddress);
853 }
854 }
855 return true;
856 }
857
858 bool
859 NVC0LoweringPass::visit(BasicBlock *bb)
860 {
861 return true;
862 }
863
864 inline Value *
865 NVC0LoweringPass::loadTexHandle(Value *ptr, unsigned int slot)
866 {
867 uint8_t b = prog->driver->io.auxCBSlot;
868 uint32_t off = prog->driver->io.texBindBase + slot * 4;
869
870 if (ptr)
871 ptr = bld.mkOp2v(OP_SHL, TYPE_U32, bld.getSSA(), ptr, bld.mkImm(2));
872
873 return bld.
874 mkLoadv(TYPE_U32, bld.mkSymbol(FILE_MEMORY_CONST, b, TYPE_U32, off), ptr);
875 }
876
877 // move array source to first slot, convert to u16, add indirections
878 bool
879 NVC0LoweringPass::handleTEX(TexInstruction *i)
880 {
881 const int dim = i->tex.target.getDim() + i->tex.target.isCube();
882 const int arg = i->tex.target.getArgCount();
883 const int lyr = arg - (i->tex.target.isMS() ? 2 : 1);
884 const int chipset = prog->getTarget()->getChipset();
885
886 /* Only normalize in the non-explicit derivatives case. For explicit
887 * derivatives, this is handled in handleManualTXD.
888 */
889 if (i->tex.target.isCube() && i->dPdx[0].get() == NULL) {
890 Value *src[3], *val;
891 int c;
892 for (c = 0; c < 3; ++c)
893 src[c] = bld.mkOp1v(OP_ABS, TYPE_F32, bld.getSSA(), i->getSrc(c));
894 val = bld.getScratch();
895 bld.mkOp2(OP_MAX, TYPE_F32, val, src[0], src[1]);
896 bld.mkOp2(OP_MAX, TYPE_F32, val, src[2], val);
897 bld.mkOp1(OP_RCP, TYPE_F32, val, val);
898 for (c = 0; c < 3; ++c) {
899 i->setSrc(c, bld.mkOp2v(OP_MUL, TYPE_F32, bld.getSSA(),
900 i->getSrc(c), val));
901 }
902 }
903
904 // Arguments to the TEX instruction are a little insane. Even though the
905 // encoding is identical between SM20 and SM30, the arguments mean
906 // different things between Fermi and Kepler+. A lot of arguments are
907 // optional based on flags passed to the instruction. This summarizes the
908 // order of things.
909 //
910 // Fermi:
911 // array/indirect
912 // coords
913 // sample
914 // lod bias
915 // depth compare
916 // offsets:
917 // - tg4: 8 bits each, either 2 (1 offset reg) or 8 (2 offset reg)
918 // - other: 4 bits each, single reg
919 //
920 // Kepler+:
921 // indirect handle
922 // array (+ offsets for txd in upper 16 bits)
923 // coords
924 // sample
925 // lod bias
926 // depth compare
927 // offsets (same as fermi, except txd which takes it with array)
928 //
929 // Maxwell (tex):
930 // array
931 // coords
932 // indirect handle
933 // sample
934 // lod bias
935 // depth compare
936 // offsets
937 //
938 // Maxwell (txd):
939 // indirect handle
940 // coords
941 // array + offsets
942 // derivatives
943
944 if (chipset >= NVISA_GK104_CHIPSET) {
945 if (i->tex.rIndirectSrc >= 0 || i->tex.sIndirectSrc >= 0) {
946 // XXX this ignores tsc, and assumes a 1:1 mapping
947 assert(i->tex.rIndirectSrc >= 0);
948 if (!i->tex.bindless) {
949 Value *hnd = loadTexHandle(i->getIndirectR(), i->tex.r);
950 i->tex.r = 0xff;
951 i->tex.s = 0x1f;
952 i->setIndirectR(hnd);
953 }
954 i->setIndirectS(NULL);
955 } else if (i->tex.r == i->tex.s || i->op == OP_TXF) {
956 if (i->tex.r == 0xffff)
957 i->tex.r = prog->driver->io.fbtexBindBase / 4;
958 else
959 i->tex.r += prog->driver->io.texBindBase / 4;
960 i->tex.s = 0; // only a single cX[] value possible here
961 } else {
962 Value *hnd = bld.getScratch();
963 Value *rHnd = loadTexHandle(NULL, i->tex.r);
964 Value *sHnd = loadTexHandle(NULL, i->tex.s);
965
966 bld.mkOp3(OP_INSBF, TYPE_U32, hnd, rHnd, bld.mkImm(0x1400), sHnd);
967
968 i->tex.r = 0; // not used for indirect tex
969 i->tex.s = 0;
970 i->setIndirectR(hnd);
971 }
972 if (i->tex.target.isArray()) {
973 LValue *layer = new_LValue(func, FILE_GPR);
974 Value *src = i->getSrc(lyr);
975 const int sat = (i->op == OP_TXF) ? 1 : 0;
976 DataType sTy = (i->op == OP_TXF) ? TYPE_U32 : TYPE_F32;
977 bld.mkCvt(OP_CVT, TYPE_U16, layer, sTy, src)->saturate = sat;
978 if (i->op != OP_TXD || chipset < NVISA_GM107_CHIPSET) {
979 for (int s = dim; s >= 1; --s)
980 i->setSrc(s, i->getSrc(s - 1));
981 i->setSrc(0, layer);
982 } else {
983 i->setSrc(dim, layer);
984 }
985 }
986 // Move the indirect reference to the first place
987 if (i->tex.rIndirectSrc >= 0 && (
988 i->op == OP_TXD || chipset < NVISA_GM107_CHIPSET)) {
989 Value *hnd = i->getIndirectR();
990
991 i->setIndirectR(NULL);
992 i->moveSources(0, 1);
993 i->setSrc(0, hnd);
994 i->tex.rIndirectSrc = 0;
995 i->tex.sIndirectSrc = -1;
996 }
997 // Move the indirect reference to right after the coords
998 else if (i->tex.rIndirectSrc >= 0 && chipset >= NVISA_GM107_CHIPSET) {
999 Value *hnd = i->getIndirectR();
1000
1001 i->setIndirectR(NULL);
1002 i->moveSources(arg, 1);
1003 i->setSrc(arg, hnd);
1004 i->tex.rIndirectSrc = 0;
1005 i->tex.sIndirectSrc = -1;
1006 }
1007 } else
1008 // (nvc0) generate and move the tsc/tic/array source to the front
1009 if (i->tex.target.isArray() || i->tex.rIndirectSrc >= 0 || i->tex.sIndirectSrc >= 0) {
1010 LValue *src = new_LValue(func, FILE_GPR); // 0xttxsaaaa
1011
1012 Value *ticRel = i->getIndirectR();
1013 Value *tscRel = i->getIndirectS();
1014
1015 if (i->tex.r == 0xffff) {
1016 i->tex.r = 0x20;
1017 i->tex.s = 0x10;
1018 }
1019
1020 if (ticRel) {
1021 i->setSrc(i->tex.rIndirectSrc, NULL);
1022 if (i->tex.r)
1023 ticRel = bld.mkOp2v(OP_ADD, TYPE_U32, bld.getScratch(),
1024 ticRel, bld.mkImm(i->tex.r));
1025 }
1026 if (tscRel) {
1027 i->setSrc(i->tex.sIndirectSrc, NULL);
1028 if (i->tex.s)
1029 tscRel = bld.mkOp2v(OP_ADD, TYPE_U32, bld.getScratch(),
1030 tscRel, bld.mkImm(i->tex.s));
1031 }
1032
1033 Value *arrayIndex = i->tex.target.isArray() ? i->getSrc(lyr) : NULL;
1034 if (arrayIndex) {
1035 for (int s = dim; s >= 1; --s)
1036 i->setSrc(s, i->getSrc(s - 1));
1037 i->setSrc(0, arrayIndex);
1038 } else {
1039 i->moveSources(0, 1);
1040 }
1041
1042 if (arrayIndex) {
1043 int sat = (i->op == OP_TXF) ? 1 : 0;
1044 DataType sTy = (i->op == OP_TXF) ? TYPE_U32 : TYPE_F32;
1045 bld.mkCvt(OP_CVT, TYPE_U16, src, sTy, arrayIndex)->saturate = sat;
1046 } else {
1047 bld.loadImm(src, 0);
1048 }
1049
1050 if (ticRel)
1051 bld.mkOp3(OP_INSBF, TYPE_U32, src, ticRel, bld.mkImm(0x0917), src);
1052 if (tscRel)
1053 bld.mkOp3(OP_INSBF, TYPE_U32, src, tscRel, bld.mkImm(0x0710), src);
1054
1055 i->setSrc(0, src);
1056 }
1057
1058 // For nvc0, the sample id has to be in the second operand, as the offset
1059 // does. Right now we don't know how to pass both in, and this case can't
1060 // happen with OpenGL. On nve0, the sample id is part of the texture
1061 // coordinate argument.
1062 assert(chipset >= NVISA_GK104_CHIPSET ||
1063 !i->tex.useOffsets || !i->tex.target.isMS());
1064
1065 // offset is between lod and dc
1066 if (i->tex.useOffsets) {
1067 int n, c;
1068 int s = i->srcCount(0xff, true);
1069 if (i->op != OP_TXD || chipset < NVISA_GK104_CHIPSET) {
1070 if (i->tex.target.isShadow())
1071 s--;
1072 if (i->srcExists(s)) // move potential predicate out of the way
1073 i->moveSources(s, 1);
1074 if (i->tex.useOffsets == 4 && i->srcExists(s + 1))
1075 i->moveSources(s + 1, 1);
1076 }
1077 if (i->op == OP_TXG) {
1078 // Either there is 1 offset, which goes into the 2 low bytes of the
1079 // first source, or there are 4 offsets, which go into 2 sources (8
1080 // values, 1 byte each).
1081 Value *offs[2] = {NULL, NULL};
1082 for (n = 0; n < i->tex.useOffsets; n++) {
1083 for (c = 0; c < 2; ++c) {
1084 if ((n % 2) == 0 && c == 0)
1085 bld.mkMov(offs[n / 2] = bld.getScratch(), i->offset[n][c].get());
1086 else
1087 bld.mkOp3(OP_INSBF, TYPE_U32,
1088 offs[n / 2],
1089 i->offset[n][c].get(),
1090 bld.mkImm(0x800 | ((n * 16 + c * 8) % 32)),
1091 offs[n / 2]);
1092 }
1093 }
1094 i->setSrc(s, offs[0]);
1095 if (offs[1])
1096 i->setSrc(s + 1, offs[1]);
1097 } else {
1098 unsigned imm = 0;
1099 assert(i->tex.useOffsets == 1);
1100 for (c = 0; c < 3; ++c) {
1101 ImmediateValue val;
1102 if (!i->offset[0][c].getImmediate(val))
1103 assert(!"non-immediate offset passed to non-TXG");
1104 imm |= (val.reg.data.u32 & 0xf) << (c * 4);
1105 }
1106 if (i->op == OP_TXD && chipset >= NVISA_GK104_CHIPSET) {
1107 // The offset goes into the upper 16 bits of the array index. So
1108 // create it if it's not already there, and INSBF it if it already
1109 // is.
1110 s = (i->tex.rIndirectSrc >= 0) ? 1 : 0;
1111 if (chipset >= NVISA_GM107_CHIPSET)
1112 s += dim;
1113 if (i->tex.target.isArray()) {
1114 Value *offset = bld.getScratch();
1115 bld.mkOp3(OP_INSBF, TYPE_U32, offset,
1116 bld.loadImm(NULL, imm), bld.mkImm(0xc10),
1117 i->getSrc(s));
1118 i->setSrc(s, offset);
1119 } else {
1120 i->moveSources(s, 1);
1121 i->setSrc(s, bld.loadImm(NULL, imm << 16));
1122 }
1123 } else {
1124 i->setSrc(s, bld.loadImm(NULL, imm));
1125 }
1126 }
1127 }
1128
1129 if (chipset >= NVISA_GK104_CHIPSET) {
1130 //
1131 // If TEX requires more than 4 sources, the 2nd register tuple must be
1132 // aligned to 4, even if it consists of just a single 4-byte register.
1133 //
1134 // XXX HACK: We insert 0 sources to avoid the 5 or 6 regs case.
1135 //
1136 int s = i->srcCount(0xff, true);
1137 if (s > 4 && s < 7) {
1138 if (i->srcExists(s)) // move potential predicate out of the way
1139 i->moveSources(s, 7 - s);
1140 while (s < 7)
1141 i->setSrc(s++, bld.loadImm(NULL, 0));
1142 }
1143 }
1144
1145 return true;
1146 }
1147
1148 bool
1149 NVC0LoweringPass::handleManualTXD(TexInstruction *i)
1150 {
1151 // Always done from the l0 perspective. This is the way that NVIDIA's
1152 // driver does it, and doing it from the "current" lane's perpsective
1153 // doesn't seem to always work for reasons that aren't altogether clear,
1154 // even in frag shaders.
1155 //
1156 // Note that we must move not only the coordinates into lane0, but also all
1157 // ancillary arguments, like array indices and depth compare as they may
1158 // differ between lanes. Offsets for TXD are supposed to be uniform, so we
1159 // leave them alone.
1160 static const uint8_t qOps[2] =
1161 { QUADOP(MOV2, ADD, MOV2, ADD), QUADOP(MOV2, MOV2, ADD, ADD) };
1162
1163 Value *def[4][4];
1164 Value *crd[3], *arr[2], *shadow;
1165 Instruction *tex;
1166 Value *zero = bld.loadImm(bld.getSSA(), 0);
1167 int l, c;
1168 const int dim = i->tex.target.getDim() + i->tex.target.isCube();
1169
1170 // This function is invoked after handleTEX lowering, so we have to expect
1171 // the arguments in the order that the hw wants them. For Fermi, array and
1172 // indirect are both in the leading arg, while for Kepler, array and
1173 // indirect are separate (and both precede the coordinates). Maxwell is
1174 // handled in a separate function.
1175 int array;
1176 if (targ->getChipset() < NVISA_GK104_CHIPSET)
1177 array = i->tex.target.isArray() || i->tex.rIndirectSrc >= 0;
1178 else
1179 array = i->tex.target.isArray() + (i->tex.rIndirectSrc >= 0);
1180
1181 i->op = OP_TEX; // no need to clone dPdx/dPdy later
1182
1183 for (c = 0; c < dim; ++c)
1184 crd[c] = bld.getScratch();
1185 for (c = 0; c < array; ++c)
1186 arr[c] = bld.getScratch();
1187 shadow = bld.getScratch();
1188
1189 for (l = 0; l < 4; ++l) {
1190 Value *src[3], *val;
1191
1192 bld.mkOp(OP_QUADON, TYPE_NONE, NULL);
1193 // we're using the texture result from lane 0 in all cases, so make sure
1194 // that lane 0 is pointing at the proper array index, indirect value,
1195 // and depth compare.
1196 if (l != 0) {
1197 for (c = 0; c < array; ++c)
1198 bld.mkQuadop(0x00, arr[c], l, i->getSrc(c), zero);
1199 if (i->tex.target.isShadow()) {
1200 // The next argument after coords is the depth compare
1201 bld.mkQuadop(0x00, shadow, l, i->getSrc(array + dim), zero);
1202 }
1203 }
1204 // mov position coordinates from lane l to all lanes
1205 for (c = 0; c < dim; ++c)
1206 bld.mkQuadop(0x00, crd[c], l, i->getSrc(c + array), zero);
1207 // add dPdx from lane l to lanes dx
1208 for (c = 0; c < dim; ++c)
1209 bld.mkQuadop(qOps[0], crd[c], l, i->dPdx[c].get(), crd[c]);
1210 // add dPdy from lane l to lanes dy
1211 for (c = 0; c < dim; ++c)
1212 bld.mkQuadop(qOps[1], crd[c], l, i->dPdy[c].get(), crd[c]);
1213 // normalize cube coordinates
1214 if (i->tex.target.isCube()) {
1215 for (c = 0; c < 3; ++c)
1216 src[c] = bld.mkOp1v(OP_ABS, TYPE_F32, bld.getSSA(), crd[c]);
1217 val = bld.getScratch();
1218 bld.mkOp2(OP_MAX, TYPE_F32, val, src[0], src[1]);
1219 bld.mkOp2(OP_MAX, TYPE_F32, val, src[2], val);
1220 bld.mkOp1(OP_RCP, TYPE_F32, val, val);
1221 for (c = 0; c < 3; ++c)
1222 src[c] = bld.mkOp2v(OP_MUL, TYPE_F32, bld.getSSA(), crd[c], val);
1223 } else {
1224 for (c = 0; c < dim; ++c)
1225 src[c] = crd[c];
1226 }
1227 // texture
1228 bld.insert(tex = cloneForward(func, i));
1229 if (l != 0) {
1230 for (c = 0; c < array; ++c)
1231 tex->setSrc(c, arr[c]);
1232 if (i->tex.target.isShadow())
1233 tex->setSrc(array + dim, shadow);
1234 }
1235 for (c = 0; c < dim; ++c)
1236 tex->setSrc(c + array, src[c]);
1237 // broadcast results from lane 0 to all lanes so that the moves *into*
1238 // the target lane pick up the proper value.
1239 if (l != 0)
1240 for (c = 0; i->defExists(c); ++c)
1241 bld.mkQuadop(0x00, tex->getDef(c), 0, tex->getDef(c), zero);
1242 bld.mkOp(OP_QUADPOP, TYPE_NONE, NULL);
1243
1244 // save results
1245 for (c = 0; i->defExists(c); ++c) {
1246 Instruction *mov;
1247 def[c][l] = bld.getSSA();
1248 mov = bld.mkMov(def[c][l], tex->getDef(c));
1249 mov->fixed = 1;
1250 mov->lanes = 1 << l;
1251 }
1252 }
1253
1254 for (c = 0; i->defExists(c); ++c) {
1255 Instruction *u = bld.mkOp(OP_UNION, TYPE_U32, i->getDef(c));
1256 for (l = 0; l < 4; ++l)
1257 u->setSrc(l, def[c][l]);
1258 }
1259
1260 i->bb->remove(i);
1261 return true;
1262 }
1263
1264 bool
1265 NVC0LoweringPass::handleTXD(TexInstruction *txd)
1266 {
1267 int dim = txd->tex.target.getDim() + txd->tex.target.isCube();
1268 unsigned arg = txd->tex.target.getArgCount();
1269 unsigned expected_args = arg;
1270 const int chipset = prog->getTarget()->getChipset();
1271
1272 if (chipset >= NVISA_GK104_CHIPSET) {
1273 if (!txd->tex.target.isArray() && txd->tex.useOffsets)
1274 expected_args++;
1275 if (txd->tex.rIndirectSrc >= 0 || txd->tex.sIndirectSrc >= 0)
1276 expected_args++;
1277 } else {
1278 if (txd->tex.useOffsets)
1279 expected_args++;
1280 if (!txd->tex.target.isArray() && (
1281 txd->tex.rIndirectSrc >= 0 || txd->tex.sIndirectSrc >= 0))
1282 expected_args++;
1283 }
1284
1285 if (expected_args > 4 ||
1286 dim > 2 ||
1287 txd->tex.target.isShadow())
1288 txd->op = OP_TEX;
1289
1290 handleTEX(txd);
1291 while (txd->srcExists(arg))
1292 ++arg;
1293
1294 txd->tex.derivAll = true;
1295 if (txd->op == OP_TEX)
1296 return handleManualTXD(txd);
1297
1298 assert(arg == expected_args);
1299 for (int c = 0; c < dim; ++c) {
1300 txd->setSrc(arg + c * 2 + 0, txd->dPdx[c]);
1301 txd->setSrc(arg + c * 2 + 1, txd->dPdy[c]);
1302 txd->dPdx[c].set(NULL);
1303 txd->dPdy[c].set(NULL);
1304 }
1305
1306 // In this case we have fewer than 4 "real" arguments, which means that
1307 // handleTEX didn't apply any padding. However we have to make sure that
1308 // the second "group" of arguments still gets padded up to 4.
1309 if (chipset >= NVISA_GK104_CHIPSET) {
1310 int s = arg + 2 * dim;
1311 if (s >= 4 && s < 7) {
1312 if (txd->srcExists(s)) // move potential predicate out of the way
1313 txd->moveSources(s, 7 - s);
1314 while (s < 7)
1315 txd->setSrc(s++, bld.loadImm(NULL, 0));
1316 }
1317 }
1318
1319 return true;
1320 }
1321
1322 bool
1323 NVC0LoweringPass::handleTXQ(TexInstruction *txq)
1324 {
1325 const int chipset = prog->getTarget()->getChipset();
1326 if (chipset >= NVISA_GK104_CHIPSET && txq->tex.rIndirectSrc < 0)
1327 txq->tex.r += prog->driver->io.texBindBase / 4;
1328
1329 if (txq->tex.rIndirectSrc < 0)
1330 return true;
1331
1332 Value *ticRel = txq->getIndirectR();
1333
1334 txq->setIndirectS(NULL);
1335 txq->tex.sIndirectSrc = -1;
1336
1337 assert(ticRel);
1338
1339 if (chipset < NVISA_GK104_CHIPSET) {
1340 LValue *src = new_LValue(func, FILE_GPR); // 0xttxsaaaa
1341
1342 txq->setSrc(txq->tex.rIndirectSrc, NULL);
1343 if (txq->tex.r)
1344 ticRel = bld.mkOp2v(OP_ADD, TYPE_U32, bld.getScratch(),
1345 ticRel, bld.mkImm(txq->tex.r));
1346
1347 bld.mkOp2(OP_SHL, TYPE_U32, src, ticRel, bld.mkImm(0x17));
1348
1349 txq->moveSources(0, 1);
1350 txq->setSrc(0, src);
1351 } else {
1352 Value *hnd = loadTexHandle(txq->getIndirectR(), txq->tex.r);
1353 txq->tex.r = 0xff;
1354 txq->tex.s = 0x1f;
1355
1356 txq->setIndirectR(NULL);
1357 txq->moveSources(0, 1);
1358 txq->setSrc(0, hnd);
1359 txq->tex.rIndirectSrc = 0;
1360 }
1361
1362 return true;
1363 }
1364
1365 bool
1366 NVC0LoweringPass::handleTXLQ(TexInstruction *i)
1367 {
1368 /* The outputs are inverted compared to what the TGSI instruction
1369 * expects. Take that into account in the mask.
1370 */
1371 assert((i->tex.mask & ~3) == 0);
1372 if (i->tex.mask == 1)
1373 i->tex.mask = 2;
1374 else if (i->tex.mask == 2)
1375 i->tex.mask = 1;
1376 handleTEX(i);
1377 bld.setPosition(i, true);
1378
1379 /* The returned values are not quite what we want:
1380 * (a) convert from s16/u16 to f32
1381 * (b) multiply by 1/256
1382 */
1383 for (int def = 0; def < 2; ++def) {
1384 if (!i->defExists(def))
1385 continue;
1386 enum DataType type = TYPE_S16;
1387 if (i->tex.mask == 2 || def > 0)
1388 type = TYPE_U16;
1389 bld.mkCvt(OP_CVT, TYPE_F32, i->getDef(def), type, i->getDef(def));
1390 bld.mkOp2(OP_MUL, TYPE_F32, i->getDef(def),
1391 i->getDef(def), bld.loadImm(NULL, 1.0f / 256));
1392 }
1393 if (i->tex.mask == 3) {
1394 LValue *t = new_LValue(func, FILE_GPR);
1395 bld.mkMov(t, i->getDef(0));
1396 bld.mkMov(i->getDef(0), i->getDef(1));
1397 bld.mkMov(i->getDef(1), t);
1398 }
1399 return true;
1400 }
1401
1402 bool
1403 NVC0LoweringPass::handleBUFQ(Instruction *bufq)
1404 {
1405 bufq->op = OP_MOV;
1406 bufq->setSrc(0, loadBufLength32(bufq->getIndirect(0, 1),
1407 bufq->getSrc(0)->reg.fileIndex * 16));
1408 bufq->setIndirect(0, 0, NULL);
1409 bufq->setIndirect(0, 1, NULL);
1410 return true;
1411 }
1412
1413 void
1414 NVC0LoweringPass::handleSharedATOMNVE4(Instruction *atom)
1415 {
1416 assert(atom->src(0).getFile() == FILE_MEMORY_SHARED);
1417
1418 BasicBlock *currBB = atom->bb;
1419 BasicBlock *tryLockBB = atom->bb->splitBefore(atom, false);
1420 BasicBlock *joinBB = atom->bb->splitAfter(atom);
1421 BasicBlock *setAndUnlockBB = new BasicBlock(func);
1422 BasicBlock *failLockBB = new BasicBlock(func);
1423
1424 bld.setPosition(currBB, true);
1425 assert(!currBB->joinAt);
1426 currBB->joinAt = bld.mkFlow(OP_JOINAT, joinBB, CC_ALWAYS, NULL);
1427
1428 CmpInstruction *pred =
1429 bld.mkCmp(OP_SET, CC_EQ, TYPE_U32, bld.getSSA(1, FILE_PREDICATE),
1430 TYPE_U32, bld.mkImm(0), bld.mkImm(1));
1431
1432 bld.mkFlow(OP_BRA, tryLockBB, CC_ALWAYS, NULL);
1433 currBB->cfg.attach(&tryLockBB->cfg, Graph::Edge::TREE);
1434
1435 bld.setPosition(tryLockBB, true);
1436
1437 Instruction *ld =
1438 bld.mkLoad(TYPE_U32, atom->getDef(0), atom->getSrc(0)->asSym(),
1439 atom->getIndirect(0, 0));
1440 ld->setDef(1, bld.getSSA(1, FILE_PREDICATE));
1441 ld->subOp = NV50_IR_SUBOP_LOAD_LOCKED;
1442
1443 bld.mkFlow(OP_BRA, setAndUnlockBB, CC_P, ld->getDef(1));
1444 bld.mkFlow(OP_BRA, failLockBB, CC_ALWAYS, NULL);
1445 tryLockBB->cfg.attach(&failLockBB->cfg, Graph::Edge::CROSS);
1446 tryLockBB->cfg.attach(&setAndUnlockBB->cfg, Graph::Edge::TREE);
1447
1448 tryLockBB->cfg.detach(&joinBB->cfg);
1449 bld.remove(atom);
1450
1451 bld.setPosition(setAndUnlockBB, true);
1452 Value *stVal;
1453 if (atom->subOp == NV50_IR_SUBOP_ATOM_EXCH) {
1454 // Read the old value, and write the new one.
1455 stVal = atom->getSrc(1);
1456 } else if (atom->subOp == NV50_IR_SUBOP_ATOM_CAS) {
1457 CmpInstruction *set =
1458 bld.mkCmp(OP_SET, CC_EQ, TYPE_U32, bld.getSSA(),
1459 TYPE_U32, ld->getDef(0), atom->getSrc(1));
1460
1461 bld.mkCmp(OP_SLCT, CC_NE, TYPE_U32, (stVal = bld.getSSA()),
1462 TYPE_U32, atom->getSrc(2), ld->getDef(0), set->getDef(0));
1463 } else {
1464 operation op;
1465
1466 switch (atom->subOp) {
1467 case NV50_IR_SUBOP_ATOM_ADD:
1468 op = OP_ADD;
1469 break;
1470 case NV50_IR_SUBOP_ATOM_AND:
1471 op = OP_AND;
1472 break;
1473 case NV50_IR_SUBOP_ATOM_OR:
1474 op = OP_OR;
1475 break;
1476 case NV50_IR_SUBOP_ATOM_XOR:
1477 op = OP_XOR;
1478 break;
1479 case NV50_IR_SUBOP_ATOM_MIN:
1480 op = OP_MIN;
1481 break;
1482 case NV50_IR_SUBOP_ATOM_MAX:
1483 op = OP_MAX;
1484 break;
1485 default:
1486 assert(0);
1487 return;
1488 }
1489
1490 stVal = bld.mkOp2v(op, atom->dType, bld.getSSA(), ld->getDef(0),
1491 atom->getSrc(1));
1492 }
1493
1494 Instruction *st =
1495 bld.mkStore(OP_STORE, TYPE_U32, atom->getSrc(0)->asSym(),
1496 atom->getIndirect(0, 0), stVal);
1497 st->setDef(0, pred->getDef(0));
1498 st->subOp = NV50_IR_SUBOP_STORE_UNLOCKED;
1499
1500 bld.mkFlow(OP_BRA, failLockBB, CC_ALWAYS, NULL);
1501 setAndUnlockBB->cfg.attach(&failLockBB->cfg, Graph::Edge::TREE);
1502
1503 // Lock until the store has not been performed.
1504 bld.setPosition(failLockBB, true);
1505 bld.mkFlow(OP_BRA, tryLockBB, CC_NOT_P, pred->getDef(0));
1506 bld.mkFlow(OP_BRA, joinBB, CC_ALWAYS, NULL);
1507 failLockBB->cfg.attach(&tryLockBB->cfg, Graph::Edge::BACK);
1508 failLockBB->cfg.attach(&joinBB->cfg, Graph::Edge::TREE);
1509
1510 bld.setPosition(joinBB, false);
1511 bld.mkFlow(OP_JOIN, NULL, CC_ALWAYS, NULL)->fixed = 1;
1512 }
1513
1514 void
1515 NVC0LoweringPass::handleSharedATOM(Instruction *atom)
1516 {
1517 assert(atom->src(0).getFile() == FILE_MEMORY_SHARED);
1518
1519 BasicBlock *currBB = atom->bb;
1520 BasicBlock *tryLockAndSetBB = atom->bb->splitBefore(atom, false);
1521 BasicBlock *joinBB = atom->bb->splitAfter(atom);
1522
1523 bld.setPosition(currBB, true);
1524 assert(!currBB->joinAt);
1525 currBB->joinAt = bld.mkFlow(OP_JOINAT, joinBB, CC_ALWAYS, NULL);
1526
1527 bld.mkFlow(OP_BRA, tryLockAndSetBB, CC_ALWAYS, NULL);
1528 currBB->cfg.attach(&tryLockAndSetBB->cfg, Graph::Edge::TREE);
1529
1530 bld.setPosition(tryLockAndSetBB, true);
1531
1532 Instruction *ld =
1533 bld.mkLoad(TYPE_U32, atom->getDef(0), atom->getSrc(0)->asSym(),
1534 atom->getIndirect(0, 0));
1535 ld->setDef(1, bld.getSSA(1, FILE_PREDICATE));
1536 ld->subOp = NV50_IR_SUBOP_LOAD_LOCKED;
1537
1538 Value *stVal;
1539 if (atom->subOp == NV50_IR_SUBOP_ATOM_EXCH) {
1540 // Read the old value, and write the new one.
1541 stVal = atom->getSrc(1);
1542 } else if (atom->subOp == NV50_IR_SUBOP_ATOM_CAS) {
1543 CmpInstruction *set =
1544 bld.mkCmp(OP_SET, CC_EQ, TYPE_U32, bld.getSSA(1, FILE_PREDICATE),
1545 TYPE_U32, ld->getDef(0), atom->getSrc(1));
1546 set->setPredicate(CC_P, ld->getDef(1));
1547
1548 Instruction *selp =
1549 bld.mkOp3(OP_SELP, TYPE_U32, bld.getSSA(), ld->getDef(0),
1550 atom->getSrc(2), set->getDef(0));
1551 selp->src(2).mod = Modifier(NV50_IR_MOD_NOT);
1552 selp->setPredicate(CC_P, ld->getDef(1));
1553
1554 stVal = selp->getDef(0);
1555 } else {
1556 operation op;
1557
1558 switch (atom->subOp) {
1559 case NV50_IR_SUBOP_ATOM_ADD:
1560 op = OP_ADD;
1561 break;
1562 case NV50_IR_SUBOP_ATOM_AND:
1563 op = OP_AND;
1564 break;
1565 case NV50_IR_SUBOP_ATOM_OR:
1566 op = OP_OR;
1567 break;
1568 case NV50_IR_SUBOP_ATOM_XOR:
1569 op = OP_XOR;
1570 break;
1571 case NV50_IR_SUBOP_ATOM_MIN:
1572 op = OP_MIN;
1573 break;
1574 case NV50_IR_SUBOP_ATOM_MAX:
1575 op = OP_MAX;
1576 break;
1577 default:
1578 assert(0);
1579 return;
1580 }
1581
1582 Instruction *i =
1583 bld.mkOp2(op, atom->dType, bld.getSSA(), ld->getDef(0),
1584 atom->getSrc(1));
1585 i->setPredicate(CC_P, ld->getDef(1));
1586
1587 stVal = i->getDef(0);
1588 }
1589
1590 Instruction *st =
1591 bld.mkStore(OP_STORE, TYPE_U32, atom->getSrc(0)->asSym(),
1592 atom->getIndirect(0, 0), stVal);
1593 st->setPredicate(CC_P, ld->getDef(1));
1594 st->subOp = NV50_IR_SUBOP_STORE_UNLOCKED;
1595
1596 // Loop until the lock is acquired.
1597 bld.mkFlow(OP_BRA, tryLockAndSetBB, CC_NOT_P, ld->getDef(1));
1598 tryLockAndSetBB->cfg.attach(&tryLockAndSetBB->cfg, Graph::Edge::BACK);
1599 tryLockAndSetBB->cfg.attach(&joinBB->cfg, Graph::Edge::CROSS);
1600 bld.mkFlow(OP_BRA, joinBB, CC_ALWAYS, NULL);
1601
1602 bld.remove(atom);
1603
1604 bld.setPosition(joinBB, false);
1605 bld.mkFlow(OP_JOIN, NULL, CC_ALWAYS, NULL)->fixed = 1;
1606 }
1607
1608 bool
1609 NVC0LoweringPass::handleATOM(Instruction *atom)
1610 {
1611 SVSemantic sv;
1612 Value *ptr = atom->getIndirect(0, 0), *ind = atom->getIndirect(0, 1), *base;
1613
1614 switch (atom->src(0).getFile()) {
1615 case FILE_MEMORY_LOCAL:
1616 sv = SV_LBASE;
1617 break;
1618 case FILE_MEMORY_SHARED:
1619 // For Fermi/Kepler, we have to use ld lock/st unlock to perform atomic
1620 // operations on shared memory. For Maxwell, ATOMS is enough.
1621 if (targ->getChipset() < NVISA_GK104_CHIPSET)
1622 handleSharedATOM(atom);
1623 else if (targ->getChipset() < NVISA_GM107_CHIPSET)
1624 handleSharedATOMNVE4(atom);
1625 return true;
1626 default:
1627 assert(atom->src(0).getFile() == FILE_MEMORY_BUFFER);
1628 base = loadBufInfo64(ind, atom->getSrc(0)->reg.fileIndex * 16);
1629 assert(base->reg.size == 8);
1630 if (ptr)
1631 base = bld.mkOp2v(OP_ADD, TYPE_U64, base, base, ptr);
1632 assert(base->reg.size == 8);
1633 atom->setIndirect(0, 0, base);
1634 atom->getSrc(0)->reg.file = FILE_MEMORY_GLOBAL;
1635
1636 // Harden against out-of-bounds accesses
1637 Value *offset = bld.loadImm(NULL, atom->getSrc(0)->reg.data.offset + typeSizeof(atom->sType));
1638 Value *length = loadBufLength32(ind, atom->getSrc(0)->reg.fileIndex * 16);
1639 Value *pred = new_LValue(func, FILE_PREDICATE);
1640 if (ptr)
1641 bld.mkOp2(OP_ADD, TYPE_U32, offset, offset, ptr);
1642 bld.mkCmp(OP_SET, CC_GT, TYPE_U32, pred, TYPE_U32, offset, length);
1643 atom->setPredicate(CC_NOT_P, pred);
1644 if (atom->defExists(0)) {
1645 Value *zero, *dst = atom->getDef(0);
1646 atom->setDef(0, bld.getSSA());
1647
1648 bld.setPosition(atom, true);
1649 bld.mkMov((zero = bld.getSSA()), bld.mkImm(0))
1650 ->setPredicate(CC_P, pred);
1651 bld.mkOp2(OP_UNION, TYPE_U32, dst, atom->getDef(0), zero);
1652 }
1653
1654 return true;
1655 }
1656 base =
1657 bld.mkOp1v(OP_RDSV, TYPE_U32, bld.getScratch(), bld.mkSysVal(sv, 0));
1658
1659 atom->setSrc(0, cloneShallow(func, atom->getSrc(0)));
1660 atom->getSrc(0)->reg.file = FILE_MEMORY_GLOBAL;
1661 if (ptr)
1662 base = bld.mkOp2v(OP_ADD, TYPE_U32, base, base, ptr);
1663 atom->setIndirect(0, 1, NULL);
1664 atom->setIndirect(0, 0, base);
1665
1666 return true;
1667 }
1668
1669 bool
1670 NVC0LoweringPass::handleCasExch(Instruction *cas, bool needCctl)
1671 {
1672 if (targ->getChipset() < NVISA_GM107_CHIPSET) {
1673 if (cas->src(0).getFile() == FILE_MEMORY_SHARED) {
1674 // ATOM_CAS and ATOM_EXCH are handled in handleSharedATOM().
1675 return false;
1676 }
1677 }
1678
1679 if (cas->subOp != NV50_IR_SUBOP_ATOM_CAS &&
1680 cas->subOp != NV50_IR_SUBOP_ATOM_EXCH)
1681 return false;
1682 bld.setPosition(cas, true);
1683
1684 if (needCctl) {
1685 Instruction *cctl = bld.mkOp1(OP_CCTL, TYPE_NONE, NULL, cas->getSrc(0));
1686 cctl->setIndirect(0, 0, cas->getIndirect(0, 0));
1687 cctl->fixed = 1;
1688 cctl->subOp = NV50_IR_SUBOP_CCTL_IV;
1689 if (cas->isPredicated())
1690 cctl->setPredicate(cas->cc, cas->getPredicate());
1691 }
1692
1693 if (cas->subOp == NV50_IR_SUBOP_ATOM_CAS) {
1694 // CAS is crazy. It's 2nd source is a double reg, and the 3rd source
1695 // should be set to the high part of the double reg or bad things will
1696 // happen elsewhere in the universe.
1697 // Also, it sometimes returns the new value instead of the old one
1698 // under mysterious circumstances.
1699 Value *dreg = bld.getSSA(8);
1700 bld.setPosition(cas, false);
1701 bld.mkOp2(OP_MERGE, TYPE_U64, dreg, cas->getSrc(1), cas->getSrc(2));
1702 cas->setSrc(1, dreg);
1703 cas->setSrc(2, dreg);
1704 }
1705
1706 return true;
1707 }
1708
1709 inline Value *
1710 NVC0LoweringPass::loadResInfo32(Value *ptr, uint32_t off, uint16_t base)
1711 {
1712 uint8_t b = prog->driver->io.auxCBSlot;
1713 off += base;
1714
1715 return bld.
1716 mkLoadv(TYPE_U32, bld.mkSymbol(FILE_MEMORY_CONST, b, TYPE_U32, off), ptr);
1717 }
1718
1719 inline Value *
1720 NVC0LoweringPass::loadResInfo64(Value *ptr, uint32_t off, uint16_t base)
1721 {
1722 uint8_t b = prog->driver->io.auxCBSlot;
1723 off += base;
1724
1725 if (ptr)
1726 ptr = bld.mkOp2v(OP_SHL, TYPE_U32, bld.getScratch(), ptr, bld.mkImm(4));
1727
1728 return bld.
1729 mkLoadv(TYPE_U64, bld.mkSymbol(FILE_MEMORY_CONST, b, TYPE_U64, off), ptr);
1730 }
1731
1732 inline Value *
1733 NVC0LoweringPass::loadResLength32(Value *ptr, uint32_t off, uint16_t base)
1734 {
1735 uint8_t b = prog->driver->io.auxCBSlot;
1736 off += base;
1737
1738 if (ptr)
1739 ptr = bld.mkOp2v(OP_SHL, TYPE_U32, bld.getScratch(), ptr, bld.mkImm(4));
1740
1741 return bld.
1742 mkLoadv(TYPE_U32, bld.mkSymbol(FILE_MEMORY_CONST, b, TYPE_U64, off + 8), ptr);
1743 }
1744
1745 inline Value *
1746 NVC0LoweringPass::loadBufInfo64(Value *ptr, uint32_t off)
1747 {
1748 return loadResInfo64(ptr, off, prog->driver->io.bufInfoBase);
1749 }
1750
1751 inline Value *
1752 NVC0LoweringPass::loadBufLength32(Value *ptr, uint32_t off)
1753 {
1754 return loadResLength32(ptr, off, prog->driver->io.bufInfoBase);
1755 }
1756
1757 inline Value *
1758 NVC0LoweringPass::loadUboInfo64(Value *ptr, uint32_t off)
1759 {
1760 return loadResInfo64(ptr, off, prog->driver->io.uboInfoBase);
1761 }
1762
1763 inline Value *
1764 NVC0LoweringPass::loadUboLength32(Value *ptr, uint32_t off)
1765 {
1766 return loadResLength32(ptr, off, prog->driver->io.uboInfoBase);
1767 }
1768
1769 inline Value *
1770 NVC0LoweringPass::loadMsInfo32(Value *ptr, uint32_t off)
1771 {
1772 uint8_t b = prog->driver->io.msInfoCBSlot;
1773 off += prog->driver->io.msInfoBase;
1774 return bld.
1775 mkLoadv(TYPE_U32, bld.mkSymbol(FILE_MEMORY_CONST, b, TYPE_U32, off), ptr);
1776 }
1777
1778 inline Value *
1779 NVC0LoweringPass::loadSuInfo32(Value *ptr, int slot, uint32_t off, bool bindless)
1780 {
1781 uint32_t base = slot * NVC0_SU_INFO__STRIDE;
1782
1783 if (ptr) {
1784 ptr = bld.mkOp2v(OP_ADD, TYPE_U32, bld.getSSA(), ptr, bld.mkImm(slot));
1785 if (bindless)
1786 ptr = bld.mkOp2v(OP_AND, TYPE_U32, bld.getSSA(), ptr, bld.mkImm(511));
1787 else
1788 ptr = bld.mkOp2v(OP_AND, TYPE_U32, bld.getSSA(), ptr, bld.mkImm(7));
1789 ptr = bld.mkOp2v(OP_SHL, TYPE_U32, bld.getSSA(), ptr, bld.mkImm(6));
1790 base = 0;
1791 }
1792 off += base;
1793
1794 return loadResInfo32(ptr, off, bindless ? prog->driver->io.bindlessBase :
1795 prog->driver->io.suInfoBase);
1796 }
1797
1798 Value *
1799 NVC0LoweringPass::loadMsAdjInfo32(TexInstruction::Target target, uint32_t index, int slot, Value *ind, bool bindless)
1800 {
1801 if (!bindless || targ->getChipset() < NVISA_GM107_CHIPSET)
1802 return loadSuInfo32(ind, slot, NVC0_SU_INFO_MS(index), bindless);
1803
1804 assert(bindless);
1805
1806 Value *samples = bld.getSSA();
1807 // this shouldn't be lowered because it's being inserted before the current instruction
1808 TexInstruction *tex = new_TexInstruction(func, OP_TXQ);
1809 tex->tex.target = target;
1810 tex->tex.query = TXQ_TYPE;
1811 tex->tex.mask = 0x4;
1812 tex->tex.r = 0xff;
1813 tex->tex.s = 0x1f;
1814 tex->tex.rIndirectSrc = 0;
1815 tex->setDef(0, samples);
1816 tex->setSrc(0, ind);
1817 tex->setSrc(1, bld.loadImm(NULL, 0));
1818 bld.insert(tex);
1819
1820 // doesn't work with sample counts other than 1/2/4/8 but they aren't supported
1821 switch (index) {
1822 case 0: {
1823 Value *tmp = bld.mkOp2v(OP_ADD, TYPE_U32, bld.getSSA(), samples, bld.mkImm(2));
1824 return bld.mkOp2v(OP_SHR, TYPE_U32, bld.getSSA(), tmp, bld.mkImm(2));
1825 }
1826 case 1: {
1827 Value *tmp = bld.mkCmp(OP_SET, CC_GT, TYPE_U32, bld.getSSA(), TYPE_U32, samples, bld.mkImm(2))->getDef(0);
1828 return bld.mkOp2v(OP_AND, TYPE_U32, bld.getSSA(), tmp, bld.mkImm(1));
1829 }
1830 default: {
1831 assert(false);
1832 return NULL;
1833 }
1834 }
1835 }
1836
1837 static inline uint16_t getSuClampSubOp(const TexInstruction *su, int c)
1838 {
1839 switch (su->tex.target.getEnum()) {
1840 case TEX_TARGET_BUFFER: return NV50_IR_SUBOP_SUCLAMP_PL(0, 1);
1841 case TEX_TARGET_RECT: return NV50_IR_SUBOP_SUCLAMP_SD(0, 2);
1842 case TEX_TARGET_1D: return NV50_IR_SUBOP_SUCLAMP_SD(0, 2);
1843 case TEX_TARGET_1D_ARRAY: return (c == 1) ?
1844 NV50_IR_SUBOP_SUCLAMP_PL(0, 2) :
1845 NV50_IR_SUBOP_SUCLAMP_SD(0, 2);
1846 case TEX_TARGET_2D: return NV50_IR_SUBOP_SUCLAMP_BL(0, 2);
1847 case TEX_TARGET_2D_MS: return NV50_IR_SUBOP_SUCLAMP_BL(0, 2);
1848 case TEX_TARGET_2D_ARRAY: return NV50_IR_SUBOP_SUCLAMP_SD(0, 2);
1849 case TEX_TARGET_2D_MS_ARRAY: return NV50_IR_SUBOP_SUCLAMP_SD(0, 2);
1850 case TEX_TARGET_3D: return NV50_IR_SUBOP_SUCLAMP_SD(0, 2);
1851 case TEX_TARGET_CUBE: return NV50_IR_SUBOP_SUCLAMP_SD(0, 2);
1852 case TEX_TARGET_CUBE_ARRAY: return NV50_IR_SUBOP_SUCLAMP_SD(0, 2);
1853 default:
1854 assert(0);
1855 return 0;
1856 }
1857 }
1858
1859 bool
1860 NVC0LoweringPass::handleSUQ(TexInstruction *suq)
1861 {
1862 int mask = suq->tex.mask;
1863 int dim = suq->tex.target.getDim();
1864 int arg = dim + (suq->tex.target.isArray() || suq->tex.target.isCube());
1865 Value *ind = suq->getIndirectR();
1866 int slot = suq->tex.r;
1867 int c, d;
1868
1869 for (c = 0, d = 0; c < 3; ++c, mask >>= 1) {
1870 if (c >= arg || !(mask & 1))
1871 continue;
1872
1873 int offset;
1874
1875 if (c == 1 && suq->tex.target == TEX_TARGET_1D_ARRAY) {
1876 offset = NVC0_SU_INFO_SIZE(2);
1877 } else {
1878 offset = NVC0_SU_INFO_SIZE(c);
1879 }
1880 bld.mkMov(suq->getDef(d++), loadSuInfo32(ind, slot, offset, suq->tex.bindless));
1881 if (c == 2 && suq->tex.target.isCube())
1882 bld.mkOp2(OP_DIV, TYPE_U32, suq->getDef(d - 1), suq->getDef(d - 1),
1883 bld.loadImm(NULL, 6));
1884 }
1885
1886 if (mask & 1) {
1887 if (suq->tex.target.isMS()) {
1888 Value *ms_x = loadSuInfo32(ind, slot, NVC0_SU_INFO_MS(0), suq->tex.bindless);
1889 Value *ms_y = loadSuInfo32(ind, slot, NVC0_SU_INFO_MS(1), suq->tex.bindless);
1890 Value *ms = bld.mkOp2v(OP_ADD, TYPE_U32, bld.getScratch(), ms_x, ms_y);
1891 bld.mkOp2(OP_SHL, TYPE_U32, suq->getDef(d++), bld.loadImm(NULL, 1), ms);
1892 } else {
1893 bld.mkMov(suq->getDef(d++), bld.loadImm(NULL, 1));
1894 }
1895 }
1896
1897 bld.remove(suq);
1898 return true;
1899 }
1900
1901 void
1902 NVC0LoweringPass::adjustCoordinatesMS(TexInstruction *tex)
1903 {
1904 const int arg = tex->tex.target.getArgCount();
1905 int slot = tex->tex.r;
1906
1907 if (tex->tex.target == TEX_TARGET_2D_MS)
1908 tex->tex.target = TEX_TARGET_2D;
1909 else
1910 if (tex->tex.target == TEX_TARGET_2D_MS_ARRAY)
1911 tex->tex.target = TEX_TARGET_2D_ARRAY;
1912 else
1913 return;
1914
1915 Value *x = tex->getSrc(0);
1916 Value *y = tex->getSrc(1);
1917 Value *s = tex->getSrc(arg - 1);
1918
1919 Value *tx = bld.getSSA(), *ty = bld.getSSA(), *ts = bld.getSSA();
1920 Value *ind = tex->getIndirectR();
1921
1922 Value *ms_x = loadMsAdjInfo32(tex->tex.target, 0, slot, ind, tex->tex.bindless);
1923 Value *ms_y = loadMsAdjInfo32(tex->tex.target, 1, slot, ind, tex->tex.bindless);
1924
1925 bld.mkOp2(OP_SHL, TYPE_U32, tx, x, ms_x);
1926 bld.mkOp2(OP_SHL, TYPE_U32, ty, y, ms_y);
1927
1928 s = bld.mkOp2v(OP_AND, TYPE_U32, ts, s, bld.loadImm(NULL, 0x7));
1929 s = bld.mkOp2v(OP_SHL, TYPE_U32, ts, ts, bld.mkImm(3));
1930
1931 Value *dx = loadMsInfo32(ts, 0x0);
1932 Value *dy = loadMsInfo32(ts, 0x4);
1933
1934 bld.mkOp2(OP_ADD, TYPE_U32, tx, tx, dx);
1935 bld.mkOp2(OP_ADD, TYPE_U32, ty, ty, dy);
1936
1937 tex->setSrc(0, tx);
1938 tex->setSrc(1, ty);
1939 tex->moveSources(arg, -1);
1940 }
1941
1942 // Sets 64-bit "generic address", predicate and format sources for SULD/SUST.
1943 // They're computed from the coordinates using the surface info in c[] space.
1944 void
1945 NVC0LoweringPass::processSurfaceCoordsNVE4(TexInstruction *su)
1946 {
1947 Instruction *insn;
1948 const bool atom = su->op == OP_SUREDB || su->op == OP_SUREDP;
1949 const bool raw =
1950 su->op == OP_SULDB || su->op == OP_SUSTB || su->op == OP_SUREDB;
1951 const int slot = su->tex.r;
1952 const int dim = su->tex.target.getDim();
1953 const int arg = dim + (su->tex.target.isArray() || su->tex.target.isCube());
1954 int c;
1955 Value *zero = bld.mkImm(0);
1956 Value *p1 = NULL;
1957 Value *v;
1958 Value *src[3];
1959 Value *bf, *eau, *off;
1960 Value *addr, *pred;
1961 Value *ind = su->getIndirectR();
1962
1963 off = bld.getScratch(4);
1964 bf = bld.getScratch(4);
1965 addr = bld.getSSA(8);
1966 pred = bld.getScratch(1, FILE_PREDICATE);
1967
1968 bld.setPosition(su, false);
1969
1970 adjustCoordinatesMS(su);
1971
1972 // calculate clamped coordinates
1973 for (c = 0; c < arg; ++c) {
1974 int dimc = c;
1975
1976 if (c == 1 && su->tex.target == TEX_TARGET_1D_ARRAY) {
1977 // The array index is stored in the Z component for 1D arrays.
1978 dimc = 2;
1979 }
1980
1981 src[c] = bld.getScratch();
1982 if (c == 0 && raw)
1983 v = loadSuInfo32(ind, slot, NVC0_SU_INFO_RAW_X, su->tex.bindless);
1984 else
1985 v = loadSuInfo32(ind, slot, NVC0_SU_INFO_DIM(dimc), su->tex.bindless);
1986 bld.mkOp3(OP_SUCLAMP, TYPE_S32, src[c], su->getSrc(c), v, zero)
1987 ->subOp = getSuClampSubOp(su, dimc);
1988 }
1989 for (; c < 3; ++c)
1990 src[c] = zero;
1991
1992 // set predicate output
1993 if (su->tex.target == TEX_TARGET_BUFFER) {
1994 src[0]->getInsn()->setFlagsDef(1, pred);
1995 } else
1996 if (su->tex.target.isArray() || su->tex.target.isCube()) {
1997 p1 = bld.getSSA(1, FILE_PREDICATE);
1998 src[dim]->getInsn()->setFlagsDef(1, p1);
1999 }
2000
2001 // calculate pixel offset
2002 if (dim == 1) {
2003 if (su->tex.target != TEX_TARGET_BUFFER)
2004 bld.mkOp2(OP_AND, TYPE_U32, off, src[0], bld.loadImm(NULL, 0xffff));
2005 } else
2006 if (dim == 3) {
2007 v = loadSuInfo32(ind, slot, NVC0_SU_INFO_UNK1C, su->tex.bindless);
2008 bld.mkOp3(OP_MADSP, TYPE_U32, off, src[2], v, src[1])
2009 ->subOp = NV50_IR_SUBOP_MADSP(4,2,8); // u16l u16l u16l
2010
2011 v = loadSuInfo32(ind, slot, NVC0_SU_INFO_PITCH, su->tex.bindless);
2012 bld.mkOp3(OP_MADSP, TYPE_U32, off, off, v, src[0])
2013 ->subOp = NV50_IR_SUBOP_MADSP(0,2,8); // u32 u16l u16l
2014 } else {
2015 assert(dim == 2);
2016 v = loadSuInfo32(ind, slot, NVC0_SU_INFO_PITCH, su->tex.bindless);
2017 bld.mkOp3(OP_MADSP, TYPE_U32, off, src[1], v, src[0])
2018 ->subOp = (su->tex.target.isArray() || su->tex.target.isCube()) ?
2019 NV50_IR_SUBOP_MADSP_SD : NV50_IR_SUBOP_MADSP(4,2,8); // u16l u16l u16l
2020 }
2021
2022 // calculate effective address part 1
2023 if (su->tex.target == TEX_TARGET_BUFFER) {
2024 if (raw) {
2025 bf = src[0];
2026 } else {
2027 v = loadSuInfo32(ind, slot, NVC0_SU_INFO_FMT, su->tex.bindless);
2028 bld.mkOp3(OP_VSHL, TYPE_U32, bf, src[0], v, zero)
2029 ->subOp = NV50_IR_SUBOP_V1(7,6,8|2);
2030 }
2031 } else {
2032 Value *y = src[1];
2033 Value *z = src[2];
2034 uint16_t subOp = 0;
2035
2036 switch (dim) {
2037 case 1:
2038 y = zero;
2039 z = zero;
2040 break;
2041 case 2:
2042 z = off;
2043 if (!su->tex.target.isArray() && !su->tex.target.isCube()) {
2044 z = loadSuInfo32(ind, slot, NVC0_SU_INFO_UNK1C, su->tex.bindless);
2045 subOp = NV50_IR_SUBOP_SUBFM_3D;
2046 }
2047 break;
2048 default:
2049 subOp = NV50_IR_SUBOP_SUBFM_3D;
2050 assert(dim == 3);
2051 break;
2052 }
2053 insn = bld.mkOp3(OP_SUBFM, TYPE_U32, bf, src[0], y, z);
2054 insn->subOp = subOp;
2055 insn->setFlagsDef(1, pred);
2056 }
2057
2058 // part 2
2059 v = loadSuInfo32(ind, slot, NVC0_SU_INFO_ADDR, su->tex.bindless);
2060
2061 if (su->tex.target == TEX_TARGET_BUFFER) {
2062 eau = v;
2063 } else {
2064 eau = bld.mkOp3v(OP_SUEAU, TYPE_U32, bld.getScratch(4), off, bf, v);
2065 }
2066 // add array layer offset
2067 if (su->tex.target.isArray() || su->tex.target.isCube()) {
2068 v = loadSuInfo32(ind, slot, NVC0_SU_INFO_ARRAY, su->tex.bindless);
2069 if (dim == 1)
2070 bld.mkOp3(OP_MADSP, TYPE_U32, eau, src[1], v, eau)
2071 ->subOp = NV50_IR_SUBOP_MADSP(4,0,0); // u16 u24 u32
2072 else
2073 bld.mkOp3(OP_MADSP, TYPE_U32, eau, v, src[2], eau)
2074 ->subOp = NV50_IR_SUBOP_MADSP(0,0,0); // u32 u24 u32
2075 // combine predicates
2076 assert(p1);
2077 bld.mkOp2(OP_OR, TYPE_U8, pred, pred, p1);
2078 }
2079
2080 if (atom) {
2081 Value *lo = bf;
2082 if (su->tex.target == TEX_TARGET_BUFFER) {
2083 lo = zero;
2084 bld.mkMov(off, bf);
2085 }
2086 // bf == g[] address & 0xff
2087 // eau == g[] address >> 8
2088 bld.mkOp3(OP_PERMT, TYPE_U32, bf, lo, bld.loadImm(NULL, 0x6540), eau);
2089 bld.mkOp3(OP_PERMT, TYPE_U32, eau, zero, bld.loadImm(NULL, 0x0007), eau);
2090 } else
2091 if (su->op == OP_SULDP && su->tex.target == TEX_TARGET_BUFFER) {
2092 // Convert from u32 to u8 address format, which is what the library code
2093 // doing SULDP currently uses.
2094 // XXX: can SUEAU do this ?
2095 // XXX: does it matter that we don't mask high bytes in bf ?
2096 // Grrr.
2097 bld.mkOp2(OP_SHR, TYPE_U32, off, bf, bld.mkImm(8));
2098 bld.mkOp2(OP_ADD, TYPE_U32, eau, eau, off);
2099 }
2100
2101 bld.mkOp2(OP_MERGE, TYPE_U64, addr, bf, eau);
2102
2103 if (atom && su->tex.target == TEX_TARGET_BUFFER)
2104 bld.mkOp2(OP_ADD, TYPE_U64, addr, addr, off);
2105
2106 // let's just set it 0 for raw access and hope it works
2107 v = raw ?
2108 bld.mkImm(0) : loadSuInfo32(ind, slot, NVC0_SU_INFO_FMT, su->tex.bindless);
2109
2110 // get rid of old coordinate sources, make space for fmt info and predicate
2111 su->moveSources(arg, 3 - arg);
2112 // set 64 bit address and 32-bit format sources
2113 su->setSrc(0, addr);
2114 su->setSrc(1, v);
2115 su->setSrc(2, pred);
2116 su->setIndirectR(NULL);
2117
2118 // prevent read fault when the image is not actually bound
2119 CmpInstruction *pred1 =
2120 bld.mkCmp(OP_SET, CC_EQ, TYPE_U32, bld.getSSA(1, FILE_PREDICATE),
2121 TYPE_U32, bld.mkImm(0),
2122 loadSuInfo32(ind, slot, NVC0_SU_INFO_ADDR, su->tex.bindless));
2123
2124 if (su->op != OP_SUSTP && su->tex.format) {
2125 const TexInstruction::ImgFormatDesc *format = su->tex.format;
2126 int blockwidth = format->bits[0] + format->bits[1] +
2127 format->bits[2] + format->bits[3];
2128
2129 // make sure that the format doesn't mismatch
2130 assert(format->components != 0);
2131 bld.mkCmp(OP_SET_OR, CC_NE, TYPE_U32, pred1->getDef(0),
2132 TYPE_U32, bld.loadImm(NULL, blockwidth / 8),
2133 loadSuInfo32(ind, slot, NVC0_SU_INFO_BSIZE, su->tex.bindless),
2134 pred1->getDef(0));
2135 }
2136 su->setPredicate(CC_NOT_P, pred1->getDef(0));
2137
2138 // TODO: initialize def values to 0 when the surface operation is not
2139 // performed (not needed for stores). Also, fix the "address bounds test"
2140 // subtests from arb_shader_image_load_store-invalid for buffers, because it
2141 // seems like that the predicate is not correctly set by suclamp.
2142 }
2143
2144 static DataType
2145 getSrcType(const TexInstruction::ImgFormatDesc *t, int c)
2146 {
2147 switch (t->type) {
2148 case FLOAT: return t->bits[c] == 16 ? TYPE_F16 : TYPE_F32;
2149 case UNORM: return t->bits[c] == 8 ? TYPE_U8 : TYPE_U16;
2150 case SNORM: return t->bits[c] == 8 ? TYPE_S8 : TYPE_S16;
2151 case UINT:
2152 return (t->bits[c] == 8 ? TYPE_U8 :
2153 (t->bits[c] == 16 ? TYPE_U16 : TYPE_U32));
2154 case SINT:
2155 return (t->bits[c] == 8 ? TYPE_S8 :
2156 (t->bits[c] == 16 ? TYPE_S16 : TYPE_S32));
2157 }
2158 return TYPE_NONE;
2159 }
2160
2161 static DataType
2162 getDestType(const ImgType type) {
2163 switch (type) {
2164 case FLOAT:
2165 case UNORM:
2166 case SNORM:
2167 return TYPE_F32;
2168 case UINT:
2169 return TYPE_U32;
2170 case SINT:
2171 return TYPE_S32;
2172 default:
2173 assert(!"Impossible type");
2174 return TYPE_NONE;
2175 }
2176 }
2177
2178 void
2179 NVC0LoweringPass::convertSurfaceFormat(TexInstruction *su)
2180 {
2181 const TexInstruction::ImgFormatDesc *format = su->tex.format;
2182 int width = format->bits[0] + format->bits[1] +
2183 format->bits[2] + format->bits[3];
2184 Value *untypedDst[4] = {};
2185 Value *typedDst[4] = {};
2186
2187 // We must convert this to a generic load.
2188 su->op = OP_SULDB;
2189
2190 su->dType = typeOfSize(width / 8);
2191 su->sType = TYPE_U8;
2192
2193 for (int i = 0; i < width / 32; i++)
2194 untypedDst[i] = bld.getSSA();
2195 if (width < 32)
2196 untypedDst[0] = bld.getSSA();
2197
2198 for (int i = 0; i < 4; i++) {
2199 typedDst[i] = su->getDef(i);
2200 }
2201
2202 // Set the untyped dsts as the su's destinations
2203 for (int i = 0; i < 4; i++)
2204 su->setDef(i, untypedDst[i]);
2205
2206 bld.setPosition(su, true);
2207
2208 // Unpack each component into the typed dsts
2209 int bits = 0;
2210 for (int i = 0; i < 4; bits += format->bits[i], i++) {
2211 if (!typedDst[i])
2212 continue;
2213 if (i >= format->components) {
2214 if (format->type == FLOAT ||
2215 format->type == UNORM ||
2216 format->type == SNORM)
2217 bld.loadImm(typedDst[i], i == 3 ? 1.0f : 0.0f);
2218 else
2219 bld.loadImm(typedDst[i], i == 3 ? 1 : 0);
2220 continue;
2221 }
2222
2223 // Get just that component's data into the relevant place
2224 if (format->bits[i] == 32)
2225 bld.mkMov(typedDst[i], untypedDst[i]);
2226 else if (format->bits[i] == 16)
2227 bld.mkCvt(OP_CVT, getDestType(format->type), typedDst[i],
2228 getSrcType(format, i), untypedDst[i / 2])
2229 ->subOp = (i & 1) << (format->type == FLOAT ? 0 : 1);
2230 else if (format->bits[i] == 8)
2231 bld.mkCvt(OP_CVT, getDestType(format->type), typedDst[i],
2232 getSrcType(format, i), untypedDst[0])->subOp = i;
2233 else {
2234 bld.mkOp2(OP_EXTBF, TYPE_U32, typedDst[i], untypedDst[bits / 32],
2235 bld.mkImm((bits % 32) | (format->bits[i] << 8)));
2236 if (format->type == UNORM || format->type == SNORM)
2237 bld.mkCvt(OP_CVT, TYPE_F32, typedDst[i], getSrcType(format, i), typedDst[i]);
2238 }
2239
2240 // Normalize / convert as necessary
2241 if (format->type == UNORM)
2242 bld.mkOp2(OP_MUL, TYPE_F32, typedDst[i], typedDst[i], bld.loadImm(NULL, 1.0f / ((1 << format->bits[i]) - 1)));
2243 else if (format->type == SNORM)
2244 bld.mkOp2(OP_MUL, TYPE_F32, typedDst[i], typedDst[i], bld.loadImm(NULL, 1.0f / ((1 << (format->bits[i] - 1)) - 1)));
2245 else if (format->type == FLOAT && format->bits[i] < 16) {
2246 bld.mkOp2(OP_SHL, TYPE_U32, typedDst[i], typedDst[i], bld.loadImm(NULL, 15 - format->bits[i]));
2247 bld.mkCvt(OP_CVT, TYPE_F32, typedDst[i], TYPE_F16, typedDst[i]);
2248 }
2249 }
2250
2251 if (format->bgra) {
2252 std::swap(typedDst[0], typedDst[2]);
2253 }
2254 }
2255
2256 void
2257 NVC0LoweringPass::insertOOBSurfaceOpResult(TexInstruction *su)
2258 {
2259 if (!su->getPredicate())
2260 return;
2261
2262 bld.setPosition(su, true);
2263
2264 for (unsigned i = 0; su->defExists(i); ++i) {
2265 ValueDef &def = su->def(i);
2266
2267 Instruction *mov = bld.mkMov(bld.getSSA(), bld.loadImm(NULL, 0));
2268 assert(su->cc == CC_NOT_P);
2269 mov->setPredicate(CC_P, su->getPredicate());
2270 Instruction *uni = bld.mkOp2(OP_UNION, TYPE_U32, bld.getSSA(), NULL, mov->getDef(0));
2271
2272 def.replace(uni->getDef(0), false);
2273 uni->setSrc(0, def.get());
2274 }
2275 }
2276
2277 void
2278 NVC0LoweringPass::handleSurfaceOpNVE4(TexInstruction *su)
2279 {
2280 processSurfaceCoordsNVE4(su);
2281
2282 if (su->op == OP_SULDP) {
2283 convertSurfaceFormat(su);
2284 insertOOBSurfaceOpResult(su);
2285 }
2286
2287 if (su->op == OP_SUREDB || su->op == OP_SUREDP) {
2288 assert(su->getPredicate());
2289 Value *pred =
2290 bld.mkOp2v(OP_OR, TYPE_U8, bld.getScratch(1, FILE_PREDICATE),
2291 su->getPredicate(), su->getSrc(2));
2292
2293 Instruction *red = bld.mkOp(OP_ATOM, su->dType, bld.getSSA());
2294 red->subOp = su->subOp;
2295 red->setSrc(0, bld.mkSymbol(FILE_MEMORY_GLOBAL, 0, TYPE_U32, 0));
2296 red->setSrc(1, su->getSrc(3));
2297 if (su->subOp == NV50_IR_SUBOP_ATOM_CAS)
2298 red->setSrc(2, su->getSrc(4));
2299 red->setIndirect(0, 0, su->getSrc(0));
2300
2301 // make sure to initialize dst value when the atomic operation is not
2302 // performed
2303 Instruction *mov = bld.mkMov(bld.getSSA(), bld.loadImm(NULL, 0));
2304
2305 assert(su->cc == CC_NOT_P);
2306 red->setPredicate(su->cc, pred);
2307 mov->setPredicate(CC_P, pred);
2308
2309 bld.mkOp2(OP_UNION, TYPE_U32, su->getDef(0),
2310 red->getDef(0), mov->getDef(0));
2311
2312 delete_Instruction(bld.getProgram(), su);
2313 handleCasExch(red, true);
2314 }
2315
2316 if (su->op == OP_SUSTB || su->op == OP_SUSTP)
2317 su->sType = (su->tex.target == TEX_TARGET_BUFFER) ? TYPE_U32 : TYPE_U8;
2318 }
2319
2320 void
2321 NVC0LoweringPass::processSurfaceCoordsNVC0(TexInstruction *su)
2322 {
2323 const int slot = su->tex.r;
2324 const int dim = su->tex.target.getDim();
2325 const int arg = dim + (su->tex.target.isArray() || su->tex.target.isCube());
2326 int c;
2327 Value *zero = bld.mkImm(0);
2328 Value *src[3];
2329 Value *v;
2330 Value *ind = su->getIndirectR();
2331
2332 bld.setPosition(su, false);
2333
2334 adjustCoordinatesMS(su);
2335
2336 if (ind) {
2337 Value *ptr;
2338 ptr = bld.mkOp2v(OP_ADD, TYPE_U32, bld.getSSA(), ind, bld.mkImm(su->tex.r));
2339 ptr = bld.mkOp2v(OP_AND, TYPE_U32, bld.getSSA(), ptr, bld.mkImm(7));
2340 su->setIndirectR(ptr);
2341 }
2342
2343 // get surface coordinates
2344 for (c = 0; c < arg; ++c)
2345 src[c] = su->getSrc(c);
2346 for (; c < 3; ++c)
2347 src[c] = zero;
2348
2349 // calculate pixel offset
2350 if (su->op == OP_SULDP || su->op == OP_SUREDP) {
2351 v = loadSuInfo32(ind, slot, NVC0_SU_INFO_BSIZE, su->tex.bindless);
2352 su->setSrc(0, bld.mkOp2v(OP_MUL, TYPE_U32, bld.getSSA(), src[0], v));
2353 }
2354
2355 // add array layer offset
2356 if (su->tex.target.isArray() || su->tex.target.isCube()) {
2357 v = loadSuInfo32(ind, slot, NVC0_SU_INFO_ARRAY, su->tex.bindless);
2358 assert(dim > 1);
2359 su->setSrc(2, bld.mkOp2v(OP_MUL, TYPE_U32, bld.getSSA(), src[2], v));
2360 }
2361
2362 // prevent read fault when the image is not actually bound
2363 CmpInstruction *pred =
2364 bld.mkCmp(OP_SET, CC_EQ, TYPE_U32, bld.getSSA(1, FILE_PREDICATE),
2365 TYPE_U32, bld.mkImm(0),
2366 loadSuInfo32(ind, slot, NVC0_SU_INFO_ADDR, su->tex.bindless));
2367 if (su->op != OP_SUSTP && su->tex.format) {
2368 const TexInstruction::ImgFormatDesc *format = su->tex.format;
2369 int blockwidth = format->bits[0] + format->bits[1] +
2370 format->bits[2] + format->bits[3];
2371
2372 assert(format->components != 0);
2373 // make sure that the format doesn't mismatch when it's not FMT_NONE
2374 bld.mkCmp(OP_SET_OR, CC_NE, TYPE_U32, pred->getDef(0),
2375 TYPE_U32, bld.loadImm(NULL, blockwidth / 8),
2376 loadSuInfo32(ind, slot, NVC0_SU_INFO_BSIZE, su->tex.bindless),
2377 pred->getDef(0));
2378 }
2379 su->setPredicate(CC_NOT_P, pred->getDef(0));
2380 }
2381
2382 void
2383 NVC0LoweringPass::handleSurfaceOpNVC0(TexInstruction *su)
2384 {
2385 if (su->tex.target == TEX_TARGET_1D_ARRAY) {
2386 /* As 1d arrays also need 3 coordinates, switching to TEX_TARGET_2D_ARRAY
2387 * will simplify the lowering pass and the texture constraints. */
2388 su->moveSources(1, 1);
2389 su->setSrc(1, bld.loadImm(NULL, 0));
2390 su->tex.target = TEX_TARGET_2D_ARRAY;
2391 }
2392
2393 processSurfaceCoordsNVC0(su);
2394
2395 if (su->op == OP_SULDP) {
2396 convertSurfaceFormat(su);
2397 insertOOBSurfaceOpResult(su);
2398 }
2399
2400 if (su->op == OP_SUREDB || su->op == OP_SUREDP) {
2401 const int dim = su->tex.target.getDim();
2402 const int arg = dim + (su->tex.target.isArray() || su->tex.target.isCube());
2403 LValue *addr = bld.getSSA(8);
2404 Value *def = su->getDef(0);
2405
2406 su->op = OP_SULEA;
2407
2408 // Set the destination to the address
2409 su->dType = TYPE_U64;
2410 su->setDef(0, addr);
2411 su->setDef(1, su->getPredicate());
2412
2413 bld.setPosition(su, true);
2414
2415 // Perform the atomic op
2416 Instruction *red = bld.mkOp(OP_ATOM, su->sType, bld.getSSA());
2417 red->subOp = su->subOp;
2418 red->setSrc(0, bld.mkSymbol(FILE_MEMORY_GLOBAL, 0, su->sType, 0));
2419 red->setSrc(1, su->getSrc(arg));
2420 if (red->subOp == NV50_IR_SUBOP_ATOM_CAS)
2421 red->setSrc(2, su->getSrc(arg + 1));
2422 red->setIndirect(0, 0, addr);
2423
2424 // make sure to initialize dst value when the atomic operation is not
2425 // performed
2426 Instruction *mov = bld.mkMov(bld.getSSA(), bld.loadImm(NULL, 0));
2427
2428 assert(su->cc == CC_NOT_P);
2429 red->setPredicate(su->cc, su->getPredicate());
2430 mov->setPredicate(CC_P, su->getPredicate());
2431
2432 bld.mkOp2(OP_UNION, TYPE_U32, def, red->getDef(0), mov->getDef(0));
2433
2434 handleCasExch(red, false);
2435 }
2436 }
2437
2438 void
2439 NVC0LoweringPass::processSurfaceCoordsGM107(TexInstruction *su)
2440 {
2441 const int slot = su->tex.r;
2442 const int dim = su->tex.target.getDim();
2443 const int arg = dim + (su->tex.target.isArray() || su->tex.target.isCube());
2444 Value *ind = su->getIndirectR();
2445 Value *handle;
2446 int pos = 0;
2447
2448 bld.setPosition(su, false);
2449
2450 adjustCoordinatesMS(su);
2451
2452 // add texture handle
2453 switch (su->op) {
2454 case OP_SUSTP:
2455 pos = 4;
2456 break;
2457 case OP_SUREDP:
2458 pos = (su->subOp == NV50_IR_SUBOP_ATOM_CAS) ? 2 : 1;
2459 break;
2460 default:
2461 assert(pos == 0);
2462 break;
2463 }
2464 if (su->tex.bindless)
2465 handle = ind;
2466 else
2467 handle = loadTexHandle(ind, slot + 32);
2468 su->setSrc(arg + pos, handle);
2469
2470 // The address check doesn't make sense here. The format check could make
2471 // sense but it's a bit of a pain.
2472 if (su->tex.bindless)
2473 return;
2474
2475 // prevent read fault when the image is not actually bound
2476 CmpInstruction *pred =
2477 bld.mkCmp(OP_SET, CC_EQ, TYPE_U32, bld.getSSA(1, FILE_PREDICATE),
2478 TYPE_U32, bld.mkImm(0),
2479 loadSuInfo32(ind, slot, NVC0_SU_INFO_ADDR, su->tex.bindless));
2480 if (su->op != OP_SUSTP && su->tex.format) {
2481 const TexInstruction::ImgFormatDesc *format = su->tex.format;
2482 int blockwidth = format->bits[0] + format->bits[1] +
2483 format->bits[2] + format->bits[3];
2484
2485 assert(format->components != 0);
2486 // make sure that the format doesn't mismatch when it's not FMT_NONE
2487 bld.mkCmp(OP_SET_OR, CC_NE, TYPE_U32, pred->getDef(0),
2488 TYPE_U32, bld.loadImm(NULL, blockwidth / 8),
2489 loadSuInfo32(ind, slot, NVC0_SU_INFO_BSIZE, su->tex.bindless),
2490 pred->getDef(0));
2491 }
2492 su->setPredicate(CC_NOT_P, pred->getDef(0));
2493 }
2494
2495 void
2496 NVC0LoweringPass::handleSurfaceOpGM107(TexInstruction *su)
2497 {
2498 processSurfaceCoordsGM107(su);
2499
2500 if (su->op == OP_SULDP) {
2501 convertSurfaceFormat(su);
2502 insertOOBSurfaceOpResult(su);
2503 }
2504
2505 if (su->op == OP_SUREDP) {
2506 Value *def = su->getDef(0);
2507
2508 su->op = OP_SUREDB;
2509
2510 // There may not be a predicate in the bindless case.
2511 if (su->getPredicate()) {
2512 su->setDef(0, bld.getSSA());
2513
2514 bld.setPosition(su, true);
2515
2516 // make sure to initialize dst value when the atomic operation is not
2517 // performed
2518 Instruction *mov = bld.mkMov(bld.getSSA(), bld.loadImm(NULL, 0));
2519
2520 assert(su->cc == CC_NOT_P);
2521 mov->setPredicate(CC_P, su->getPredicate());
2522
2523 bld.mkOp2(OP_UNION, TYPE_U32, def, su->getDef(0), mov->getDef(0));
2524 }
2525 }
2526 }
2527
2528 bool
2529 NVC0LoweringPass::handleWRSV(Instruction *i)
2530 {
2531 Instruction *st;
2532 Symbol *sym;
2533 uint32_t addr;
2534
2535 // must replace, $sreg are not writeable
2536 addr = targ->getSVAddress(FILE_SHADER_OUTPUT, i->getSrc(0)->asSym());
2537 if (addr >= 0x400)
2538 return false;
2539 sym = bld.mkSymbol(FILE_SHADER_OUTPUT, 0, i->sType, addr);
2540
2541 st = bld.mkStore(OP_EXPORT, i->dType, sym, i->getIndirect(0, 0),
2542 i->getSrc(1));
2543 st->perPatch = i->perPatch;
2544
2545 bld.getBB()->remove(i);
2546 return true;
2547 }
2548
2549 void
2550 NVC0LoweringPass::handleLDST(Instruction *i)
2551 {
2552 if (i->src(0).getFile() == FILE_SHADER_INPUT) {
2553 if (prog->getType() == Program::TYPE_COMPUTE) {
2554 i->getSrc(0)->reg.file = FILE_MEMORY_CONST;
2555 i->getSrc(0)->reg.fileIndex = 0;
2556 } else
2557 if (prog->getType() == Program::TYPE_GEOMETRY &&
2558 i->src(0).isIndirect(0)) {
2559 // XXX: this assumes vec4 units
2560 Value *ptr = bld.mkOp2v(OP_SHL, TYPE_U32, bld.getSSA(),
2561 i->getIndirect(0, 0), bld.mkImm(4));
2562 i->setIndirect(0, 0, ptr);
2563 i->op = OP_VFETCH;
2564 } else {
2565 i->op = OP_VFETCH;
2566 assert(prog->getType() != Program::TYPE_FRAGMENT); // INTERP
2567 }
2568 } else if (i->src(0).getFile() == FILE_MEMORY_CONST) {
2569 int8_t fileIndex = i->getSrc(0)->reg.fileIndex - 1;
2570 Value *ind = i->getIndirect(0, 1);
2571
2572 if (targ->getChipset() >= NVISA_GK104_CHIPSET &&
2573 prog->getType() == Program::TYPE_COMPUTE &&
2574 (fileIndex >= 6 || ind)) {
2575 // The launch descriptor only allows to set up 8 CBs, but OpenGL
2576 // requires at least 12 UBOs. To bypass this limitation, for constant
2577 // buffers 7+, we store the addrs into the driver constbuf and we
2578 // directly load from the global memory.
2579 if (ind) {
2580 // Clamp the UBO index when an indirect access is used to avoid
2581 // loading information from the wrong place in the driver cb.
2582 // TODO - synchronize the max with the driver.
2583 ind = bld.mkOp2v(OP_MIN, TYPE_U32, bld.getSSA(),
2584 bld.mkOp2v(OP_ADD, TYPE_U32, bld.getSSA(),
2585 ind, bld.loadImm(NULL, fileIndex)),
2586 bld.loadImm(NULL, 13));
2587 fileIndex = 0;
2588 }
2589
2590 Value *offset = bld.loadImm(NULL, i->getSrc(0)->reg.data.offset + typeSizeof(i->sType));
2591 Value *ptr = loadUboInfo64(ind, fileIndex * 16);
2592 Value *length = loadUboLength32(ind, fileIndex * 16);
2593 Value *pred = new_LValue(func, FILE_PREDICATE);
2594 if (i->src(0).isIndirect(0)) {
2595 bld.mkOp2(OP_ADD, TYPE_U64, ptr, ptr, i->getIndirect(0, 0));
2596 bld.mkOp2(OP_ADD, TYPE_U32, offset, offset, i->getIndirect(0, 0));
2597 }
2598 i->getSrc(0)->reg.file = FILE_MEMORY_GLOBAL;
2599 i->setIndirect(0, 1, NULL);
2600 i->setIndirect(0, 0, ptr);
2601 bld.mkCmp(OP_SET, CC_GT, TYPE_U32, pred, TYPE_U32, offset, length);
2602 i->setPredicate(CC_NOT_P, pred);
2603 Value *zero, *dst = i->getDef(0);
2604 i->setDef(0, bld.getSSA());
2605
2606 bld.setPosition(i, true);
2607 bld.mkMov((zero = bld.getSSA()), bld.mkImm(0))
2608 ->setPredicate(CC_P, pred);
2609 bld.mkOp2(OP_UNION, TYPE_U32, dst, i->getDef(0), zero);
2610 } else if (i->src(0).isIndirect(1)) {
2611 Value *ptr;
2612 if (i->src(0).isIndirect(0))
2613 ptr = bld.mkOp3v(OP_INSBF, TYPE_U32, bld.getSSA(),
2614 i->getIndirect(0, 1), bld.mkImm(0x1010),
2615 i->getIndirect(0, 0));
2616 else
2617 ptr = bld.mkOp2v(OP_SHL, TYPE_U32, bld.getSSA(),
2618 i->getIndirect(0, 1), bld.mkImm(16));
2619 i->setIndirect(0, 1, NULL);
2620 i->setIndirect(0, 0, ptr);
2621 i->subOp = NV50_IR_SUBOP_LDC_IS;
2622 }
2623 } else if (i->src(0).getFile() == FILE_SHADER_OUTPUT) {
2624 assert(prog->getType() == Program::TYPE_TESSELLATION_CONTROL);
2625 i->op = OP_VFETCH;
2626 } else if (i->src(0).getFile() == FILE_MEMORY_BUFFER) {
2627 Value *ind = i->getIndirect(0, 1);
2628 Value *ptr = loadBufInfo64(ind, i->getSrc(0)->reg.fileIndex * 16);
2629 // XXX come up with a way not to do this for EVERY little access but
2630 // rather to batch these up somehow. Unfortunately we've lost the
2631 // information about the field width by the time we get here.
2632 Value *offset = bld.loadImm(NULL, i->getSrc(0)->reg.data.offset + typeSizeof(i->sType));
2633 Value *length = loadBufLength32(ind, i->getSrc(0)->reg.fileIndex * 16);
2634 Value *pred = new_LValue(func, FILE_PREDICATE);
2635 if (i->src(0).isIndirect(0)) {
2636 bld.mkOp2(OP_ADD, TYPE_U64, ptr, ptr, i->getIndirect(0, 0));
2637 bld.mkOp2(OP_ADD, TYPE_U32, offset, offset, i->getIndirect(0, 0));
2638 }
2639 i->setIndirect(0, 1, NULL);
2640 i->setIndirect(0, 0, ptr);
2641 i->getSrc(0)->reg.file = FILE_MEMORY_GLOBAL;
2642 bld.mkCmp(OP_SET, CC_GT, TYPE_U32, pred, TYPE_U32, offset, length);
2643 i->setPredicate(CC_NOT_P, pred);
2644 if (i->defExists(0)) {
2645 Value *zero, *dst = i->getDef(0);
2646 i->setDef(0, bld.getSSA());
2647
2648 bld.setPosition(i, true);
2649 bld.mkMov((zero = bld.getSSA()), bld.mkImm(0))
2650 ->setPredicate(CC_P, pred);
2651 bld.mkOp2(OP_UNION, TYPE_U32, dst, i->getDef(0), zero);
2652 }
2653 }
2654 }
2655
2656 void
2657 NVC0LoweringPass::readTessCoord(LValue *dst, int c)
2658 {
2659 Value *laneid = bld.getSSA();
2660 Value *x, *y;
2661
2662 bld.mkOp1(OP_RDSV, TYPE_U32, laneid, bld.mkSysVal(SV_LANEID, 0));
2663
2664 if (c == 0) {
2665 x = dst;
2666 y = NULL;
2667 } else
2668 if (c == 1) {
2669 x = NULL;
2670 y = dst;
2671 } else {
2672 assert(c == 2);
2673 if (prog->driver->prop.tp.domain != PIPE_PRIM_TRIANGLES) {
2674 bld.mkMov(dst, bld.loadImm(NULL, 0));
2675 return;
2676 }
2677 x = bld.getSSA();
2678 y = bld.getSSA();
2679 }
2680 if (x)
2681 bld.mkFetch(x, TYPE_F32, FILE_SHADER_OUTPUT, 0x2f0, NULL, laneid);
2682 if (y)
2683 bld.mkFetch(y, TYPE_F32, FILE_SHADER_OUTPUT, 0x2f4, NULL, laneid);
2684
2685 if (c == 2) {
2686 bld.mkOp2(OP_ADD, TYPE_F32, dst, x, y);
2687 bld.mkOp2(OP_SUB, TYPE_F32, dst, bld.loadImm(NULL, 1.0f), dst);
2688 }
2689 }
2690
2691 bool
2692 NVC0LoweringPass::handleRDSV(Instruction *i)
2693 {
2694 Symbol *sym = i->getSrc(0)->asSym();
2695 const SVSemantic sv = sym->reg.data.sv.sv;
2696 Value *vtx = NULL;
2697 Instruction *ld;
2698 uint32_t addr = targ->getSVAddress(FILE_SHADER_INPUT, sym);
2699
2700 if (addr >= 0x400) {
2701 // mov $sreg
2702 if (sym->reg.data.sv.index == 3) {
2703 // TGSI backend may use 4th component of TID,NTID,CTAID,NCTAID
2704 i->op = OP_MOV;
2705 i->setSrc(0, bld.mkImm((sv == SV_NTID || sv == SV_NCTAID) ? 1 : 0));
2706 } else
2707 if (sv == SV_TID) {
2708 // Help CSE combine TID fetches
2709 Value *tid = bld.mkOp1v(OP_RDSV, TYPE_U32, bld.getScratch(),
2710 bld.mkSysVal(SV_COMBINED_TID, 0));
2711 i->op = OP_EXTBF;
2712 i->setSrc(0, tid);
2713 switch (sym->reg.data.sv.index) {
2714 case 0: i->setSrc(1, bld.mkImm(0x1000)); break;
2715 case 1: i->setSrc(1, bld.mkImm(0x0a10)); break;
2716 case 2: i->setSrc(1, bld.mkImm(0x061a)); break;
2717 }
2718 }
2719 if (sv == SV_VERTEX_COUNT) {
2720 bld.setPosition(i, true);
2721 bld.mkOp2(OP_EXTBF, TYPE_U32, i->getDef(0), i->getDef(0), bld.mkImm(0x808));
2722 }
2723 return true;
2724 }
2725
2726 switch (sv) {
2727 case SV_POSITION:
2728 assert(prog->getType() == Program::TYPE_FRAGMENT);
2729 if (i->srcExists(1)) {
2730 // Pass offset through to the interpolation logic
2731 ld = bld.mkInterp(NV50_IR_INTERP_LINEAR | NV50_IR_INTERP_OFFSET,
2732 i->getDef(0), addr, NULL);
2733 ld->setSrc(1, i->getSrc(1));
2734 } else {
2735 bld.mkInterp(NV50_IR_INTERP_LINEAR, i->getDef(0), addr, NULL);
2736 }
2737 break;
2738 case SV_FACE:
2739 {
2740 Value *face = i->getDef(0);
2741 bld.mkInterp(NV50_IR_INTERP_FLAT, face, addr, NULL);
2742 if (i->dType == TYPE_F32) {
2743 bld.mkOp2(OP_OR, TYPE_U32, face, face, bld.mkImm(0x00000001));
2744 bld.mkOp1(OP_NEG, TYPE_S32, face, face);
2745 bld.mkCvt(OP_CVT, TYPE_F32, face, TYPE_S32, face);
2746 }
2747 }
2748 break;
2749 case SV_TESS_COORD:
2750 assert(prog->getType() == Program::TYPE_TESSELLATION_EVAL);
2751 readTessCoord(i->getDef(0)->asLValue(), i->getSrc(0)->reg.data.sv.index);
2752 break;
2753 case SV_NTID:
2754 case SV_NCTAID:
2755 case SV_GRIDID:
2756 assert(targ->getChipset() >= NVISA_GK104_CHIPSET); // mov $sreg otherwise
2757 if (sym->reg.data.sv.index == 3) {
2758 i->op = OP_MOV;
2759 i->setSrc(0, bld.mkImm(sv == SV_GRIDID ? 0 : 1));
2760 return true;
2761 }
2762 // Fallthrough
2763 case SV_WORK_DIM:
2764 addr += prog->driver->prop.cp.gridInfoBase;
2765 bld.mkLoad(TYPE_U32, i->getDef(0),
2766 bld.mkSymbol(FILE_MEMORY_CONST, prog->driver->io.auxCBSlot,
2767 TYPE_U32, addr), NULL);
2768 break;
2769 case SV_SAMPLE_INDEX:
2770 // TODO: Properly pass source as an address in the PIX address space
2771 // (which can be of the form [r0+offset]). But this is currently
2772 // unnecessary.
2773 ld = bld.mkOp1(OP_PIXLD, TYPE_U32, i->getDef(0), bld.mkImm(0));
2774 ld->subOp = NV50_IR_SUBOP_PIXLD_SAMPLEID;
2775 break;
2776 case SV_SAMPLE_POS: {
2777 Value *sampleID = bld.getScratch();
2778 ld = bld.mkOp1(OP_PIXLD, TYPE_U32, sampleID, bld.mkImm(0));
2779 ld->subOp = NV50_IR_SUBOP_PIXLD_SAMPLEID;
2780 Value *offset = calculateSampleOffset(sampleID);
2781
2782 assert(prog->driver->prop.fp.readsSampleLocations);
2783
2784 if (targ->getChipset() >= NVISA_GM200_CHIPSET) {
2785 bld.mkLoad(TYPE_F32,
2786 i->getDef(0),
2787 bld.mkSymbol(
2788 FILE_MEMORY_CONST, prog->driver->io.auxCBSlot,
2789 TYPE_U32, prog->driver->io.sampleInfoBase),
2790 offset);
2791 bld.mkOp2(OP_EXTBF, TYPE_U32, i->getDef(0), i->getDef(0),
2792 bld.mkImm(0x040c + sym->reg.data.sv.index * 16));
2793 bld.mkCvt(OP_CVT, TYPE_F32, i->getDef(0), TYPE_U32, i->getDef(0));
2794 bld.mkOp2(OP_MUL, TYPE_F32, i->getDef(0), i->getDef(0), bld.mkImm(1.0f / 16.0f));
2795 } else {
2796 bld.mkLoad(TYPE_F32,
2797 i->getDef(0),
2798 bld.mkSymbol(
2799 FILE_MEMORY_CONST, prog->driver->io.auxCBSlot,
2800 TYPE_U32, prog->driver->io.sampleInfoBase +
2801 4 * sym->reg.data.sv.index),
2802 offset);
2803 }
2804 break;
2805 }
2806 case SV_SAMPLE_MASK: {
2807 ld = bld.mkOp1(OP_PIXLD, TYPE_U32, i->getDef(0), bld.mkImm(0));
2808 ld->subOp = NV50_IR_SUBOP_PIXLD_COVMASK;
2809 Instruction *sampleid =
2810 bld.mkOp1(OP_PIXLD, TYPE_U32, bld.getSSA(), bld.mkImm(0));
2811 sampleid->subOp = NV50_IR_SUBOP_PIXLD_SAMPLEID;
2812 Value *masked =
2813 bld.mkOp2v(OP_AND, TYPE_U32, bld.getSSA(), ld->getDef(0),
2814 bld.mkOp2v(OP_SHL, TYPE_U32, bld.getSSA(),
2815 bld.loadImm(NULL, 1), sampleid->getDef(0)));
2816 if (prog->driver->prop.fp.persampleInvocation) {
2817 bld.mkMov(i->getDef(0), masked);
2818 } else {
2819 bld.mkOp3(OP_SELP, TYPE_U32, i->getDef(0), ld->getDef(0), masked,
2820 bld.mkImm(0))
2821 ->subOp = 1;
2822 }
2823 break;
2824 }
2825 case SV_BASEVERTEX:
2826 case SV_BASEINSTANCE:
2827 case SV_DRAWID:
2828 ld = bld.mkLoad(TYPE_U32, i->getDef(0),
2829 bld.mkSymbol(FILE_MEMORY_CONST,
2830 prog->driver->io.auxCBSlot,
2831 TYPE_U32,
2832 prog->driver->io.drawInfoBase +
2833 4 * (sv - SV_BASEVERTEX)),
2834 NULL);
2835 break;
2836 default:
2837 if (prog->getType() == Program::TYPE_TESSELLATION_EVAL && !i->perPatch)
2838 vtx = bld.mkOp1v(OP_PFETCH, TYPE_U32, bld.getSSA(), bld.mkImm(0));
2839 if (prog->getType() == Program::TYPE_FRAGMENT) {
2840 bld.mkInterp(NV50_IR_INTERP_FLAT, i->getDef(0), addr, NULL);
2841 } else {
2842 ld = bld.mkFetch(i->getDef(0), i->dType,
2843 FILE_SHADER_INPUT, addr, i->getIndirect(0, 0), vtx);
2844 ld->perPatch = i->perPatch;
2845 }
2846 break;
2847 }
2848 bld.getBB()->remove(i);
2849 return true;
2850 }
2851
2852 bool
2853 NVC0LoweringPass::handleDIV(Instruction *i)
2854 {
2855 if (!isFloatType(i->dType))
2856 return true;
2857 bld.setPosition(i, false);
2858 Instruction *rcp = bld.mkOp1(OP_RCP, i->dType, bld.getSSA(typeSizeof(i->dType)), i->getSrc(1));
2859 i->op = OP_MUL;
2860 i->setSrc(1, rcp->getDef(0));
2861 return true;
2862 }
2863
2864 bool
2865 NVC0LoweringPass::handleMOD(Instruction *i)
2866 {
2867 if (!isFloatType(i->dType))
2868 return true;
2869 LValue *value = bld.getScratch(typeSizeof(i->dType));
2870 bld.mkOp1(OP_RCP, i->dType, value, i->getSrc(1));
2871 bld.mkOp2(OP_MUL, i->dType, value, i->getSrc(0), value);
2872 bld.mkOp1(OP_TRUNC, i->dType, value, value);
2873 bld.mkOp2(OP_MUL, i->dType, value, i->getSrc(1), value);
2874 i->op = OP_SUB;
2875 i->setSrc(1, value);
2876 return true;
2877 }
2878
2879 bool
2880 NVC0LoweringPass::handleSQRT(Instruction *i)
2881 {
2882 if (targ->isOpSupported(OP_SQRT, i->dType))
2883 return true;
2884
2885 if (i->dType == TYPE_F64) {
2886 Value *pred = bld.getSSA(1, FILE_PREDICATE);
2887 Value *zero = bld.loadImm(NULL, 0.0);
2888 Value *dst = bld.getSSA(8);
2889 bld.mkOp1(OP_RSQ, i->dType, dst, i->getSrc(0));
2890 bld.mkCmp(OP_SET, CC_LE, i->dType, pred, i->dType, i->getSrc(0), zero);
2891 bld.mkOp3(OP_SELP, TYPE_U64, dst, zero, dst, pred);
2892 i->op = OP_MUL;
2893 i->setSrc(1, dst);
2894 // TODO: Handle this properly with a library function
2895 } else {
2896 bld.setPosition(i, true);
2897 i->op = OP_RSQ;
2898 bld.mkOp1(OP_RCP, i->dType, i->getDef(0), i->getDef(0));
2899 }
2900
2901 return true;
2902 }
2903
2904 bool
2905 NVC0LoweringPass::handlePOW(Instruction *i)
2906 {
2907 LValue *val = bld.getScratch();
2908
2909 bld.mkOp1(OP_LG2, TYPE_F32, val, i->getSrc(0));
2910 bld.mkOp2(OP_MUL, TYPE_F32, val, i->getSrc(1), val)->dnz = 1;
2911 bld.mkOp1(OP_PREEX2, TYPE_F32, val, val);
2912
2913 i->op = OP_EX2;
2914 i->setSrc(0, val);
2915 i->setSrc(1, NULL);
2916
2917 return true;
2918 }
2919
2920 bool
2921 NVC0LoweringPass::handleEXPORT(Instruction *i)
2922 {
2923 if (prog->getType() == Program::TYPE_FRAGMENT) {
2924 int id = i->getSrc(0)->reg.data.offset / 4;
2925
2926 if (i->src(0).isIndirect(0)) // TODO, ugly
2927 return false;
2928 i->op = OP_MOV;
2929 i->subOp = NV50_IR_SUBOP_MOV_FINAL;
2930 i->src(0).set(i->src(1));
2931 i->setSrc(1, NULL);
2932 i->setDef(0, new_LValue(func, FILE_GPR));
2933 i->getDef(0)->reg.data.id = id;
2934
2935 prog->maxGPR = MAX2(prog->maxGPR, id);
2936 } else
2937 if (prog->getType() == Program::TYPE_GEOMETRY) {
2938 i->setIndirect(0, 1, gpEmitAddress);
2939 }
2940 return true;
2941 }
2942
2943 bool
2944 NVC0LoweringPass::handleOUT(Instruction *i)
2945 {
2946 Instruction *prev = i->prev;
2947 ImmediateValue stream, prevStream;
2948
2949 // Only merge if the stream ids match. Also, note that the previous
2950 // instruction would have already been lowered, so we take arg1 from it.
2951 if (i->op == OP_RESTART && prev && prev->op == OP_EMIT &&
2952 i->src(0).getImmediate(stream) &&
2953 prev->src(1).getImmediate(prevStream) &&
2954 stream.reg.data.u32 == prevStream.reg.data.u32) {
2955 i->prev->subOp = NV50_IR_SUBOP_EMIT_RESTART;
2956 delete_Instruction(prog, i);
2957 } else {
2958 assert(gpEmitAddress);
2959 i->setDef(0, gpEmitAddress);
2960 i->setSrc(1, i->getSrc(0));
2961 i->setSrc(0, gpEmitAddress);
2962 }
2963 return true;
2964 }
2965
2966 Value *
2967 NVC0LoweringPass::calculateSampleOffset(Value *sampleID)
2968 {
2969 Value *offset = bld.getScratch();
2970 if (targ->getChipset() >= NVISA_GM200_CHIPSET) {
2971 // Sample location offsets (in bytes) are calculated like so:
2972 // offset = (SV_POSITION.y % 4 * 2) + (SV_POSITION.x % 2)
2973 // offset = offset * 32 + sampleID % 8 * 4;
2974 // which is equivalent to:
2975 // offset = (SV_POSITION.y & 0x3) << 6 + (SV_POSITION.x & 0x1) << 5;
2976 // offset += sampleID << 2
2977
2978 // The second operand (src1) of the INSBF instructions are like so:
2979 // 0xssll where ss is the size and ll is the offset.
2980 // so: dest = src2 | (src0 & (1 << ss - 1)) << ll
2981
2982 // Add sample ID (offset = (sampleID & 0x7) << 2)
2983 bld.mkOp3(OP_INSBF, TYPE_U32, offset, sampleID, bld.mkImm(0x0302), bld.mkImm(0x0));
2984
2985 Symbol *xSym = bld.mkSysVal(SV_POSITION, 0);
2986 Symbol *ySym = bld.mkSysVal(SV_POSITION, 1);
2987 Value *coord = bld.getScratch();
2988
2989 // Add X coordinate (offset |= (SV_POSITION.x & 0x1) << 5)
2990 bld.mkInterp(NV50_IR_INTERP_LINEAR, coord,
2991 targ->getSVAddress(FILE_SHADER_INPUT, xSym), NULL);
2992 bld.mkCvt(OP_CVT, TYPE_U32, coord, TYPE_F32, coord)
2993 ->rnd = ROUND_ZI;
2994 bld.mkOp3(OP_INSBF, TYPE_U32, offset, coord, bld.mkImm(0x0105), offset);
2995
2996 // Add Y coordinate (offset |= (SV_POSITION.y & 0x3) << 6)
2997 bld.mkInterp(NV50_IR_INTERP_LINEAR, coord,
2998 targ->getSVAddress(FILE_SHADER_INPUT, ySym), NULL);
2999 bld.mkCvt(OP_CVT, TYPE_U32, coord, TYPE_F32, coord)
3000 ->rnd = ROUND_ZI;
3001 bld.mkOp3(OP_INSBF, TYPE_U32, offset, coord, bld.mkImm(0x0206), offset);
3002 } else {
3003 bld.mkOp2(OP_SHL, TYPE_U32, offset, sampleID, bld.mkImm(3));
3004 }
3005 return offset;
3006 }
3007
3008 // Handle programmable sample locations for GM20x+
3009 void
3010 NVC0LoweringPass::handlePIXLD(Instruction *i)
3011 {
3012 if (i->subOp != NV50_IR_SUBOP_PIXLD_OFFSET)
3013 return;
3014 if (targ->getChipset() < NVISA_GM200_CHIPSET)
3015 return;
3016
3017 assert(prog->driver->prop.fp.readsSampleLocations);
3018
3019 bld.mkLoad(TYPE_F32,
3020 i->getDef(0),
3021 bld.mkSymbol(
3022 FILE_MEMORY_CONST, prog->driver->io.auxCBSlot,
3023 TYPE_U32, prog->driver->io.sampleInfoBase),
3024 calculateSampleOffset(i->getSrc(0)));
3025
3026 bld.getBB()->remove(i);
3027 }
3028
3029 // Generate a binary predicate if an instruction is predicated by
3030 // e.g. an f32 value.
3031 void
3032 NVC0LoweringPass::checkPredicate(Instruction *insn)
3033 {
3034 Value *pred = insn->getPredicate();
3035 Value *pdst;
3036
3037 if (!pred || pred->reg.file == FILE_PREDICATE)
3038 return;
3039 pdst = new_LValue(func, FILE_PREDICATE);
3040
3041 // CAUTION: don't use pdst->getInsn, the definition might not be unique,
3042 // delay turning PSET(FSET(x,y),0) into PSET(x,y) to a later pass
3043
3044 bld.mkCmp(OP_SET, CC_NEU, insn->dType, pdst, insn->dType, bld.mkImm(0), pred);
3045
3046 insn->setPredicate(insn->cc, pdst);
3047 }
3048
3049 //
3050 // - add quadop dance for texturing
3051 // - put FP outputs in GPRs
3052 // - convert instruction sequences
3053 //
3054 bool
3055 NVC0LoweringPass::visit(Instruction *i)
3056 {
3057 bool ret = true;
3058 bld.setPosition(i, false);
3059
3060 if (i->cc != CC_ALWAYS)
3061 checkPredicate(i);
3062
3063 switch (i->op) {
3064 case OP_TEX:
3065 case OP_TXB:
3066 case OP_TXL:
3067 case OP_TXF:
3068 case OP_TXG:
3069 return handleTEX(i->asTex());
3070 case OP_TXD:
3071 return handleTXD(i->asTex());
3072 case OP_TXLQ:
3073 return handleTXLQ(i->asTex());
3074 case OP_TXQ:
3075 return handleTXQ(i->asTex());
3076 case OP_EX2:
3077 bld.mkOp1(OP_PREEX2, TYPE_F32, i->getDef(0), i->getSrc(0));
3078 i->setSrc(0, i->getDef(0));
3079 break;
3080 case OP_POW:
3081 return handlePOW(i);
3082 case OP_DIV:
3083 return handleDIV(i);
3084 case OP_MOD:
3085 return handleMOD(i);
3086 case OP_SQRT:
3087 return handleSQRT(i);
3088 case OP_EXPORT:
3089 ret = handleEXPORT(i);
3090 break;
3091 case OP_EMIT:
3092 case OP_RESTART:
3093 return handleOUT(i);
3094 case OP_RDSV:
3095 return handleRDSV(i);
3096 case OP_WRSV:
3097 return handleWRSV(i);
3098 case OP_STORE:
3099 case OP_LOAD:
3100 handleLDST(i);
3101 break;
3102 case OP_ATOM:
3103 {
3104 const bool cctl = i->src(0).getFile() == FILE_MEMORY_BUFFER;
3105 handleATOM(i);
3106 handleCasExch(i, cctl);
3107 }
3108 break;
3109 case OP_SULDB:
3110 case OP_SULDP:
3111 case OP_SUSTB:
3112 case OP_SUSTP:
3113 case OP_SUREDB:
3114 case OP_SUREDP:
3115 if (targ->getChipset() >= NVISA_GM107_CHIPSET)
3116 handleSurfaceOpGM107(i->asTex());
3117 else if (targ->getChipset() >= NVISA_GK104_CHIPSET)
3118 handleSurfaceOpNVE4(i->asTex());
3119 else
3120 handleSurfaceOpNVC0(i->asTex());
3121 break;
3122 case OP_SUQ:
3123 handleSUQ(i->asTex());
3124 break;
3125 case OP_BUFQ:
3126 handleBUFQ(i);
3127 break;
3128 case OP_PIXLD:
3129 handlePIXLD(i);
3130 break;
3131 default:
3132 break;
3133 }
3134
3135 /* Kepler+ has a special opcode to compute a new base address to be used
3136 * for indirect loads.
3137 *
3138 * Maxwell+ has an additional similar requirement for indirect
3139 * interpolation ops in frag shaders.
3140 */
3141 bool doAfetch = false;
3142 if (targ->getChipset() >= NVISA_GK104_CHIPSET &&
3143 !i->perPatch &&
3144 (i->op == OP_VFETCH || i->op == OP_EXPORT) &&
3145 i->src(0).isIndirect(0)) {
3146 doAfetch = true;
3147 }
3148 if (targ->getChipset() >= NVISA_GM107_CHIPSET &&
3149 (i->op == OP_LINTERP || i->op == OP_PINTERP) &&
3150 i->src(0).isIndirect(0)) {
3151 doAfetch = true;
3152 }
3153
3154 if (doAfetch) {
3155 Value *addr = cloneShallow(func, i->getSrc(0));
3156 Instruction *afetch = bld.mkOp1(OP_AFETCH, TYPE_U32, bld.getSSA(),
3157 i->getSrc(0));
3158 afetch->setIndirect(0, 0, i->getIndirect(0, 0));
3159 addr->reg.data.offset = 0;
3160 i->setSrc(0, addr);
3161 i->setIndirect(0, 0, afetch->getDef(0));
3162 }
3163
3164 return ret;
3165 }
3166
3167 bool
3168 TargetNVC0::runLegalizePass(Program *prog, CGStage stage) const
3169 {
3170 if (stage == CG_STAGE_PRE_SSA) {
3171 NVC0LoweringPass pass(prog);
3172 return pass.run(prog, false, true);
3173 } else
3174 if (stage == CG_STAGE_POST_RA) {
3175 NVC0LegalizePostRA pass(prog);
3176 return pass.run(prog, false, true);
3177 } else
3178 if (stage == CG_STAGE_SSA) {
3179 NVC0LegalizeSSA pass;
3180 return pass.run(prog, false, true);
3181 }
3182 return false;
3183 }
3184
3185 } // namespace nv50_ir