0b3220903b9f33bcfa488183bb06736c42dd2ca1
[mesa.git] / src / gallium / drivers / nouveau / codegen / nv50_ir_peephole.cpp
1 /*
2 * Copyright 2011 Christoph Bumiller
3 *
4 * Permission is hereby granted, free of charge, to any person obtaining a
5 * copy of this software and associated documentation files (the "Software"),
6 * to deal in the Software without restriction, including without limitation
7 * the rights to use, copy, modify, merge, publish, distribute, sublicense,
8 * and/or sell copies of the Software, and to permit persons to whom the
9 * Software is furnished to do so, subject to the following conditions:
10 *
11 * The above copyright notice and this permission notice shall be included in
12 * all copies or substantial portions of the Software.
13 *
14 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
15 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
16 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
17 * THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR
18 * OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE,
19 * ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
20 * OTHER DEALINGS IN THE SOFTWARE.
21 */
22
23 #include "codegen/nv50_ir.h"
24 #include "codegen/nv50_ir_target.h"
25 #include "codegen/nv50_ir_build_util.h"
26
27 extern "C" {
28 #include "util/u_math.h"
29 }
30
31 namespace nv50_ir {
32
33 bool
34 Instruction::isNop() const
35 {
36 if (op == OP_PHI || op == OP_SPLIT || op == OP_MERGE || op == OP_CONSTRAINT)
37 return true;
38 if (terminator || join) // XXX: should terminator imply flow ?
39 return false;
40 if (op == OP_ATOM)
41 return false;
42 if (!fixed && op == OP_NOP)
43 return true;
44
45 if (defExists(0) && def(0).rep()->reg.data.id < 0) {
46 for (int d = 1; defExists(d); ++d)
47 if (def(d).rep()->reg.data.id >= 0)
48 WARN("part of vector result is unused !\n");
49 return true;
50 }
51
52 if (op == OP_MOV || op == OP_UNION) {
53 if (!getDef(0)->equals(getSrc(0)))
54 return false;
55 if (op == OP_UNION)
56 if (!def(0).rep()->equals(getSrc(1)))
57 return false;
58 return true;
59 }
60
61 return false;
62 }
63
64 bool Instruction::isDead() const
65 {
66 if (op == OP_STORE ||
67 op == OP_EXPORT ||
68 op == OP_ATOM ||
69 op == OP_SUSTB || op == OP_SUSTP || op == OP_SUREDP || op == OP_SUREDB ||
70 op == OP_WRSV)
71 return false;
72
73 for (int d = 0; defExists(d); ++d)
74 if (getDef(d)->refCount() || getDef(d)->reg.data.id >= 0)
75 return false;
76
77 if (terminator || asFlow())
78 return false;
79 if (fixed)
80 return false;
81
82 return true;
83 };
84
85 // =============================================================================
86
87 class CopyPropagation : public Pass
88 {
89 private:
90 virtual bool visit(BasicBlock *);
91 };
92
93 // Propagate all MOVs forward to make subsequent optimization easier, except if
94 // the sources stem from a phi, in which case we don't want to mess up potential
95 // swaps $rX <-> $rY, i.e. do not create live range overlaps of phi src and def.
96 bool
97 CopyPropagation::visit(BasicBlock *bb)
98 {
99 Instruction *mov, *si, *next;
100
101 for (mov = bb->getEntry(); mov; mov = next) {
102 next = mov->next;
103 if (mov->op != OP_MOV || mov->fixed || !mov->getSrc(0)->asLValue())
104 continue;
105 if (mov->getPredicate())
106 continue;
107 if (mov->def(0).getFile() != mov->src(0).getFile())
108 continue;
109 si = mov->getSrc(0)->getInsn();
110 if (mov->getDef(0)->reg.data.id < 0 && si && si->op != OP_PHI) {
111 // propagate
112 mov->def(0).replace(mov->getSrc(0), false);
113 delete_Instruction(prog, mov);
114 }
115 }
116 return true;
117 }
118
119 // =============================================================================
120
121 class MergeSplits : public Pass
122 {
123 private:
124 virtual bool visit(BasicBlock *);
125 };
126
127 // For SPLIT / MERGE pairs that operate on the same registers, replace the
128 // post-merge def with the SPLIT's source.
129 bool
130 MergeSplits::visit(BasicBlock *bb)
131 {
132 Instruction *i, *next, *si;
133
134 for (i = bb->getEntry(); i; i = next) {
135 next = i->next;
136 if (i->op != OP_MERGE || typeSizeof(i->dType) != 8)
137 continue;
138 si = i->getSrc(0)->getInsn();
139 if (si->op != OP_SPLIT || si != i->getSrc(1)->getInsn())
140 continue;
141 i->def(0).replace(si->getSrc(0), false);
142 delete_Instruction(prog, i);
143 }
144
145 return true;
146 }
147
148 // =============================================================================
149
150 class LoadPropagation : public Pass
151 {
152 private:
153 virtual bool visit(BasicBlock *);
154
155 void checkSwapSrc01(Instruction *);
156
157 bool isCSpaceLoad(Instruction *);
158 bool isImmdLoad(Instruction *);
159 bool isAttribOrSharedLoad(Instruction *);
160 };
161
162 bool
163 LoadPropagation::isCSpaceLoad(Instruction *ld)
164 {
165 return ld && ld->op == OP_LOAD && ld->src(0).getFile() == FILE_MEMORY_CONST;
166 }
167
168 bool
169 LoadPropagation::isImmdLoad(Instruction *ld)
170 {
171 if (!ld || (ld->op != OP_MOV) ||
172 ((typeSizeof(ld->dType) != 4) && (typeSizeof(ld->dType) != 8)))
173 return false;
174
175 // A 0 can be replaced with a register, so it doesn't count as an immediate.
176 ImmediateValue val;
177 return ld->src(0).getImmediate(val) && !val.isInteger(0);
178 }
179
180 bool
181 LoadPropagation::isAttribOrSharedLoad(Instruction *ld)
182 {
183 return ld &&
184 (ld->op == OP_VFETCH ||
185 (ld->op == OP_LOAD &&
186 (ld->src(0).getFile() == FILE_SHADER_INPUT ||
187 ld->src(0).getFile() == FILE_MEMORY_SHARED)));
188 }
189
190 void
191 LoadPropagation::checkSwapSrc01(Instruction *insn)
192 {
193 const Target *targ = prog->getTarget();
194 if (!targ->getOpInfo(insn).commutative) {
195 if (insn->op != OP_SET && insn->op != OP_SLCT &&
196 insn->op != OP_SUB && insn->op != OP_XMAD)
197 return;
198 // XMAD is only commutative if both the CBCC and MRG flags are not set.
199 if (insn->op == OP_XMAD &&
200 (insn->subOp & NV50_IR_SUBOP_XMAD_CMODE_MASK) == NV50_IR_SUBOP_XMAD_CBCC)
201 return;
202 if (insn->op == OP_XMAD && (insn->subOp & NV50_IR_SUBOP_XMAD_MRG))
203 return;
204 }
205 if (insn->src(1).getFile() != FILE_GPR)
206 return;
207 // This is the special OP_SET used for alphatesting, we can't reverse its
208 // arguments as that will confuse the fixup code.
209 if (insn->op == OP_SET && insn->subOp)
210 return;
211
212 Instruction *i0 = insn->getSrc(0)->getInsn();
213 Instruction *i1 = insn->getSrc(1)->getInsn();
214
215 // Swap sources to inline the less frequently used source. That way,
216 // optimistically, it will eventually be able to remove the instruction.
217 int i0refs = insn->getSrc(0)->refCount();
218 int i1refs = insn->getSrc(1)->refCount();
219
220 if ((isCSpaceLoad(i0) || isImmdLoad(i0)) && targ->insnCanLoad(insn, 1, i0)) {
221 if ((!isImmdLoad(i1) && !isCSpaceLoad(i1)) ||
222 !targ->insnCanLoad(insn, 1, i1) ||
223 i0refs < i1refs)
224 insn->swapSources(0, 1);
225 else
226 return;
227 } else
228 if (isAttribOrSharedLoad(i1)) {
229 if (!isAttribOrSharedLoad(i0))
230 insn->swapSources(0, 1);
231 else
232 return;
233 } else {
234 return;
235 }
236
237 if (insn->op == OP_SET || insn->op == OP_SET_AND ||
238 insn->op == OP_SET_OR || insn->op == OP_SET_XOR)
239 insn->asCmp()->setCond = reverseCondCode(insn->asCmp()->setCond);
240 else
241 if (insn->op == OP_SLCT)
242 insn->asCmp()->setCond = inverseCondCode(insn->asCmp()->setCond);
243 else
244 if (insn->op == OP_SUB) {
245 insn->src(0).mod = insn->src(0).mod ^ Modifier(NV50_IR_MOD_NEG);
246 insn->src(1).mod = insn->src(1).mod ^ Modifier(NV50_IR_MOD_NEG);
247 } else
248 if (insn->op == OP_XMAD) {
249 // swap h1 flags
250 uint16_t h1 = (insn->subOp >> 1 & NV50_IR_SUBOP_XMAD_H1(0)) |
251 (insn->subOp << 1 & NV50_IR_SUBOP_XMAD_H1(1));
252 insn->subOp = (insn->subOp & ~NV50_IR_SUBOP_XMAD_H1_MASK) | h1;
253 }
254 }
255
256 bool
257 LoadPropagation::visit(BasicBlock *bb)
258 {
259 const Target *targ = prog->getTarget();
260 Instruction *next;
261
262 for (Instruction *i = bb->getEntry(); i; i = next) {
263 next = i->next;
264
265 if (i->op == OP_CALL) // calls have args as sources, they must be in regs
266 continue;
267
268 if (i->op == OP_PFETCH) // pfetch expects arg1 to be a reg
269 continue;
270
271 if (i->srcExists(1))
272 checkSwapSrc01(i);
273
274 for (int s = 0; i->srcExists(s); ++s) {
275 Instruction *ld = i->getSrc(s)->getInsn();
276
277 if (!ld || ld->fixed || (ld->op != OP_LOAD && ld->op != OP_MOV))
278 continue;
279 if (!targ->insnCanLoad(i, s, ld))
280 continue;
281
282 // propagate !
283 i->setSrc(s, ld->getSrc(0));
284 if (ld->src(0).isIndirect(0))
285 i->setIndirect(s, 0, ld->getIndirect(0, 0));
286
287 if (ld->getDef(0)->refCount() == 0)
288 delete_Instruction(prog, ld);
289 }
290 }
291 return true;
292 }
293
294 // =============================================================================
295
296 class IndirectPropagation : public Pass
297 {
298 private:
299 virtual bool visit(BasicBlock *);
300
301 BuildUtil bld;
302 };
303
304 bool
305 IndirectPropagation::visit(BasicBlock *bb)
306 {
307 const Target *targ = prog->getTarget();
308 Instruction *next;
309
310 for (Instruction *i = bb->getEntry(); i; i = next) {
311 next = i->next;
312
313 bld.setPosition(i, false);
314
315 for (int s = 0; i->srcExists(s); ++s) {
316 Instruction *insn;
317 ImmediateValue imm;
318 if (!i->src(s).isIndirect(0))
319 continue;
320 insn = i->getIndirect(s, 0)->getInsn();
321 if (!insn)
322 continue;
323 if (insn->op == OP_ADD && !isFloatType(insn->dType)) {
324 if (insn->src(0).getFile() != targ->nativeFile(FILE_ADDRESS) ||
325 !insn->src(1).getImmediate(imm) ||
326 !targ->insnCanLoadOffset(i, s, imm.reg.data.s32))
327 continue;
328 i->setIndirect(s, 0, insn->getSrc(0));
329 i->setSrc(s, cloneShallow(func, i->getSrc(s)));
330 i->src(s).get()->reg.data.offset += imm.reg.data.u32;
331 } else if (insn->op == OP_SUB && !isFloatType(insn->dType)) {
332 if (insn->src(0).getFile() != targ->nativeFile(FILE_ADDRESS) ||
333 !insn->src(1).getImmediate(imm) ||
334 !targ->insnCanLoadOffset(i, s, -imm.reg.data.s32))
335 continue;
336 i->setIndirect(s, 0, insn->getSrc(0));
337 i->setSrc(s, cloneShallow(func, i->getSrc(s)));
338 i->src(s).get()->reg.data.offset -= imm.reg.data.u32;
339 } else if (insn->op == OP_MOV) {
340 if (!insn->src(0).getImmediate(imm) ||
341 !targ->insnCanLoadOffset(i, s, imm.reg.data.s32))
342 continue;
343 i->setIndirect(s, 0, NULL);
344 i->setSrc(s, cloneShallow(func, i->getSrc(s)));
345 i->src(s).get()->reg.data.offset += imm.reg.data.u32;
346 } else if (insn->op == OP_SHLADD) {
347 if (!insn->src(2).getImmediate(imm) ||
348 !targ->insnCanLoadOffset(i, s, imm.reg.data.s32))
349 continue;
350 i->setIndirect(s, 0, bld.mkOp2v(
351 OP_SHL, TYPE_U32, bld.getSSA(), insn->getSrc(0), insn->getSrc(1)));
352 i->setSrc(s, cloneShallow(func, i->getSrc(s)));
353 i->src(s).get()->reg.data.offset += imm.reg.data.u32;
354 }
355 }
356 }
357 return true;
358 }
359
360 // =============================================================================
361
362 // Evaluate constant expressions.
363 class ConstantFolding : public Pass
364 {
365 public:
366 bool foldAll(Program *);
367
368 private:
369 virtual bool visit(BasicBlock *);
370
371 void expr(Instruction *, ImmediateValue&, ImmediateValue&);
372 void expr(Instruction *, ImmediateValue&, ImmediateValue&, ImmediateValue&);
373 /* true if i was deleted */
374 bool opnd(Instruction *i, ImmediateValue&, int s);
375 void opnd3(Instruction *, ImmediateValue&);
376
377 void unary(Instruction *, const ImmediateValue&);
378
379 void tryCollapseChainedMULs(Instruction *, const int s, ImmediateValue&);
380
381 CmpInstruction *findOriginForTestWithZero(Value *);
382
383 bool createMul(DataType ty, Value *def, Value *a, int64_t b, Value *c);
384
385 unsigned int foldCount;
386
387 BuildUtil bld;
388 };
389
390 // TODO: remember generated immediates and only revisit these
391 bool
392 ConstantFolding::foldAll(Program *prog)
393 {
394 unsigned int iterCount = 0;
395 do {
396 foldCount = 0;
397 if (!run(prog))
398 return false;
399 } while (foldCount && ++iterCount < 2);
400 return true;
401 }
402
403 bool
404 ConstantFolding::visit(BasicBlock *bb)
405 {
406 Instruction *i, *next;
407
408 for (i = bb->getEntry(); i; i = next) {
409 next = i->next;
410 if (i->op == OP_MOV || i->op == OP_CALL)
411 continue;
412
413 ImmediateValue src0, src1, src2;
414
415 if (i->srcExists(2) &&
416 i->src(0).getImmediate(src0) &&
417 i->src(1).getImmediate(src1) &&
418 i->src(2).getImmediate(src2)) {
419 expr(i, src0, src1, src2);
420 } else
421 if (i->srcExists(1) &&
422 i->src(0).getImmediate(src0) && i->src(1).getImmediate(src1)) {
423 expr(i, src0, src1);
424 } else
425 if (i->srcExists(0) && i->src(0).getImmediate(src0)) {
426 if (opnd(i, src0, 0))
427 continue;
428 } else
429 if (i->srcExists(1) && i->src(1).getImmediate(src1)) {
430 if (opnd(i, src1, 1))
431 continue;
432 }
433 if (i->srcExists(2) && i->src(2).getImmediate(src2))
434 opnd3(i, src2);
435 }
436 return true;
437 }
438
439 CmpInstruction *
440 ConstantFolding::findOriginForTestWithZero(Value *value)
441 {
442 if (!value)
443 return NULL;
444 Instruction *insn = value->getInsn();
445 if (!insn)
446 return NULL;
447
448 if (insn->asCmp() && insn->op != OP_SLCT)
449 return insn->asCmp();
450
451 /* Sometimes mov's will sneak in as a result of other folding. This gets
452 * cleaned up later.
453 */
454 if (insn->op == OP_MOV)
455 return findOriginForTestWithZero(insn->getSrc(0));
456
457 /* Deal with AND 1.0 here since nv50 can't fold into boolean float */
458 if (insn->op == OP_AND) {
459 int s = 0;
460 ImmediateValue imm;
461 if (!insn->src(s).getImmediate(imm)) {
462 s = 1;
463 if (!insn->src(s).getImmediate(imm))
464 return NULL;
465 }
466 if (imm.reg.data.f32 != 1.0f)
467 return NULL;
468 /* TODO: Come up with a way to handle the condition being inverted */
469 if (insn->src(!s).mod != Modifier(0))
470 return NULL;
471 return findOriginForTestWithZero(insn->getSrc(!s));
472 }
473
474 return NULL;
475 }
476
477 void
478 Modifier::applyTo(ImmediateValue& imm) const
479 {
480 if (!bits) // avoid failure if imm.reg.type is unhandled (e.g. b128)
481 return;
482 switch (imm.reg.type) {
483 case TYPE_F32:
484 if (bits & NV50_IR_MOD_ABS)
485 imm.reg.data.f32 = fabsf(imm.reg.data.f32);
486 if (bits & NV50_IR_MOD_NEG)
487 imm.reg.data.f32 = -imm.reg.data.f32;
488 if (bits & NV50_IR_MOD_SAT) {
489 if (imm.reg.data.f32 < 0.0f)
490 imm.reg.data.f32 = 0.0f;
491 else
492 if (imm.reg.data.f32 > 1.0f)
493 imm.reg.data.f32 = 1.0f;
494 }
495 assert(!(bits & NV50_IR_MOD_NOT));
496 break;
497
498 case TYPE_S8: // NOTE: will be extended
499 case TYPE_S16:
500 case TYPE_S32:
501 case TYPE_U8: // NOTE: treated as signed
502 case TYPE_U16:
503 case TYPE_U32:
504 if (bits & NV50_IR_MOD_ABS)
505 imm.reg.data.s32 = (imm.reg.data.s32 >= 0) ?
506 imm.reg.data.s32 : -imm.reg.data.s32;
507 if (bits & NV50_IR_MOD_NEG)
508 imm.reg.data.s32 = -imm.reg.data.s32;
509 if (bits & NV50_IR_MOD_NOT)
510 imm.reg.data.s32 = ~imm.reg.data.s32;
511 break;
512
513 case TYPE_F64:
514 if (bits & NV50_IR_MOD_ABS)
515 imm.reg.data.f64 = fabs(imm.reg.data.f64);
516 if (bits & NV50_IR_MOD_NEG)
517 imm.reg.data.f64 = -imm.reg.data.f64;
518 if (bits & NV50_IR_MOD_SAT) {
519 if (imm.reg.data.f64 < 0.0)
520 imm.reg.data.f64 = 0.0;
521 else
522 if (imm.reg.data.f64 > 1.0)
523 imm.reg.data.f64 = 1.0;
524 }
525 assert(!(bits & NV50_IR_MOD_NOT));
526 break;
527
528 default:
529 assert(!"invalid/unhandled type");
530 imm.reg.data.u64 = 0;
531 break;
532 }
533 }
534
535 operation
536 Modifier::getOp() const
537 {
538 switch (bits) {
539 case NV50_IR_MOD_ABS: return OP_ABS;
540 case NV50_IR_MOD_NEG: return OP_NEG;
541 case NV50_IR_MOD_SAT: return OP_SAT;
542 case NV50_IR_MOD_NOT: return OP_NOT;
543 case 0:
544 return OP_MOV;
545 default:
546 return OP_CVT;
547 }
548 }
549
550 void
551 ConstantFolding::expr(Instruction *i,
552 ImmediateValue &imm0, ImmediateValue &imm1)
553 {
554 struct Storage *const a = &imm0.reg, *const b = &imm1.reg;
555 struct Storage res;
556 DataType type = i->dType;
557
558 memset(&res.data, 0, sizeof(res.data));
559
560 switch (i->op) {
561 case OP_MAD:
562 case OP_FMA:
563 case OP_MUL:
564 if (i->dnz && i->dType == TYPE_F32) {
565 if (!isfinite(a->data.f32))
566 a->data.f32 = 0.0f;
567 if (!isfinite(b->data.f32))
568 b->data.f32 = 0.0f;
569 }
570 switch (i->dType) {
571 case TYPE_F32:
572 res.data.f32 = a->data.f32 * b->data.f32 * exp2f(i->postFactor);
573 break;
574 case TYPE_F64: res.data.f64 = a->data.f64 * b->data.f64; break;
575 case TYPE_S32:
576 if (i->subOp == NV50_IR_SUBOP_MUL_HIGH) {
577 res.data.s32 = ((int64_t)a->data.s32 * b->data.s32) >> 32;
578 break;
579 }
580 /* fallthrough */
581 case TYPE_U32:
582 if (i->subOp == NV50_IR_SUBOP_MUL_HIGH) {
583 res.data.u32 = ((uint64_t)a->data.u32 * b->data.u32) >> 32;
584 break;
585 }
586 res.data.u32 = a->data.u32 * b->data.u32; break;
587 default:
588 return;
589 }
590 break;
591 case OP_DIV:
592 if (b->data.u32 == 0)
593 break;
594 switch (i->dType) {
595 case TYPE_F32: res.data.f32 = a->data.f32 / b->data.f32; break;
596 case TYPE_F64: res.data.f64 = a->data.f64 / b->data.f64; break;
597 case TYPE_S32: res.data.s32 = a->data.s32 / b->data.s32; break;
598 case TYPE_U32: res.data.u32 = a->data.u32 / b->data.u32; break;
599 default:
600 return;
601 }
602 break;
603 case OP_ADD:
604 switch (i->dType) {
605 case TYPE_F32: res.data.f32 = a->data.f32 + b->data.f32; break;
606 case TYPE_F64: res.data.f64 = a->data.f64 + b->data.f64; break;
607 case TYPE_S32:
608 case TYPE_U32: res.data.u32 = a->data.u32 + b->data.u32; break;
609 default:
610 return;
611 }
612 break;
613 case OP_SUB:
614 switch (i->dType) {
615 case TYPE_F32: res.data.f32 = a->data.f32 - b->data.f32; break;
616 case TYPE_F64: res.data.f64 = a->data.f64 - b->data.f64; break;
617 case TYPE_S32:
618 case TYPE_U32: res.data.u32 = a->data.u32 - b->data.u32; break;
619 default:
620 return;
621 }
622 break;
623 case OP_POW:
624 switch (i->dType) {
625 case TYPE_F32: res.data.f32 = pow(a->data.f32, b->data.f32); break;
626 case TYPE_F64: res.data.f64 = pow(a->data.f64, b->data.f64); break;
627 default:
628 return;
629 }
630 break;
631 case OP_MAX:
632 switch (i->dType) {
633 case TYPE_F32: res.data.f32 = MAX2(a->data.f32, b->data.f32); break;
634 case TYPE_F64: res.data.f64 = MAX2(a->data.f64, b->data.f64); break;
635 case TYPE_S32: res.data.s32 = MAX2(a->data.s32, b->data.s32); break;
636 case TYPE_U32: res.data.u32 = MAX2(a->data.u32, b->data.u32); break;
637 default:
638 return;
639 }
640 break;
641 case OP_MIN:
642 switch (i->dType) {
643 case TYPE_F32: res.data.f32 = MIN2(a->data.f32, b->data.f32); break;
644 case TYPE_F64: res.data.f64 = MIN2(a->data.f64, b->data.f64); break;
645 case TYPE_S32: res.data.s32 = MIN2(a->data.s32, b->data.s32); break;
646 case TYPE_U32: res.data.u32 = MIN2(a->data.u32, b->data.u32); break;
647 default:
648 return;
649 }
650 break;
651 case OP_AND:
652 res.data.u64 = a->data.u64 & b->data.u64;
653 break;
654 case OP_OR:
655 res.data.u64 = a->data.u64 | b->data.u64;
656 break;
657 case OP_XOR:
658 res.data.u64 = a->data.u64 ^ b->data.u64;
659 break;
660 case OP_SHL:
661 res.data.u32 = a->data.u32 << b->data.u32;
662 break;
663 case OP_SHR:
664 switch (i->dType) {
665 case TYPE_S32: res.data.s32 = a->data.s32 >> b->data.u32; break;
666 case TYPE_U32: res.data.u32 = a->data.u32 >> b->data.u32; break;
667 default:
668 return;
669 }
670 break;
671 case OP_SLCT:
672 if (a->data.u32 != b->data.u32)
673 return;
674 res.data.u32 = a->data.u32;
675 break;
676 case OP_EXTBF: {
677 int offset = b->data.u32 & 0xff;
678 int width = (b->data.u32 >> 8) & 0xff;
679 int rshift = offset;
680 int lshift = 0;
681 if (width == 0) {
682 res.data.u32 = 0;
683 break;
684 }
685 if (width + offset < 32) {
686 rshift = 32 - width;
687 lshift = 32 - width - offset;
688 }
689 if (i->subOp == NV50_IR_SUBOP_EXTBF_REV)
690 res.data.u32 = util_bitreverse(a->data.u32);
691 else
692 res.data.u32 = a->data.u32;
693 switch (i->dType) {
694 case TYPE_S32: res.data.s32 = (res.data.s32 << lshift) >> rshift; break;
695 case TYPE_U32: res.data.u32 = (res.data.u32 << lshift) >> rshift; break;
696 default:
697 return;
698 }
699 break;
700 }
701 case OP_POPCNT:
702 res.data.u32 = util_bitcount(a->data.u32 & b->data.u32);
703 break;
704 case OP_PFETCH:
705 // The two arguments to pfetch are logically added together. Normally
706 // the second argument will not be constant, but that can happen.
707 res.data.u32 = a->data.u32 + b->data.u32;
708 type = TYPE_U32;
709 break;
710 case OP_MERGE:
711 switch (i->dType) {
712 case TYPE_U64:
713 case TYPE_S64:
714 case TYPE_F64:
715 res.data.u64 = (((uint64_t)b->data.u32) << 32) | a->data.u32;
716 break;
717 default:
718 return;
719 }
720 break;
721 default:
722 return;
723 }
724 ++foldCount;
725
726 i->src(0).mod = Modifier(0);
727 i->src(1).mod = Modifier(0);
728 i->postFactor = 0;
729
730 i->setSrc(0, new_ImmediateValue(i->bb->getProgram(), res.data.u32));
731 i->setSrc(1, NULL);
732
733 i->getSrc(0)->reg.data = res.data;
734 i->getSrc(0)->reg.type = type;
735 i->getSrc(0)->reg.size = typeSizeof(type);
736
737 switch (i->op) {
738 case OP_MAD:
739 case OP_FMA: {
740 ImmediateValue src0, src1 = *i->getSrc(0)->asImm();
741
742 // Move the immediate into position 1, where we know it might be
743 // emittable. However it might not be anyways, as there may be other
744 // restrictions, so move it into a separate LValue.
745 bld.setPosition(i, false);
746 i->op = OP_ADD;
747 i->dnz = 0;
748 i->setSrc(1, bld.mkMov(bld.getSSA(type), i->getSrc(0), type)->getDef(0));
749 i->setSrc(0, i->getSrc(2));
750 i->src(0).mod = i->src(2).mod;
751 i->setSrc(2, NULL);
752
753 if (i->src(0).getImmediate(src0))
754 expr(i, src0, src1);
755 else
756 opnd(i, src1, 1);
757 break;
758 }
759 case OP_PFETCH:
760 // Leave PFETCH alone... we just folded its 2 args into 1.
761 break;
762 default:
763 i->op = i->saturate ? OP_SAT : OP_MOV;
764 if (i->saturate)
765 unary(i, *i->getSrc(0)->asImm());
766 break;
767 }
768 i->subOp = 0;
769 }
770
771 void
772 ConstantFolding::expr(Instruction *i,
773 ImmediateValue &imm0,
774 ImmediateValue &imm1,
775 ImmediateValue &imm2)
776 {
777 struct Storage *const a = &imm0.reg, *const b = &imm1.reg, *const c = &imm2.reg;
778 struct Storage res;
779
780 memset(&res.data, 0, sizeof(res.data));
781
782 switch (i->op) {
783 case OP_INSBF: {
784 int offset = b->data.u32 & 0xff;
785 int width = (b->data.u32 >> 8) & 0xff;
786 unsigned bitmask = ((1 << width) - 1) << offset;
787 res.data.u32 = ((a->data.u32 << offset) & bitmask) | (c->data.u32 & ~bitmask);
788 break;
789 }
790 case OP_MAD:
791 case OP_FMA: {
792 switch (i->dType) {
793 case TYPE_F32:
794 res.data.f32 = a->data.f32 * b->data.f32 * exp2f(i->postFactor) +
795 c->data.f32;
796 break;
797 case TYPE_F64:
798 res.data.f64 = a->data.f64 * b->data.f64 + c->data.f64;
799 break;
800 case TYPE_S32:
801 if (i->subOp == NV50_IR_SUBOP_MUL_HIGH) {
802 res.data.s32 = ((int64_t)a->data.s32 * b->data.s32 >> 32) + c->data.s32;
803 break;
804 }
805 /* fallthrough */
806 case TYPE_U32:
807 if (i->subOp == NV50_IR_SUBOP_MUL_HIGH) {
808 res.data.u32 = ((uint64_t)a->data.u32 * b->data.u32 >> 32) + c->data.u32;
809 break;
810 }
811 res.data.u32 = a->data.u32 * b->data.u32 + c->data.u32;
812 break;
813 default:
814 return;
815 }
816 break;
817 }
818 case OP_SHLADD:
819 res.data.u32 = (a->data.u32 << b->data.u32) + c->data.u32;
820 break;
821 default:
822 return;
823 }
824
825 ++foldCount;
826 i->src(0).mod = Modifier(0);
827 i->src(1).mod = Modifier(0);
828 i->src(2).mod = Modifier(0);
829
830 i->setSrc(0, new_ImmediateValue(i->bb->getProgram(), res.data.u32));
831 i->setSrc(1, NULL);
832 i->setSrc(2, NULL);
833
834 i->getSrc(0)->reg.data = res.data;
835 i->getSrc(0)->reg.type = i->dType;
836 i->getSrc(0)->reg.size = typeSizeof(i->dType);
837
838 i->op = OP_MOV;
839 }
840
841 void
842 ConstantFolding::unary(Instruction *i, const ImmediateValue &imm)
843 {
844 Storage res;
845
846 if (i->dType != TYPE_F32)
847 return;
848 switch (i->op) {
849 case OP_NEG: res.data.f32 = -imm.reg.data.f32; break;
850 case OP_ABS: res.data.f32 = fabsf(imm.reg.data.f32); break;
851 case OP_SAT: res.data.f32 = CLAMP(imm.reg.data.f32, 0.0f, 1.0f); break;
852 case OP_RCP: res.data.f32 = 1.0f / imm.reg.data.f32; break;
853 case OP_RSQ: res.data.f32 = 1.0f / sqrtf(imm.reg.data.f32); break;
854 case OP_LG2: res.data.f32 = log2f(imm.reg.data.f32); break;
855 case OP_EX2: res.data.f32 = exp2f(imm.reg.data.f32); break;
856 case OP_SIN: res.data.f32 = sinf(imm.reg.data.f32); break;
857 case OP_COS: res.data.f32 = cosf(imm.reg.data.f32); break;
858 case OP_SQRT: res.data.f32 = sqrtf(imm.reg.data.f32); break;
859 case OP_PRESIN:
860 case OP_PREEX2:
861 // these should be handled in subsequent OP_SIN/COS/EX2
862 res.data.f32 = imm.reg.data.f32;
863 break;
864 default:
865 return;
866 }
867 i->op = OP_MOV;
868 i->setSrc(0, new_ImmediateValue(i->bb->getProgram(), res.data.f32));
869 i->src(0).mod = Modifier(0);
870 }
871
872 void
873 ConstantFolding::tryCollapseChainedMULs(Instruction *mul2,
874 const int s, ImmediateValue& imm2)
875 {
876 const int t = s ? 0 : 1;
877 Instruction *insn;
878 Instruction *mul1 = NULL; // mul1 before mul2
879 int e = 0;
880 float f = imm2.reg.data.f32 * exp2f(mul2->postFactor);
881 ImmediateValue imm1;
882
883 assert(mul2->op == OP_MUL && mul2->dType == TYPE_F32);
884
885 if (mul2->getSrc(t)->refCount() == 1) {
886 insn = mul2->getSrc(t)->getInsn();
887 if (!mul2->src(t).mod && insn->op == OP_MUL && insn->dType == TYPE_F32)
888 mul1 = insn;
889 if (mul1 && !mul1->saturate) {
890 int s1;
891
892 if (mul1->src(s1 = 0).getImmediate(imm1) ||
893 mul1->src(s1 = 1).getImmediate(imm1)) {
894 bld.setPosition(mul1, false);
895 // a = mul r, imm1
896 // d = mul a, imm2 -> d = mul r, (imm1 * imm2)
897 mul1->setSrc(s1, bld.loadImm(NULL, f * imm1.reg.data.f32));
898 mul1->src(s1).mod = Modifier(0);
899 mul2->def(0).replace(mul1->getDef(0), false);
900 mul1->saturate = mul2->saturate;
901 } else
902 if (prog->getTarget()->isPostMultiplySupported(OP_MUL, f, e)) {
903 // c = mul a, b
904 // d = mul c, imm -> d = mul_x_imm a, b
905 mul1->postFactor = e;
906 mul2->def(0).replace(mul1->getDef(0), false);
907 if (f < 0)
908 mul1->src(0).mod *= Modifier(NV50_IR_MOD_NEG);
909 mul1->saturate = mul2->saturate;
910 }
911 return;
912 }
913 }
914 if (mul2->getDef(0)->refCount() == 1 && !mul2->saturate) {
915 // b = mul a, imm
916 // d = mul b, c -> d = mul_x_imm a, c
917 int s2, t2;
918 insn = (*mul2->getDef(0)->uses.begin())->getInsn();
919 if (!insn)
920 return;
921 mul1 = mul2;
922 mul2 = NULL;
923 s2 = insn->getSrc(0) == mul1->getDef(0) ? 0 : 1;
924 t2 = s2 ? 0 : 1;
925 if (insn->op == OP_MUL && insn->dType == TYPE_F32)
926 if (!insn->src(s2).mod && !insn->src(t2).getImmediate(imm1))
927 mul2 = insn;
928 if (mul2 && prog->getTarget()->isPostMultiplySupported(OP_MUL, f, e)) {
929 mul2->postFactor = e;
930 mul2->setSrc(s2, mul1->src(t));
931 if (f < 0)
932 mul2->src(s2).mod *= Modifier(NV50_IR_MOD_NEG);
933 }
934 }
935 }
936
937 void
938 ConstantFolding::opnd3(Instruction *i, ImmediateValue &imm2)
939 {
940 switch (i->op) {
941 case OP_MAD:
942 case OP_FMA:
943 if (imm2.isInteger(0)) {
944 i->op = OP_MUL;
945 i->setSrc(2, NULL);
946 foldCount++;
947 return;
948 }
949 break;
950 case OP_SHLADD:
951 if (imm2.isInteger(0)) {
952 i->op = OP_SHL;
953 i->setSrc(2, NULL);
954 foldCount++;
955 return;
956 }
957 break;
958 default:
959 return;
960 }
961 }
962
963 bool
964 ConstantFolding::createMul(DataType ty, Value *def, Value *a, int64_t b, Value *c)
965 {
966 const Target *target = prog->getTarget();
967 int64_t absB = llabs(b);
968
969 //a * (2^shl) -> a << shl
970 if (b >= 0 && util_is_power_of_two_or_zero64(b)) {
971 int shl = util_logbase2_64(b);
972
973 Value *res = c ? bld.getSSA(typeSizeof(ty)) : def;
974 bld.mkOp2(OP_SHL, ty, res, a, bld.mkImm(shl));
975 if (c)
976 bld.mkOp2(OP_ADD, ty, def, res, c);
977
978 return true;
979 }
980
981 //a * (2^shl + 1) -> a << shl + a
982 //a * -(2^shl + 1) -> -a << shl + a
983 //a * (2^shl - 1) -> a << shl - a
984 //a * -(2^shl - 1) -> -a << shl - a
985 if (typeSizeof(ty) == 4 &&
986 (util_is_power_of_two_or_zero64(absB - 1) ||
987 util_is_power_of_two_or_zero64(absB + 1)) &&
988 target->isOpSupported(OP_SHLADD, TYPE_U32)) {
989 bool subA = util_is_power_of_two_or_zero64(absB + 1);
990 int shl = subA ? util_logbase2_64(absB + 1) : util_logbase2_64(absB - 1);
991
992 Value *res = c ? bld.getSSA() : def;
993 Instruction *insn = bld.mkOp3(OP_SHLADD, TYPE_U32, res, a, bld.mkImm(shl), a);
994 if (b < 0)
995 insn->src(0).mod = Modifier(NV50_IR_MOD_NEG);
996 if (subA)
997 insn->src(2).mod = Modifier(NV50_IR_MOD_NEG);
998
999 if (c)
1000 bld.mkOp2(OP_ADD, TYPE_U32, def, res, c);
1001
1002 return true;
1003 }
1004
1005 if (typeSizeof(ty) == 4 && b >= 0 && b <= 0xffff &&
1006 target->isOpSupported(OP_XMAD, TYPE_U32)) {
1007 Value *tmp = bld.mkOp3v(OP_XMAD, TYPE_U32, bld.getSSA(),
1008 a, bld.mkImm((uint32_t)b), c ? c : bld.mkImm(0));
1009 bld.mkOp3(OP_XMAD, TYPE_U32, def, a, bld.mkImm((uint32_t)b), tmp)->subOp =
1010 NV50_IR_SUBOP_XMAD_PSL | NV50_IR_SUBOP_XMAD_H1(0);
1011
1012 return true;
1013 }
1014
1015 return false;
1016 }
1017
1018 bool
1019 ConstantFolding::opnd(Instruction *i, ImmediateValue &imm0, int s)
1020 {
1021 const int t = !s;
1022 const operation op = i->op;
1023 Instruction *newi = i;
1024 bool deleted = false;
1025
1026 switch (i->op) {
1027 case OP_SPLIT: {
1028 bld.setPosition(i, false);
1029
1030 uint8_t size = i->getDef(0)->reg.size;
1031 uint8_t bitsize = size * 8;
1032 uint32_t mask = (1ULL << bitsize) - 1;
1033 assert(bitsize <= 32);
1034
1035 uint64_t val = imm0.reg.data.u64;
1036 for (int8_t d = 0; i->defExists(d); ++d) {
1037 Value *def = i->getDef(d);
1038 assert(def->reg.size == size);
1039
1040 newi = bld.mkMov(def, bld.mkImm((uint32_t)(val & mask)), TYPE_U32);
1041 val >>= bitsize;
1042 }
1043 delete_Instruction(prog, i);
1044 deleted = true;
1045 break;
1046 }
1047 case OP_MUL:
1048 if (i->dType == TYPE_F32 && !i->precise)
1049 tryCollapseChainedMULs(i, s, imm0);
1050
1051 if (i->subOp == NV50_IR_SUBOP_MUL_HIGH) {
1052 assert(!isFloatType(i->sType));
1053 if (imm0.isInteger(1) && i->dType == TYPE_S32) {
1054 bld.setPosition(i, false);
1055 // Need to set to the sign value, which is a compare.
1056 newi = bld.mkCmp(OP_SET, CC_LT, TYPE_S32, i->getDef(0),
1057 TYPE_S32, i->getSrc(t), bld.mkImm(0));
1058 delete_Instruction(prog, i);
1059 deleted = true;
1060 } else if (imm0.isInteger(0) || imm0.isInteger(1)) {
1061 // The high bits can't be set in this case (either mul by 0 or
1062 // unsigned by 1)
1063 i->op = OP_MOV;
1064 i->subOp = 0;
1065 i->setSrc(0, new_ImmediateValue(prog, 0u));
1066 i->src(0).mod = Modifier(0);
1067 i->setSrc(1, NULL);
1068 } else if (!imm0.isNegative() && imm0.isPow2()) {
1069 // Translate into a shift
1070 imm0.applyLog2();
1071 i->op = OP_SHR;
1072 i->subOp = 0;
1073 imm0.reg.data.u32 = 32 - imm0.reg.data.u32;
1074 i->setSrc(0, i->getSrc(t));
1075 i->src(0).mod = i->src(t).mod;
1076 i->setSrc(1, new_ImmediateValue(prog, imm0.reg.data.u32));
1077 i->src(1).mod = 0;
1078 }
1079 } else
1080 if (imm0.isInteger(0)) {
1081 i->op = OP_MOV;
1082 i->setSrc(0, new_ImmediateValue(prog, 0u));
1083 i->src(0).mod = Modifier(0);
1084 i->postFactor = 0;
1085 i->setSrc(1, NULL);
1086 } else
1087 if (!i->postFactor && (imm0.isInteger(1) || imm0.isInteger(-1))) {
1088 if (imm0.isNegative())
1089 i->src(t).mod = i->src(t).mod ^ Modifier(NV50_IR_MOD_NEG);
1090 i->op = i->src(t).mod.getOp();
1091 if (s == 0) {
1092 i->setSrc(0, i->getSrc(1));
1093 i->src(0).mod = i->src(1).mod;
1094 i->src(1).mod = 0;
1095 }
1096 if (i->op != OP_CVT)
1097 i->src(0).mod = 0;
1098 i->setSrc(1, NULL);
1099 } else
1100 if (!i->postFactor && (imm0.isInteger(2) || imm0.isInteger(-2))) {
1101 if (imm0.isNegative())
1102 i->src(t).mod = i->src(t).mod ^ Modifier(NV50_IR_MOD_NEG);
1103 i->op = OP_ADD;
1104 i->dnz = 0;
1105 i->setSrc(s, i->getSrc(t));
1106 i->src(s).mod = i->src(t).mod;
1107 } else
1108 if (!isFloatType(i->dType) && !i->src(t).mod) {
1109 bld.setPosition(i, false);
1110 int64_t b = typeSizeof(i->dType) == 8 ? imm0.reg.data.s64 : imm0.reg.data.s32;
1111 if (createMul(i->dType, i->getDef(0), i->getSrc(t), b, NULL)) {
1112 delete_Instruction(prog, i);
1113 deleted = true;
1114 }
1115 } else
1116 if (i->postFactor && i->sType == TYPE_F32) {
1117 /* Can't emit a postfactor with an immediate, have to fold it in */
1118 i->setSrc(s, new_ImmediateValue(
1119 prog, imm0.reg.data.f32 * exp2f(i->postFactor)));
1120 i->postFactor = 0;
1121 }
1122 break;
1123 case OP_FMA:
1124 case OP_MAD:
1125 if (imm0.isInteger(0)) {
1126 i->setSrc(0, i->getSrc(2));
1127 i->src(0).mod = i->src(2).mod;
1128 i->setSrc(1, NULL);
1129 i->setSrc(2, NULL);
1130 i->op = i->src(0).mod.getOp();
1131 if (i->op != OP_CVT)
1132 i->src(0).mod = 0;
1133 } else
1134 if (i->subOp != NV50_IR_SUBOP_MUL_HIGH &&
1135 (imm0.isInteger(1) || imm0.isInteger(-1))) {
1136 if (imm0.isNegative())
1137 i->src(t).mod = i->src(t).mod ^ Modifier(NV50_IR_MOD_NEG);
1138 if (s == 0) {
1139 i->setSrc(0, i->getSrc(1));
1140 i->src(0).mod = i->src(1).mod;
1141 }
1142 i->setSrc(1, i->getSrc(2));
1143 i->src(1).mod = i->src(2).mod;
1144 i->setSrc(2, NULL);
1145 i->dnz = 0;
1146 i->op = OP_ADD;
1147 } else
1148 if (!isFloatType(i->dType) && !i->subOp && !i->src(t).mod && !i->src(2).mod) {
1149 bld.setPosition(i, false);
1150 int64_t b = typeSizeof(i->dType) == 8 ? imm0.reg.data.s64 : imm0.reg.data.s32;
1151 if (createMul(i->dType, i->getDef(0), i->getSrc(t), b, i->getSrc(2))) {
1152 delete_Instruction(prog, i);
1153 deleted = true;
1154 }
1155 }
1156 break;
1157 case OP_SUB:
1158 if (imm0.isInteger(0) && s == 0 && typeSizeof(i->dType) == 8 &&
1159 !isFloatType(i->dType))
1160 break;
1161 /* fallthrough */
1162 case OP_ADD:
1163 if (i->usesFlags())
1164 break;
1165 if (imm0.isInteger(0)) {
1166 if (s == 0) {
1167 i->setSrc(0, i->getSrc(1));
1168 i->src(0).mod = i->src(1).mod;
1169 if (i->op == OP_SUB)
1170 i->src(0).mod = i->src(0).mod ^ Modifier(NV50_IR_MOD_NEG);
1171 }
1172 i->setSrc(1, NULL);
1173 i->op = i->src(0).mod.getOp();
1174 if (i->op != OP_CVT)
1175 i->src(0).mod = Modifier(0);
1176 }
1177 break;
1178
1179 case OP_DIV:
1180 if (s != 1 || (i->dType != TYPE_S32 && i->dType != TYPE_U32))
1181 break;
1182 bld.setPosition(i, false);
1183 if (imm0.reg.data.u32 == 0) {
1184 break;
1185 } else
1186 if (imm0.reg.data.u32 == 1) {
1187 i->op = OP_MOV;
1188 i->setSrc(1, NULL);
1189 } else
1190 if (i->dType == TYPE_U32 && imm0.isPow2()) {
1191 i->op = OP_SHR;
1192 i->setSrc(1, bld.mkImm(util_logbase2(imm0.reg.data.u32)));
1193 } else
1194 if (i->dType == TYPE_U32) {
1195 Instruction *mul;
1196 Value *tA, *tB;
1197 const uint32_t d = imm0.reg.data.u32;
1198 uint32_t m;
1199 int r, s;
1200 uint32_t l = util_logbase2(d);
1201 if (((uint32_t)1 << l) < d)
1202 ++l;
1203 m = (((uint64_t)1 << 32) * (((uint64_t)1 << l) - d)) / d + 1;
1204 r = l ? 1 : 0;
1205 s = l ? (l - 1) : 0;
1206
1207 tA = bld.getSSA();
1208 tB = bld.getSSA();
1209 mul = bld.mkOp2(OP_MUL, TYPE_U32, tA, i->getSrc(0),
1210 bld.loadImm(NULL, m));
1211 mul->subOp = NV50_IR_SUBOP_MUL_HIGH;
1212 bld.mkOp2(OP_SUB, TYPE_U32, tB, i->getSrc(0), tA);
1213 tA = bld.getSSA();
1214 if (r)
1215 bld.mkOp2(OP_SHR, TYPE_U32, tA, tB, bld.mkImm(r));
1216 else
1217 tA = tB;
1218 tB = s ? bld.getSSA() : i->getDef(0);
1219 newi = bld.mkOp2(OP_ADD, TYPE_U32, tB, mul->getDef(0), tA);
1220 if (s)
1221 bld.mkOp2(OP_SHR, TYPE_U32, i->getDef(0), tB, bld.mkImm(s));
1222
1223 delete_Instruction(prog, i);
1224 deleted = true;
1225 } else
1226 if (imm0.reg.data.s32 == -1) {
1227 i->op = OP_NEG;
1228 i->setSrc(1, NULL);
1229 } else {
1230 LValue *tA, *tB;
1231 LValue *tD;
1232 const int32_t d = imm0.reg.data.s32;
1233 int32_t m;
1234 int32_t l = util_logbase2(static_cast<unsigned>(abs(d)));
1235 if ((1 << l) < abs(d))
1236 ++l;
1237 if (!l)
1238 l = 1;
1239 m = ((uint64_t)1 << (32 + l - 1)) / abs(d) + 1 - ((uint64_t)1 << 32);
1240
1241 tA = bld.getSSA();
1242 tB = bld.getSSA();
1243 bld.mkOp3(OP_MAD, TYPE_S32, tA, i->getSrc(0), bld.loadImm(NULL, m),
1244 i->getSrc(0))->subOp = NV50_IR_SUBOP_MUL_HIGH;
1245 if (l > 1)
1246 bld.mkOp2(OP_SHR, TYPE_S32, tB, tA, bld.mkImm(l - 1));
1247 else
1248 tB = tA;
1249 tA = bld.getSSA();
1250 bld.mkCmp(OP_SET, CC_LT, TYPE_S32, tA, TYPE_S32, i->getSrc(0), bld.mkImm(0));
1251 tD = (d < 0) ? bld.getSSA() : i->getDef(0)->asLValue();
1252 newi = bld.mkOp2(OP_SUB, TYPE_U32, tD, tB, tA);
1253 if (d < 0)
1254 bld.mkOp1(OP_NEG, TYPE_S32, i->getDef(0), tB);
1255
1256 delete_Instruction(prog, i);
1257 deleted = true;
1258 }
1259 break;
1260
1261 case OP_MOD:
1262 if (s == 1 && imm0.isPow2()) {
1263 bld.setPosition(i, false);
1264 if (i->sType == TYPE_U32) {
1265 i->op = OP_AND;
1266 i->setSrc(1, bld.loadImm(NULL, imm0.reg.data.u32 - 1));
1267 } else if (i->sType == TYPE_S32) {
1268 // Do it on the absolute value of the input, and then restore the
1269 // sign. The only odd case is MIN_INT, but that should work out
1270 // as well, since MIN_INT mod any power of 2 is 0.
1271 //
1272 // Technically we don't have to do any of this since MOD is
1273 // undefined with negative arguments in GLSL, but this seems like
1274 // the nice thing to do.
1275 Value *abs = bld.mkOp1v(OP_ABS, TYPE_S32, bld.getSSA(), i->getSrc(0));
1276 Value *neg, *v1, *v2;
1277 bld.mkCmp(OP_SET, CC_LT, TYPE_S32,
1278 (neg = bld.getSSA(1, prog->getTarget()->nativeFile(FILE_PREDICATE))),
1279 TYPE_S32, i->getSrc(0), bld.loadImm(NULL, 0));
1280 Value *mod = bld.mkOp2v(OP_AND, TYPE_U32, bld.getSSA(), abs,
1281 bld.loadImm(NULL, imm0.reg.data.u32 - 1));
1282 bld.mkOp1(OP_NEG, TYPE_S32, (v1 = bld.getSSA()), mod)
1283 ->setPredicate(CC_P, neg);
1284 bld.mkOp1(OP_MOV, TYPE_S32, (v2 = bld.getSSA()), mod)
1285 ->setPredicate(CC_NOT_P, neg);
1286 newi = bld.mkOp2(OP_UNION, TYPE_S32, i->getDef(0), v1, v2);
1287
1288 delete_Instruction(prog, i);
1289 deleted = true;
1290 }
1291 } else if (s == 1) {
1292 // In this case, we still want the optimized lowering that we get
1293 // from having division by an immediate.
1294 //
1295 // a % b == a - (a/b) * b
1296 bld.setPosition(i, false);
1297 Value *div = bld.mkOp2v(OP_DIV, i->sType, bld.getSSA(),
1298 i->getSrc(0), i->getSrc(1));
1299 newi = bld.mkOp2(OP_ADD, i->sType, i->getDef(0), i->getSrc(0),
1300 bld.mkOp2v(OP_MUL, i->sType, bld.getSSA(), div, i->getSrc(1)));
1301 // TODO: Check that target supports this. In this case, we know that
1302 // all backends do.
1303 newi->src(1).mod = Modifier(NV50_IR_MOD_NEG);
1304
1305 delete_Instruction(prog, i);
1306 deleted = true;
1307 }
1308 break;
1309
1310 case OP_SET: // TODO: SET_AND,OR,XOR
1311 {
1312 /* This optimizes the case where the output of a set is being compared
1313 * to zero. Since the set can only produce 0/-1 (int) or 0/1 (float), we
1314 * can be a lot cleverer in our comparison.
1315 */
1316 CmpInstruction *si = findOriginForTestWithZero(i->getSrc(t));
1317 CondCode cc, ccZ;
1318 if (imm0.reg.data.u32 != 0 || !si)
1319 return false;
1320 cc = si->setCond;
1321 ccZ = (CondCode)((unsigned int)i->asCmp()->setCond & ~CC_U);
1322 // We do everything assuming var (cmp) 0, reverse the condition if 0 is
1323 // first.
1324 if (s == 0)
1325 ccZ = reverseCondCode(ccZ);
1326 // If there is a negative modifier, we need to undo that, by flipping
1327 // the comparison to zero.
1328 if (i->src(t).mod.neg())
1329 ccZ = reverseCondCode(ccZ);
1330 // If this is a signed comparison, we expect the input to be a regular
1331 // boolean, i.e. 0/-1. However the rest of the logic assumes that true
1332 // is positive, so just flip the sign.
1333 if (i->sType == TYPE_S32) {
1334 assert(!isFloatType(si->dType));
1335 ccZ = reverseCondCode(ccZ);
1336 }
1337 switch (ccZ) {
1338 case CC_LT: cc = CC_FL; break; // bool < 0 -- this is never true
1339 case CC_GE: cc = CC_TR; break; // bool >= 0 -- this is always true
1340 case CC_EQ: cc = inverseCondCode(cc); break; // bool == 0 -- !bool
1341 case CC_LE: cc = inverseCondCode(cc); break; // bool <= 0 -- !bool
1342 case CC_GT: break; // bool > 0 -- bool
1343 case CC_NE: break; // bool != 0 -- bool
1344 default:
1345 return false;
1346 }
1347
1348 // Update the condition of this SET to be identical to the origin set,
1349 // but with the updated condition code. The original SET should get
1350 // DCE'd, ideally.
1351 i->op = si->op;
1352 i->asCmp()->setCond = cc;
1353 i->setSrc(0, si->src(0));
1354 i->setSrc(1, si->src(1));
1355 if (si->srcExists(2))
1356 i->setSrc(2, si->src(2));
1357 i->sType = si->sType;
1358 }
1359 break;
1360
1361 case OP_AND:
1362 {
1363 Instruction *src = i->getSrc(t)->getInsn();
1364 ImmediateValue imm1;
1365 if (imm0.reg.data.u32 == 0) {
1366 i->op = OP_MOV;
1367 i->setSrc(0, new_ImmediateValue(prog, 0u));
1368 i->src(0).mod = Modifier(0);
1369 i->setSrc(1, NULL);
1370 } else if (imm0.reg.data.u32 == ~0U) {
1371 i->op = i->src(t).mod.getOp();
1372 if (t) {
1373 i->setSrc(0, i->getSrc(t));
1374 i->src(0).mod = i->src(t).mod;
1375 }
1376 i->setSrc(1, NULL);
1377 } else if (src->asCmp()) {
1378 CmpInstruction *cmp = src->asCmp();
1379 if (!cmp || cmp->op == OP_SLCT || cmp->getDef(0)->refCount() > 1)
1380 return false;
1381 if (!prog->getTarget()->isOpSupported(cmp->op, TYPE_F32))
1382 return false;
1383 if (imm0.reg.data.f32 != 1.0)
1384 return false;
1385 if (cmp->dType != TYPE_U32)
1386 return false;
1387
1388 cmp->dType = TYPE_F32;
1389 if (i->src(t).mod != Modifier(0)) {
1390 assert(i->src(t).mod == Modifier(NV50_IR_MOD_NOT));
1391 i->src(t).mod = Modifier(0);
1392 cmp->setCond = inverseCondCode(cmp->setCond);
1393 }
1394 i->op = OP_MOV;
1395 i->setSrc(s, NULL);
1396 if (t) {
1397 i->setSrc(0, i->getSrc(t));
1398 i->setSrc(t, NULL);
1399 }
1400 } else if (prog->getTarget()->isOpSupported(OP_EXTBF, TYPE_U32) &&
1401 src->op == OP_SHR &&
1402 src->src(1).getImmediate(imm1) &&
1403 i->src(t).mod == Modifier(0) &&
1404 util_is_power_of_two_or_zero(imm0.reg.data.u32 + 1)) {
1405 // low byte = offset, high byte = width
1406 uint32_t ext = (util_last_bit(imm0.reg.data.u32) << 8) | imm1.reg.data.u32;
1407 i->op = OP_EXTBF;
1408 i->setSrc(0, src->getSrc(0));
1409 i->setSrc(1, new_ImmediateValue(prog, ext));
1410 } else if (src->op == OP_SHL &&
1411 src->src(1).getImmediate(imm1) &&
1412 i->src(t).mod == Modifier(0) &&
1413 util_is_power_of_two_or_zero(~imm0.reg.data.u32 + 1) &&
1414 util_last_bit(~imm0.reg.data.u32) <= imm1.reg.data.u32) {
1415 i->op = OP_MOV;
1416 i->setSrc(s, NULL);
1417 if (t) {
1418 i->setSrc(0, i->getSrc(t));
1419 i->setSrc(t, NULL);
1420 }
1421 }
1422 }
1423 break;
1424
1425 case OP_SHL:
1426 {
1427 if (s != 1 || i->src(0).mod != Modifier(0))
1428 break;
1429 // try to concatenate shifts
1430 Instruction *si = i->getSrc(0)->getInsn();
1431 if (!si)
1432 break;
1433 ImmediateValue imm1;
1434 switch (si->op) {
1435 case OP_SHL:
1436 if (si->src(1).getImmediate(imm1)) {
1437 bld.setPosition(i, false);
1438 i->setSrc(0, si->getSrc(0));
1439 i->setSrc(1, bld.loadImm(NULL, imm0.reg.data.u32 + imm1.reg.data.u32));
1440 }
1441 break;
1442 case OP_SHR:
1443 if (si->src(1).getImmediate(imm1) && imm0.reg.data.u32 == imm1.reg.data.u32) {
1444 bld.setPosition(i, false);
1445 i->op = OP_AND;
1446 i->setSrc(0, si->getSrc(0));
1447 i->setSrc(1, bld.loadImm(NULL, ~((1 << imm0.reg.data.u32) - 1)));
1448 }
1449 break;
1450 case OP_MUL:
1451 int muls;
1452 if (isFloatType(si->dType))
1453 return false;
1454 if (si->src(1).getImmediate(imm1))
1455 muls = 1;
1456 else if (si->src(0).getImmediate(imm1))
1457 muls = 0;
1458 else
1459 return false;
1460
1461 bld.setPosition(i, false);
1462 i->op = OP_MUL;
1463 i->setSrc(0, si->getSrc(!muls));
1464 i->setSrc(1, bld.loadImm(NULL, imm1.reg.data.u32 << imm0.reg.data.u32));
1465 break;
1466 case OP_SUB:
1467 case OP_ADD:
1468 int adds;
1469 if (isFloatType(si->dType))
1470 return false;
1471 if (si->op != OP_SUB && si->src(0).getImmediate(imm1))
1472 adds = 0;
1473 else if (si->src(1).getImmediate(imm1))
1474 adds = 1;
1475 else
1476 return false;
1477 if (si->src(!adds).mod != Modifier(0))
1478 return false;
1479 // SHL(ADD(x, y), z) = ADD(SHL(x, z), SHL(y, z))
1480
1481 // This is more operations, but if one of x, y is an immediate, then
1482 // we can get a situation where (a) we can use ISCADD, or (b)
1483 // propagate the add bit into an indirect load.
1484 bld.setPosition(i, false);
1485 i->op = si->op;
1486 i->setSrc(adds, bld.loadImm(NULL, imm1.reg.data.u32 << imm0.reg.data.u32));
1487 i->setSrc(!adds, bld.mkOp2v(OP_SHL, i->dType,
1488 bld.getSSA(i->def(0).getSize(), i->def(0).getFile()),
1489 si->getSrc(!adds),
1490 bld.mkImm(imm0.reg.data.u32)));
1491 break;
1492 default:
1493 return false;
1494 }
1495 }
1496 break;
1497
1498 case OP_ABS:
1499 case OP_NEG:
1500 case OP_SAT:
1501 case OP_LG2:
1502 case OP_RCP:
1503 case OP_SQRT:
1504 case OP_RSQ:
1505 case OP_PRESIN:
1506 case OP_SIN:
1507 case OP_COS:
1508 case OP_PREEX2:
1509 case OP_EX2:
1510 unary(i, imm0);
1511 break;
1512 case OP_BFIND: {
1513 int32_t res;
1514 switch (i->dType) {
1515 case TYPE_S32: res = util_last_bit_signed(imm0.reg.data.s32) - 1; break;
1516 case TYPE_U32: res = util_last_bit(imm0.reg.data.u32) - 1; break;
1517 default:
1518 return false;
1519 }
1520 if (i->subOp == NV50_IR_SUBOP_BFIND_SAMT && res >= 0)
1521 res = 31 - res;
1522 bld.setPosition(i, false); /* make sure bld is init'ed */
1523 i->setSrc(0, bld.mkImm(res));
1524 i->setSrc(1, NULL);
1525 i->op = OP_MOV;
1526 i->subOp = 0;
1527 break;
1528 }
1529 case OP_POPCNT: {
1530 // Only deal with 1-arg POPCNT here
1531 if (i->srcExists(1))
1532 break;
1533 uint32_t res = util_bitcount(imm0.reg.data.u32);
1534 i->setSrc(0, new_ImmediateValue(i->bb->getProgram(), res));
1535 i->setSrc(1, NULL);
1536 i->op = OP_MOV;
1537 break;
1538 }
1539 case OP_CVT: {
1540 Storage res;
1541
1542 // TODO: handle 64-bit values properly
1543 if (typeSizeof(i->dType) == 8 || typeSizeof(i->sType) == 8)
1544 return false;
1545
1546 // TODO: handle single byte/word extractions
1547 if (i->subOp)
1548 return false;
1549
1550 bld.setPosition(i, true); /* make sure bld is init'ed */
1551
1552 #define CASE(type, dst, fmin, fmax, imin, imax, umin, umax) \
1553 case type: \
1554 switch (i->sType) { \
1555 case TYPE_F64: \
1556 res.data.dst = util_iround(i->saturate ? \
1557 CLAMP(imm0.reg.data.f64, fmin, fmax) : \
1558 imm0.reg.data.f64); \
1559 break; \
1560 case TYPE_F32: \
1561 res.data.dst = util_iround(i->saturate ? \
1562 CLAMP(imm0.reg.data.f32, fmin, fmax) : \
1563 imm0.reg.data.f32); \
1564 break; \
1565 case TYPE_S32: \
1566 res.data.dst = i->saturate ? \
1567 CLAMP(imm0.reg.data.s32, imin, imax) : \
1568 imm0.reg.data.s32; \
1569 break; \
1570 case TYPE_U32: \
1571 res.data.dst = i->saturate ? \
1572 CLAMP(imm0.reg.data.u32, umin, umax) : \
1573 imm0.reg.data.u32; \
1574 break; \
1575 case TYPE_S16: \
1576 res.data.dst = i->saturate ? \
1577 CLAMP(imm0.reg.data.s16, imin, imax) : \
1578 imm0.reg.data.s16; \
1579 break; \
1580 case TYPE_U16: \
1581 res.data.dst = i->saturate ? \
1582 CLAMP(imm0.reg.data.u16, umin, umax) : \
1583 imm0.reg.data.u16; \
1584 break; \
1585 default: return false; \
1586 } \
1587 i->setSrc(0, bld.mkImm(res.data.dst)); \
1588 break
1589
1590 switch(i->dType) {
1591 CASE(TYPE_U16, u16, 0, UINT16_MAX, 0, UINT16_MAX, 0, UINT16_MAX);
1592 CASE(TYPE_S16, s16, INT16_MIN, INT16_MAX, INT16_MIN, INT16_MAX, 0, INT16_MAX);
1593 CASE(TYPE_U32, u32, 0, UINT32_MAX, 0, INT32_MAX, 0, UINT32_MAX);
1594 CASE(TYPE_S32, s32, INT32_MIN, INT32_MAX, INT32_MIN, INT32_MAX, 0, INT32_MAX);
1595 case TYPE_F32:
1596 switch (i->sType) {
1597 case TYPE_F64:
1598 res.data.f32 = i->saturate ?
1599 CLAMP(imm0.reg.data.f64, 0.0f, 1.0f) :
1600 imm0.reg.data.f64;
1601 break;
1602 case TYPE_F32:
1603 res.data.f32 = i->saturate ?
1604 CLAMP(imm0.reg.data.f32, 0.0f, 1.0f) :
1605 imm0.reg.data.f32;
1606 break;
1607 case TYPE_U16: res.data.f32 = (float) imm0.reg.data.u16; break;
1608 case TYPE_U32: res.data.f32 = (float) imm0.reg.data.u32; break;
1609 case TYPE_S16: res.data.f32 = (float) imm0.reg.data.s16; break;
1610 case TYPE_S32: res.data.f32 = (float) imm0.reg.data.s32; break;
1611 default:
1612 return false;
1613 }
1614 i->setSrc(0, bld.mkImm(res.data.f32));
1615 break;
1616 case TYPE_F64:
1617 switch (i->sType) {
1618 case TYPE_F64:
1619 res.data.f64 = i->saturate ?
1620 CLAMP(imm0.reg.data.f64, 0.0f, 1.0f) :
1621 imm0.reg.data.f64;
1622 break;
1623 case TYPE_F32:
1624 res.data.f64 = i->saturate ?
1625 CLAMP(imm0.reg.data.f32, 0.0f, 1.0f) :
1626 imm0.reg.data.f32;
1627 break;
1628 case TYPE_U16: res.data.f64 = (double) imm0.reg.data.u16; break;
1629 case TYPE_U32: res.data.f64 = (double) imm0.reg.data.u32; break;
1630 case TYPE_S16: res.data.f64 = (double) imm0.reg.data.s16; break;
1631 case TYPE_S32: res.data.f64 = (double) imm0.reg.data.s32; break;
1632 default:
1633 return false;
1634 }
1635 i->setSrc(0, bld.mkImm(res.data.f64));
1636 break;
1637 default:
1638 return false;
1639 }
1640 #undef CASE
1641
1642 i->setType(i->dType); /* Remove i->sType, which we don't need anymore */
1643 i->op = OP_MOV;
1644 i->saturate = 0;
1645 i->src(0).mod = Modifier(0); /* Clear the already applied modifier */
1646 break;
1647 }
1648 default:
1649 return false;
1650 }
1651
1652 // This can get left behind some of the optimizations which simplify
1653 // saturatable values.
1654 if (newi->op == OP_MOV && newi->saturate) {
1655 ImmediateValue tmp;
1656 newi->saturate = 0;
1657 newi->op = OP_SAT;
1658 if (newi->src(0).getImmediate(tmp))
1659 unary(newi, tmp);
1660 }
1661
1662 if (newi->op != op)
1663 foldCount++;
1664 return deleted;
1665 }
1666
1667 // =============================================================================
1668
1669 // Merge modifier operations (ABS, NEG, NOT) into ValueRefs where allowed.
1670 class ModifierFolding : public Pass
1671 {
1672 private:
1673 virtual bool visit(BasicBlock *);
1674 };
1675
1676 bool
1677 ModifierFolding::visit(BasicBlock *bb)
1678 {
1679 const Target *target = prog->getTarget();
1680
1681 Instruction *i, *next, *mi;
1682 Modifier mod;
1683
1684 for (i = bb->getEntry(); i; i = next) {
1685 next = i->next;
1686
1687 if (0 && i->op == OP_SUB) {
1688 // turn "sub" into "add neg" (do we really want this ?)
1689 i->op = OP_ADD;
1690 i->src(0).mod = i->src(0).mod ^ Modifier(NV50_IR_MOD_NEG);
1691 }
1692
1693 for (int s = 0; s < 3 && i->srcExists(s); ++s) {
1694 mi = i->getSrc(s)->getInsn();
1695 if (!mi ||
1696 mi->predSrc >= 0 || mi->getDef(0)->refCount() > 8)
1697 continue;
1698 if (i->sType == TYPE_U32 && mi->dType == TYPE_S32) {
1699 if ((i->op != OP_ADD &&
1700 i->op != OP_MUL) ||
1701 (mi->op != OP_ABS &&
1702 mi->op != OP_NEG))
1703 continue;
1704 } else
1705 if (i->sType != mi->dType) {
1706 continue;
1707 }
1708 if ((mod = Modifier(mi->op)) == Modifier(0))
1709 continue;
1710 mod *= mi->src(0).mod;
1711
1712 if ((i->op == OP_ABS) || i->src(s).mod.abs()) {
1713 // abs neg [abs] = abs
1714 mod = mod & Modifier(~(NV50_IR_MOD_NEG | NV50_IR_MOD_ABS));
1715 } else
1716 if ((i->op == OP_NEG) && mod.neg()) {
1717 assert(s == 0);
1718 // neg as both opcode and modifier on same insn is prohibited
1719 // neg neg abs = abs, neg neg = identity
1720 mod = mod & Modifier(~NV50_IR_MOD_NEG);
1721 i->op = mod.getOp();
1722 mod = mod & Modifier(~NV50_IR_MOD_ABS);
1723 if (mod == Modifier(0))
1724 i->op = OP_MOV;
1725 }
1726
1727 if (target->isModSupported(i, s, mod)) {
1728 i->setSrc(s, mi->getSrc(0));
1729 i->src(s).mod *= mod;
1730 }
1731 }
1732
1733 if (i->op == OP_SAT) {
1734 mi = i->getSrc(0)->getInsn();
1735 if (mi &&
1736 mi->getDef(0)->refCount() <= 1 && target->isSatSupported(mi)) {
1737 mi->saturate = 1;
1738 mi->setDef(0, i->getDef(0));
1739 delete_Instruction(prog, i);
1740 }
1741 }
1742 }
1743
1744 return true;
1745 }
1746
1747 // =============================================================================
1748
1749 // MUL + ADD -> MAD/FMA
1750 // MIN/MAX(a, a) -> a, etc.
1751 // SLCT(a, b, const) -> cc(const) ? a : b
1752 // RCP(RCP(a)) -> a
1753 // MUL(MUL(a, b), const) -> MUL_Xconst(a, b)
1754 // EXTBF(RDSV(COMBINED_TID)) -> RDSV(TID)
1755 class AlgebraicOpt : public Pass
1756 {
1757 private:
1758 virtual bool visit(BasicBlock *);
1759
1760 void handleABS(Instruction *);
1761 bool handleADD(Instruction *);
1762 bool tryADDToMADOrSAD(Instruction *, operation toOp);
1763 void handleMINMAX(Instruction *);
1764 void handleRCP(Instruction *);
1765 void handleSLCT(Instruction *);
1766 void handleLOGOP(Instruction *);
1767 void handleCVT_NEG(Instruction *);
1768 void handleCVT_CVT(Instruction *);
1769 void handleCVT_EXTBF(Instruction *);
1770 void handleSUCLAMP(Instruction *);
1771 void handleNEG(Instruction *);
1772 void handleEXTBF_RDSV(Instruction *);
1773
1774 BuildUtil bld;
1775 };
1776
1777 void
1778 AlgebraicOpt::handleABS(Instruction *abs)
1779 {
1780 Instruction *sub = abs->getSrc(0)->getInsn();
1781 DataType ty;
1782 if (!sub ||
1783 !prog->getTarget()->isOpSupported(OP_SAD, abs->dType))
1784 return;
1785 // expect not to have mods yet, if we do, bail
1786 if (sub->src(0).mod || sub->src(1).mod)
1787 return;
1788 // hidden conversion ?
1789 ty = intTypeToSigned(sub->dType);
1790 if (abs->dType != abs->sType || ty != abs->sType)
1791 return;
1792
1793 if ((sub->op != OP_ADD && sub->op != OP_SUB) ||
1794 sub->src(0).getFile() != FILE_GPR || sub->src(0).mod ||
1795 sub->src(1).getFile() != FILE_GPR || sub->src(1).mod)
1796 return;
1797
1798 Value *src0 = sub->getSrc(0);
1799 Value *src1 = sub->getSrc(1);
1800
1801 if (sub->op == OP_ADD) {
1802 Instruction *neg = sub->getSrc(1)->getInsn();
1803 if (neg && neg->op != OP_NEG) {
1804 neg = sub->getSrc(0)->getInsn();
1805 src0 = sub->getSrc(1);
1806 }
1807 if (!neg || neg->op != OP_NEG ||
1808 neg->dType != neg->sType || neg->sType != ty)
1809 return;
1810 src1 = neg->getSrc(0);
1811 }
1812
1813 // found ABS(SUB))
1814 abs->moveSources(1, 2); // move sources >=1 up by 2
1815 abs->op = OP_SAD;
1816 abs->setType(sub->dType);
1817 abs->setSrc(0, src0);
1818 abs->setSrc(1, src1);
1819 bld.setPosition(abs, false);
1820 abs->setSrc(2, bld.loadImm(bld.getSSA(typeSizeof(ty)), 0));
1821 }
1822
1823 bool
1824 AlgebraicOpt::handleADD(Instruction *add)
1825 {
1826 Value *src0 = add->getSrc(0);
1827 Value *src1 = add->getSrc(1);
1828
1829 if (src0->reg.file != FILE_GPR || src1->reg.file != FILE_GPR)
1830 return false;
1831
1832 bool changed = false;
1833 // we can't optimize to MAD if the add is precise
1834 if (!add->precise && prog->getTarget()->isOpSupported(OP_MAD, add->dType))
1835 changed = tryADDToMADOrSAD(add, OP_MAD);
1836 if (!changed && prog->getTarget()->isOpSupported(OP_SAD, add->dType))
1837 changed = tryADDToMADOrSAD(add, OP_SAD);
1838 return changed;
1839 }
1840
1841 // ADD(SAD(a,b,0), c) -> SAD(a,b,c)
1842 // ADD(MUL(a,b), c) -> MAD(a,b,c)
1843 bool
1844 AlgebraicOpt::tryADDToMADOrSAD(Instruction *add, operation toOp)
1845 {
1846 Value *src0 = add->getSrc(0);
1847 Value *src1 = add->getSrc(1);
1848 Value *src;
1849 int s;
1850 const operation srcOp = toOp == OP_SAD ? OP_SAD : OP_MUL;
1851 const Modifier modBad = Modifier(~((toOp == OP_MAD) ? NV50_IR_MOD_NEG : 0));
1852 Modifier mod[4];
1853
1854 if (src0->refCount() == 1 &&
1855 src0->getUniqueInsn() && src0->getUniqueInsn()->op == srcOp)
1856 s = 0;
1857 else
1858 if (src1->refCount() == 1 &&
1859 src1->getUniqueInsn() && src1->getUniqueInsn()->op == srcOp)
1860 s = 1;
1861 else
1862 return false;
1863
1864 src = add->getSrc(s);
1865
1866 if (src->getUniqueInsn() && src->getUniqueInsn()->bb != add->bb)
1867 return false;
1868
1869 if (src->getInsn()->saturate || src->getInsn()->postFactor ||
1870 src->getInsn()->dnz || src->getInsn()->precise)
1871 return false;
1872
1873 if (toOp == OP_SAD) {
1874 ImmediateValue imm;
1875 if (!src->getInsn()->src(2).getImmediate(imm))
1876 return false;
1877 if (!imm.isInteger(0))
1878 return false;
1879 }
1880
1881 if (typeSizeof(add->dType) != typeSizeof(src->getInsn()->dType) ||
1882 isFloatType(add->dType) != isFloatType(src->getInsn()->dType))
1883 return false;
1884
1885 mod[0] = add->src(0).mod;
1886 mod[1] = add->src(1).mod;
1887 mod[2] = src->getUniqueInsn()->src(0).mod;
1888 mod[3] = src->getUniqueInsn()->src(1).mod;
1889
1890 if (((mod[0] | mod[1]) | (mod[2] | mod[3])) & modBad)
1891 return false;
1892
1893 add->op = toOp;
1894 add->subOp = src->getInsn()->subOp; // potentially mul-high
1895 add->dnz = src->getInsn()->dnz;
1896 add->dType = src->getInsn()->dType; // sign matters for imad hi
1897 add->sType = src->getInsn()->sType;
1898
1899 add->setSrc(2, add->src(s ? 0 : 1));
1900
1901 add->setSrc(0, src->getInsn()->getSrc(0));
1902 add->src(0).mod = mod[2] ^ mod[s];
1903 add->setSrc(1, src->getInsn()->getSrc(1));
1904 add->src(1).mod = mod[3];
1905
1906 return true;
1907 }
1908
1909 void
1910 AlgebraicOpt::handleMINMAX(Instruction *minmax)
1911 {
1912 Value *src0 = minmax->getSrc(0);
1913 Value *src1 = minmax->getSrc(1);
1914
1915 if (src0 != src1 || src0->reg.file != FILE_GPR)
1916 return;
1917 if (minmax->src(0).mod == minmax->src(1).mod) {
1918 if (minmax->def(0).mayReplace(minmax->src(0))) {
1919 minmax->def(0).replace(minmax->src(0), false);
1920 delete_Instruction(prog, minmax);
1921 } else {
1922 minmax->op = OP_CVT;
1923 minmax->setSrc(1, NULL);
1924 }
1925 } else {
1926 // TODO:
1927 // min(x, -x) = -abs(x)
1928 // min(x, -abs(x)) = -abs(x)
1929 // min(x, abs(x)) = x
1930 // max(x, -abs(x)) = x
1931 // max(x, abs(x)) = abs(x)
1932 // max(x, -x) = abs(x)
1933 }
1934 }
1935
1936 // rcp(rcp(a)) = a
1937 // rcp(sqrt(a)) = rsq(a)
1938 void
1939 AlgebraicOpt::handleRCP(Instruction *rcp)
1940 {
1941 Instruction *si = rcp->getSrc(0)->getUniqueInsn();
1942
1943 if (!si)
1944 return;
1945
1946 if (si->op == OP_RCP) {
1947 Modifier mod = rcp->src(0).mod * si->src(0).mod;
1948 rcp->op = mod.getOp();
1949 rcp->setSrc(0, si->getSrc(0));
1950 } else if (si->op == OP_SQRT) {
1951 rcp->op = OP_RSQ;
1952 rcp->setSrc(0, si->getSrc(0));
1953 rcp->src(0).mod = rcp->src(0).mod * si->src(0).mod;
1954 }
1955 }
1956
1957 void
1958 AlgebraicOpt::handleSLCT(Instruction *slct)
1959 {
1960 if (slct->getSrc(2)->reg.file == FILE_IMMEDIATE) {
1961 if (slct->getSrc(2)->asImm()->compare(slct->asCmp()->setCond, 0.0f))
1962 slct->setSrc(0, slct->getSrc(1));
1963 } else
1964 if (slct->getSrc(0) != slct->getSrc(1)) {
1965 return;
1966 }
1967 slct->op = OP_MOV;
1968 slct->setSrc(1, NULL);
1969 slct->setSrc(2, NULL);
1970 }
1971
1972 void
1973 AlgebraicOpt::handleLOGOP(Instruction *logop)
1974 {
1975 Value *src0 = logop->getSrc(0);
1976 Value *src1 = logop->getSrc(1);
1977
1978 if (src0->reg.file != FILE_GPR || src1->reg.file != FILE_GPR)
1979 return;
1980
1981 if (src0 == src1) {
1982 if ((logop->op == OP_AND || logop->op == OP_OR) &&
1983 logop->def(0).mayReplace(logop->src(0))) {
1984 logop->def(0).replace(logop->src(0), false);
1985 delete_Instruction(prog, logop);
1986 }
1987 } else {
1988 // try AND(SET, SET) -> SET_AND(SET)
1989 Instruction *set0 = src0->getInsn();
1990 Instruction *set1 = src1->getInsn();
1991
1992 if (!set0 || set0->fixed || !set1 || set1->fixed)
1993 return;
1994 if (set1->op != OP_SET) {
1995 Instruction *xchg = set0;
1996 set0 = set1;
1997 set1 = xchg;
1998 if (set1->op != OP_SET)
1999 return;
2000 }
2001 operation redOp = (logop->op == OP_AND ? OP_SET_AND :
2002 logop->op == OP_XOR ? OP_SET_XOR : OP_SET_OR);
2003 if (!prog->getTarget()->isOpSupported(redOp, set1->sType))
2004 return;
2005 if (set0->op != OP_SET &&
2006 set0->op != OP_SET_AND &&
2007 set0->op != OP_SET_OR &&
2008 set0->op != OP_SET_XOR)
2009 return;
2010 if (set0->getDef(0)->refCount() > 1 &&
2011 set1->getDef(0)->refCount() > 1)
2012 return;
2013 if (set0->getPredicate() || set1->getPredicate())
2014 return;
2015 // check that they don't source each other
2016 for (int s = 0; s < 2; ++s)
2017 if (set0->getSrc(s) == set1->getDef(0) ||
2018 set1->getSrc(s) == set0->getDef(0))
2019 return;
2020
2021 set0 = cloneForward(func, set0);
2022 set1 = cloneShallow(func, set1);
2023 logop->bb->insertAfter(logop, set1);
2024 logop->bb->insertAfter(logop, set0);
2025
2026 set0->dType = TYPE_U8;
2027 set0->getDef(0)->reg.file = FILE_PREDICATE;
2028 set0->getDef(0)->reg.size = 1;
2029 set1->setSrc(2, set0->getDef(0));
2030 set1->op = redOp;
2031 set1->setDef(0, logop->getDef(0));
2032 delete_Instruction(prog, logop);
2033 }
2034 }
2035
2036 // F2I(NEG(SET with result 1.0f/0.0f)) -> SET with result -1/0
2037 // nv50:
2038 // F2I(NEG(I2F(ABS(SET))))
2039 void
2040 AlgebraicOpt::handleCVT_NEG(Instruction *cvt)
2041 {
2042 Instruction *insn = cvt->getSrc(0)->getInsn();
2043 if (cvt->sType != TYPE_F32 ||
2044 cvt->dType != TYPE_S32 || cvt->src(0).mod != Modifier(0))
2045 return;
2046 if (!insn || insn->op != OP_NEG || insn->dType != TYPE_F32)
2047 return;
2048 if (insn->src(0).mod != Modifier(0))
2049 return;
2050 insn = insn->getSrc(0)->getInsn();
2051
2052 // check for nv50 SET(-1,0) -> SET(1.0f/0.0f) chain and nvc0's f32 SET
2053 if (insn && insn->op == OP_CVT &&
2054 insn->dType == TYPE_F32 &&
2055 insn->sType == TYPE_S32) {
2056 insn = insn->getSrc(0)->getInsn();
2057 if (!insn || insn->op != OP_ABS || insn->sType != TYPE_S32 ||
2058 insn->src(0).mod)
2059 return;
2060 insn = insn->getSrc(0)->getInsn();
2061 if (!insn || insn->op != OP_SET || insn->dType != TYPE_U32)
2062 return;
2063 } else
2064 if (!insn || insn->op != OP_SET || insn->dType != TYPE_F32) {
2065 return;
2066 }
2067
2068 Instruction *bset = cloneShallow(func, insn);
2069 bset->dType = TYPE_U32;
2070 bset->setDef(0, cvt->getDef(0));
2071 cvt->bb->insertAfter(cvt, bset);
2072 delete_Instruction(prog, cvt);
2073 }
2074
2075 // F2I(TRUNC()) and so on can be expressed as a single CVT. If the earlier CVT
2076 // does a type conversion, this becomes trickier as there might be range
2077 // changes/etc. We could handle those in theory as long as the range was being
2078 // reduced or kept the same.
2079 void
2080 AlgebraicOpt::handleCVT_CVT(Instruction *cvt)
2081 {
2082 Instruction *insn = cvt->getSrc(0)->getInsn();
2083 RoundMode rnd = insn->rnd;
2084
2085 if (insn->saturate ||
2086 insn->subOp ||
2087 insn->dType != insn->sType ||
2088 insn->dType != cvt->sType)
2089 return;
2090
2091 switch (insn->op) {
2092 case OP_CEIL:
2093 rnd = ROUND_PI;
2094 break;
2095 case OP_FLOOR:
2096 rnd = ROUND_MI;
2097 break;
2098 case OP_TRUNC:
2099 rnd = ROUND_ZI;
2100 break;
2101 case OP_CVT:
2102 break;
2103 default:
2104 return;
2105 }
2106
2107 if (!isFloatType(cvt->dType) || !isFloatType(insn->sType))
2108 rnd = (RoundMode)(rnd & 3);
2109
2110 cvt->rnd = rnd;
2111 cvt->setSrc(0, insn->getSrc(0));
2112 cvt->src(0).mod *= insn->src(0).mod;
2113 cvt->sType = insn->sType;
2114 }
2115
2116 // Some shaders extract packed bytes out of words and convert them to
2117 // e.g. float. The Fermi+ CVT instruction can extract those directly, as can
2118 // nv50 for word sizes.
2119 //
2120 // CVT(EXTBF(x, byte/word))
2121 // CVT(AND(bytemask, x))
2122 // CVT(AND(bytemask, SHR(x, 8/16/24)))
2123 // CVT(SHR(x, 16/24))
2124 void
2125 AlgebraicOpt::handleCVT_EXTBF(Instruction *cvt)
2126 {
2127 Instruction *insn = cvt->getSrc(0)->getInsn();
2128 ImmediateValue imm;
2129 Value *arg = NULL;
2130 unsigned width, offset;
2131 if ((cvt->sType != TYPE_U32 && cvt->sType != TYPE_S32) || !insn)
2132 return;
2133 if (insn->op == OP_EXTBF && insn->src(1).getImmediate(imm)) {
2134 width = (imm.reg.data.u32 >> 8) & 0xff;
2135 offset = imm.reg.data.u32 & 0xff;
2136 arg = insn->getSrc(0);
2137
2138 if (width != 8 && width != 16)
2139 return;
2140 if (width == 8 && offset & 0x7)
2141 return;
2142 if (width == 16 && offset & 0xf)
2143 return;
2144 } else if (insn->op == OP_AND) {
2145 int s;
2146 if (insn->src(0).getImmediate(imm))
2147 s = 0;
2148 else if (insn->src(1).getImmediate(imm))
2149 s = 1;
2150 else
2151 return;
2152
2153 if (imm.reg.data.u32 == 0xff)
2154 width = 8;
2155 else if (imm.reg.data.u32 == 0xffff)
2156 width = 16;
2157 else
2158 return;
2159
2160 arg = insn->getSrc(!s);
2161 Instruction *shift = arg->getInsn();
2162 offset = 0;
2163 if (shift && shift->op == OP_SHR &&
2164 shift->sType == cvt->sType &&
2165 shift->src(1).getImmediate(imm) &&
2166 ((width == 8 && (imm.reg.data.u32 & 0x7) == 0) ||
2167 (width == 16 && (imm.reg.data.u32 & 0xf) == 0))) {
2168 arg = shift->getSrc(0);
2169 offset = imm.reg.data.u32;
2170 }
2171 // We just AND'd the high bits away, which means this is effectively an
2172 // unsigned value.
2173 cvt->sType = TYPE_U32;
2174 } else if (insn->op == OP_SHR &&
2175 insn->sType == cvt->sType &&
2176 insn->src(1).getImmediate(imm)) {
2177 arg = insn->getSrc(0);
2178 if (imm.reg.data.u32 == 24) {
2179 width = 8;
2180 offset = 24;
2181 } else if (imm.reg.data.u32 == 16) {
2182 width = 16;
2183 offset = 16;
2184 } else {
2185 return;
2186 }
2187 }
2188
2189 if (!arg)
2190 return;
2191
2192 // Irrespective of what came earlier, we can undo a shift on the argument
2193 // by adjusting the offset.
2194 Instruction *shift = arg->getInsn();
2195 if (shift && shift->op == OP_SHL &&
2196 shift->src(1).getImmediate(imm) &&
2197 ((width == 8 && (imm.reg.data.u32 & 0x7) == 0) ||
2198 (width == 16 && (imm.reg.data.u32 & 0xf) == 0)) &&
2199 imm.reg.data.u32 <= offset) {
2200 arg = shift->getSrc(0);
2201 offset -= imm.reg.data.u32;
2202 }
2203
2204 // The unpackSnorm lowering still leaves a few shifts behind, but it's too
2205 // annoying to detect them.
2206
2207 if (width == 8) {
2208 cvt->sType = cvt->sType == TYPE_U32 ? TYPE_U8 : TYPE_S8;
2209 } else {
2210 assert(width == 16);
2211 cvt->sType = cvt->sType == TYPE_U32 ? TYPE_U16 : TYPE_S16;
2212 }
2213 cvt->setSrc(0, arg);
2214 cvt->subOp = offset >> 3;
2215 }
2216
2217 // SUCLAMP dst, (ADD b imm), k, 0 -> SUCLAMP dst, b, k, imm (if imm fits s6)
2218 void
2219 AlgebraicOpt::handleSUCLAMP(Instruction *insn)
2220 {
2221 ImmediateValue imm;
2222 int32_t val = insn->getSrc(2)->asImm()->reg.data.s32;
2223 int s;
2224 Instruction *add;
2225
2226 assert(insn->srcExists(0) && insn->src(0).getFile() == FILE_GPR);
2227
2228 // look for ADD (TODO: only count references by non-SUCLAMP)
2229 if (insn->getSrc(0)->refCount() > 1)
2230 return;
2231 add = insn->getSrc(0)->getInsn();
2232 if (!add || add->op != OP_ADD ||
2233 (add->dType != TYPE_U32 &&
2234 add->dType != TYPE_S32))
2235 return;
2236
2237 // look for immediate
2238 for (s = 0; s < 2; ++s)
2239 if (add->src(s).getImmediate(imm))
2240 break;
2241 if (s >= 2)
2242 return;
2243 s = s ? 0 : 1;
2244 // determine if immediate fits
2245 val += imm.reg.data.s32;
2246 if (val > 31 || val < -32)
2247 return;
2248 // determine if other addend fits
2249 if (add->src(s).getFile() != FILE_GPR || add->src(s).mod != Modifier(0))
2250 return;
2251
2252 bld.setPosition(insn, false); // make sure bld is init'ed
2253 // replace sources
2254 insn->setSrc(2, bld.mkImm(val));
2255 insn->setSrc(0, add->getSrc(s));
2256 }
2257
2258 // NEG(AND(SET, 1)) -> SET
2259 void
2260 AlgebraicOpt::handleNEG(Instruction *i) {
2261 Instruction *src = i->getSrc(0)->getInsn();
2262 ImmediateValue imm;
2263 int b;
2264
2265 if (isFloatType(i->sType) || !src || src->op != OP_AND)
2266 return;
2267
2268 if (src->src(0).getImmediate(imm))
2269 b = 1;
2270 else if (src->src(1).getImmediate(imm))
2271 b = 0;
2272 else
2273 return;
2274
2275 if (!imm.isInteger(1))
2276 return;
2277
2278 Instruction *set = src->getSrc(b)->getInsn();
2279 if ((set->op == OP_SET || set->op == OP_SET_AND ||
2280 set->op == OP_SET_OR || set->op == OP_SET_XOR) &&
2281 !isFloatType(set->dType)) {
2282 i->def(0).replace(set->getDef(0), false);
2283 }
2284 }
2285
2286 // EXTBF(RDSV(COMBINED_TID)) -> RDSV(TID)
2287 void
2288 AlgebraicOpt::handleEXTBF_RDSV(Instruction *i)
2289 {
2290 Instruction *rdsv = i->getSrc(0)->getUniqueInsn();
2291 if (rdsv->op != OP_RDSV ||
2292 rdsv->getSrc(0)->asSym()->reg.data.sv.sv != SV_COMBINED_TID)
2293 return;
2294 // Avoid creating more RDSV instructions
2295 if (rdsv->getDef(0)->refCount() > 1)
2296 return;
2297
2298 ImmediateValue imm;
2299 if (!i->src(1).getImmediate(imm))
2300 return;
2301
2302 int index;
2303 if (imm.isInteger(0x1000))
2304 index = 0;
2305 else
2306 if (imm.isInteger(0x0a10))
2307 index = 1;
2308 else
2309 if (imm.isInteger(0x061a))
2310 index = 2;
2311 else
2312 return;
2313
2314 bld.setPosition(i, false);
2315
2316 i->op = OP_RDSV;
2317 i->setSrc(0, bld.mkSysVal(SV_TID, index));
2318 i->setSrc(1, NULL);
2319 }
2320
2321 bool
2322 AlgebraicOpt::visit(BasicBlock *bb)
2323 {
2324 Instruction *next;
2325 for (Instruction *i = bb->getEntry(); i; i = next) {
2326 next = i->next;
2327 switch (i->op) {
2328 case OP_ABS:
2329 handleABS(i);
2330 break;
2331 case OP_ADD:
2332 handleADD(i);
2333 break;
2334 case OP_RCP:
2335 handleRCP(i);
2336 break;
2337 case OP_MIN:
2338 case OP_MAX:
2339 handleMINMAX(i);
2340 break;
2341 case OP_SLCT:
2342 handleSLCT(i);
2343 break;
2344 case OP_AND:
2345 case OP_OR:
2346 case OP_XOR:
2347 handleLOGOP(i);
2348 break;
2349 case OP_CVT:
2350 handleCVT_NEG(i);
2351 handleCVT_CVT(i);
2352 if (prog->getTarget()->isOpSupported(OP_EXTBF, TYPE_U32))
2353 handleCVT_EXTBF(i);
2354 break;
2355 case OP_SUCLAMP:
2356 handleSUCLAMP(i);
2357 break;
2358 case OP_NEG:
2359 handleNEG(i);
2360 break;
2361 case OP_EXTBF:
2362 handleEXTBF_RDSV(i);
2363 break;
2364 default:
2365 break;
2366 }
2367 }
2368
2369 return true;
2370 }
2371
2372 // =============================================================================
2373
2374 // ADD(SHL(a, b), c) -> SHLADD(a, b, c)
2375 // MUL(a, b) -> a few XMADs
2376 // MAD/FMA(a, b, c) -> a few XMADs
2377 class LateAlgebraicOpt : public Pass
2378 {
2379 private:
2380 virtual bool visit(Instruction *);
2381
2382 void handleADD(Instruction *);
2383 void handleMULMAD(Instruction *);
2384 bool tryADDToSHLADD(Instruction *);
2385
2386 BuildUtil bld;
2387 };
2388
2389 void
2390 LateAlgebraicOpt::handleADD(Instruction *add)
2391 {
2392 Value *src0 = add->getSrc(0);
2393 Value *src1 = add->getSrc(1);
2394
2395 if (src0->reg.file != FILE_GPR || src1->reg.file != FILE_GPR)
2396 return;
2397
2398 if (prog->getTarget()->isOpSupported(OP_SHLADD, add->dType))
2399 tryADDToSHLADD(add);
2400 }
2401
2402 // ADD(SHL(a, b), c) -> SHLADD(a, b, c)
2403 bool
2404 LateAlgebraicOpt::tryADDToSHLADD(Instruction *add)
2405 {
2406 Value *src0 = add->getSrc(0);
2407 Value *src1 = add->getSrc(1);
2408 ImmediateValue imm;
2409 Instruction *shl;
2410 Value *src;
2411 int s;
2412
2413 if (add->saturate || add->usesFlags() || typeSizeof(add->dType) == 8
2414 || isFloatType(add->dType))
2415 return false;
2416
2417 if (src0->getUniqueInsn() && src0->getUniqueInsn()->op == OP_SHL)
2418 s = 0;
2419 else
2420 if (src1->getUniqueInsn() && src1->getUniqueInsn()->op == OP_SHL)
2421 s = 1;
2422 else
2423 return false;
2424
2425 src = add->getSrc(s);
2426 shl = src->getUniqueInsn();
2427
2428 if (shl->bb != add->bb || shl->usesFlags() || shl->subOp || shl->src(0).mod)
2429 return false;
2430
2431 if (!shl->src(1).getImmediate(imm))
2432 return false;
2433
2434 add->op = OP_SHLADD;
2435 add->setSrc(2, add->src(!s));
2436 // SHL can't have any modifiers, but the ADD source may have had
2437 // one. Preserve it.
2438 add->setSrc(0, shl->getSrc(0));
2439 if (s == 1)
2440 add->src(0).mod = add->src(1).mod;
2441 add->setSrc(1, new_ImmediateValue(shl->bb->getProgram(), imm.reg.data.u32));
2442 add->src(1).mod = Modifier(0);
2443
2444 return true;
2445 }
2446
2447 // MUL(a, b) -> a few XMADs
2448 // MAD/FMA(a, b, c) -> a few XMADs
2449 void
2450 LateAlgebraicOpt::handleMULMAD(Instruction *i)
2451 {
2452 // TODO: handle NV50_IR_SUBOP_MUL_HIGH
2453 if (!prog->getTarget()->isOpSupported(OP_XMAD, TYPE_U32))
2454 return;
2455 if (isFloatType(i->dType) || typeSizeof(i->dType) != 4)
2456 return;
2457 if (i->subOp || i->usesFlags() || i->flagsDef >= 0)
2458 return;
2459
2460 assert(!i->src(0).mod);
2461 assert(!i->src(1).mod);
2462 assert(i->op == OP_MUL ? 1 : !i->src(2).mod);
2463
2464 bld.setPosition(i, false);
2465
2466 Value *a = i->getSrc(0);
2467 Value *b = i->getSrc(1);
2468 Value *c = i->op == OP_MUL ? bld.mkImm(0) : i->getSrc(2);
2469
2470 Value *tmp0 = bld.getSSA();
2471 Value *tmp1 = bld.getSSA();
2472
2473 Instruction *insn = bld.mkOp3(OP_XMAD, TYPE_U32, tmp0, b, a, c);
2474 insn->setPredicate(i->cc, i->getPredicate());
2475
2476 insn = bld.mkOp3(OP_XMAD, TYPE_U32, tmp1, b, a, bld.mkImm(0));
2477 insn->setPredicate(i->cc, i->getPredicate());
2478 insn->subOp = NV50_IR_SUBOP_XMAD_MRG | NV50_IR_SUBOP_XMAD_H1(1);
2479
2480 Value *pred = i->getPredicate();
2481 i->setPredicate(i->cc, NULL);
2482
2483 i->op = OP_XMAD;
2484 i->setSrc(0, b);
2485 i->setSrc(1, tmp1);
2486 i->setSrc(2, tmp0);
2487 i->subOp = NV50_IR_SUBOP_XMAD_PSL | NV50_IR_SUBOP_XMAD_CBCC;
2488 i->subOp |= NV50_IR_SUBOP_XMAD_H1(0) | NV50_IR_SUBOP_XMAD_H1(1);
2489
2490 i->setPredicate(i->cc, pred);
2491 }
2492
2493 bool
2494 LateAlgebraicOpt::visit(Instruction *i)
2495 {
2496 switch (i->op) {
2497 case OP_ADD:
2498 handleADD(i);
2499 break;
2500 case OP_MUL:
2501 case OP_MAD:
2502 case OP_FMA:
2503 handleMULMAD(i);
2504 break;
2505 default:
2506 break;
2507 }
2508
2509 return true;
2510 }
2511
2512 // =============================================================================
2513
2514 // Split 64-bit MUL and MAD
2515 class Split64BitOpPreRA : public Pass
2516 {
2517 private:
2518 virtual bool visit(BasicBlock *);
2519 void split64MulMad(Function *, Instruction *, DataType);
2520
2521 BuildUtil bld;
2522 };
2523
2524 bool
2525 Split64BitOpPreRA::visit(BasicBlock *bb)
2526 {
2527 Instruction *i, *next;
2528 Modifier mod;
2529
2530 for (i = bb->getEntry(); i; i = next) {
2531 next = i->next;
2532
2533 DataType hTy;
2534 switch (i->dType) {
2535 case TYPE_U64: hTy = TYPE_U32; break;
2536 case TYPE_S64: hTy = TYPE_S32; break;
2537 default:
2538 continue;
2539 }
2540
2541 if (i->op == OP_MAD || i->op == OP_MUL)
2542 split64MulMad(func, i, hTy);
2543 }
2544
2545 return true;
2546 }
2547
2548 void
2549 Split64BitOpPreRA::split64MulMad(Function *fn, Instruction *i, DataType hTy)
2550 {
2551 assert(i->op == OP_MAD || i->op == OP_MUL);
2552 assert(!isFloatType(i->dType) && !isFloatType(i->sType));
2553 assert(typeSizeof(hTy) == 4);
2554
2555 bld.setPosition(i, true);
2556
2557 Value *zero = bld.mkImm(0u);
2558 Value *carry = bld.getSSA(1, FILE_FLAGS);
2559
2560 // We want to compute `d = a * b (+ c)?`, where a, b, c and d are 64-bit
2561 // values (a, b and c might be 32-bit values), using 32-bit operations. This
2562 // gives the following operations:
2563 // * `d.low = low(a.low * b.low) (+ c.low)?`
2564 // * `d.high = low(a.high * b.low) + low(a.low * b.high)
2565 // + high(a.low * b.low) (+ c.high)?`
2566 //
2567 // To compute the high bits, we can split in the following operations:
2568 // * `tmp1 = low(a.high * b.low) (+ c.high)?`
2569 // * `tmp2 = low(a.low * b.high) + tmp1`
2570 // * `d.high = high(a.low * b.low) + tmp2`
2571 //
2572 // mkSplit put lower bits at index 0 and higher bits at index 1
2573
2574 Value *op1[2];
2575 if (i->getSrc(0)->reg.size == 8)
2576 bld.mkSplit(op1, 4, i->getSrc(0));
2577 else {
2578 op1[0] = i->getSrc(0);
2579 op1[1] = zero;
2580 }
2581 Value *op2[2];
2582 if (i->getSrc(1)->reg.size == 8)
2583 bld.mkSplit(op2, 4, i->getSrc(1));
2584 else {
2585 op2[0] = i->getSrc(1);
2586 op2[1] = zero;
2587 }
2588
2589 Value *op3[2] = { NULL, NULL };
2590 if (i->op == OP_MAD) {
2591 if (i->getSrc(2)->reg.size == 8)
2592 bld.mkSplit(op3, 4, i->getSrc(2));
2593 else {
2594 op3[0] = i->getSrc(2);
2595 op3[1] = zero;
2596 }
2597 }
2598
2599 Value *tmpRes1Hi = bld.getSSA();
2600 if (i->op == OP_MAD)
2601 bld.mkOp3(OP_MAD, hTy, tmpRes1Hi, op1[1], op2[0], op3[1]);
2602 else
2603 bld.mkOp2(OP_MUL, hTy, tmpRes1Hi, op1[1], op2[0]);
2604
2605 Value *tmpRes2Hi = bld.mkOp3v(OP_MAD, hTy, bld.getSSA(), op1[0], op2[1], tmpRes1Hi);
2606
2607 Value *def[2] = { bld.getSSA(), bld.getSSA() };
2608
2609 // If it was a MAD, add the carry from the low bits
2610 // It is not needed if it was a MUL, since we added high(a.low * b.low) to
2611 // d.high
2612 if (i->op == OP_MAD)
2613 bld.mkOp3(OP_MAD, hTy, def[0], op1[0], op2[0], op3[0])->setFlagsDef(1, carry);
2614 else
2615 bld.mkOp2(OP_MUL, hTy, def[0], op1[0], op2[0]);
2616
2617 Instruction *hiPart3 = bld.mkOp3(OP_MAD, hTy, def[1], op1[0], op2[0], tmpRes2Hi);
2618 hiPart3->subOp = NV50_IR_SUBOP_MUL_HIGH;
2619 if (i->op == OP_MAD)
2620 hiPart3->setFlagsSrc(3, carry);
2621
2622 bld.mkOp2(OP_MERGE, i->dType, i->getDef(0), def[0], def[1]);
2623
2624 delete_Instruction(fn->getProgram(), i);
2625 }
2626
2627 // =============================================================================
2628
2629 static inline void
2630 updateLdStOffset(Instruction *ldst, int32_t offset, Function *fn)
2631 {
2632 if (offset != ldst->getSrc(0)->reg.data.offset) {
2633 if (ldst->getSrc(0)->refCount() > 1)
2634 ldst->setSrc(0, cloneShallow(fn, ldst->getSrc(0)));
2635 ldst->getSrc(0)->reg.data.offset = offset;
2636 }
2637 }
2638
2639 // Combine loads and stores, forward stores to loads where possible.
2640 class MemoryOpt : public Pass
2641 {
2642 private:
2643 class Record
2644 {
2645 public:
2646 Record *next;
2647 Instruction *insn;
2648 const Value *rel[2];
2649 const Value *base;
2650 int32_t offset;
2651 int8_t fileIndex;
2652 uint8_t size;
2653 bool locked;
2654 Record *prev;
2655
2656 bool overlaps(const Instruction *ldst) const;
2657
2658 inline void link(Record **);
2659 inline void unlink(Record **);
2660 inline void set(const Instruction *ldst);
2661 };
2662
2663 public:
2664 MemoryOpt();
2665
2666 Record *loads[DATA_FILE_COUNT];
2667 Record *stores[DATA_FILE_COUNT];
2668
2669 MemoryPool recordPool;
2670
2671 private:
2672 virtual bool visit(BasicBlock *);
2673 bool runOpt(BasicBlock *);
2674
2675 Record **getList(const Instruction *);
2676
2677 Record *findRecord(const Instruction *, bool load, bool& isAdjacent) const;
2678
2679 // merge @insn into load/store instruction from @rec
2680 bool combineLd(Record *rec, Instruction *ld);
2681 bool combineSt(Record *rec, Instruction *st);
2682
2683 bool replaceLdFromLd(Instruction *ld, Record *ldRec);
2684 bool replaceLdFromSt(Instruction *ld, Record *stRec);
2685 bool replaceStFromSt(Instruction *restrict st, Record *stRec);
2686
2687 void addRecord(Instruction *ldst);
2688 void purgeRecords(Instruction *const st, DataFile);
2689 void lockStores(Instruction *const ld);
2690 void reset();
2691
2692 private:
2693 Record *prevRecord;
2694 };
2695
2696 MemoryOpt::MemoryOpt() : recordPool(sizeof(MemoryOpt::Record), 6)
2697 {
2698 for (int i = 0; i < DATA_FILE_COUNT; ++i) {
2699 loads[i] = NULL;
2700 stores[i] = NULL;
2701 }
2702 prevRecord = NULL;
2703 }
2704
2705 void
2706 MemoryOpt::reset()
2707 {
2708 for (unsigned int i = 0; i < DATA_FILE_COUNT; ++i) {
2709 Record *it, *next;
2710 for (it = loads[i]; it; it = next) {
2711 next = it->next;
2712 recordPool.release(it);
2713 }
2714 loads[i] = NULL;
2715 for (it = stores[i]; it; it = next) {
2716 next = it->next;
2717 recordPool.release(it);
2718 }
2719 stores[i] = NULL;
2720 }
2721 }
2722
2723 bool
2724 MemoryOpt::combineLd(Record *rec, Instruction *ld)
2725 {
2726 int32_t offRc = rec->offset;
2727 int32_t offLd = ld->getSrc(0)->reg.data.offset;
2728 int sizeRc = rec->size;
2729 int sizeLd = typeSizeof(ld->dType);
2730 int size = sizeRc + sizeLd;
2731 int d, j;
2732
2733 if (!prog->getTarget()->
2734 isAccessSupported(ld->getSrc(0)->reg.file, typeOfSize(size)))
2735 return false;
2736 // no unaligned loads
2737 if (((size == 0x8) && (MIN2(offLd, offRc) & 0x7)) ||
2738 ((size == 0xc) && (MIN2(offLd, offRc) & 0xf)))
2739 return false;
2740 // for compute indirect loads are not guaranteed to be aligned
2741 if (prog->getType() == Program::TYPE_COMPUTE && rec->rel[0])
2742 return false;
2743
2744 assert(sizeRc + sizeLd <= 16 && offRc != offLd);
2745
2746 // lock any stores that overlap with the load being merged into the
2747 // existing record.
2748 lockStores(ld);
2749
2750 for (j = 0; sizeRc; sizeRc -= rec->insn->getDef(j)->reg.size, ++j);
2751
2752 if (offLd < offRc) {
2753 int sz;
2754 for (sz = 0, d = 0; sz < sizeLd; sz += ld->getDef(d)->reg.size, ++d);
2755 // d: nr of definitions in ld
2756 // j: nr of definitions in rec->insn, move:
2757 for (d = d + j - 1; j > 0; --j, --d)
2758 rec->insn->setDef(d, rec->insn->getDef(j - 1));
2759
2760 if (rec->insn->getSrc(0)->refCount() > 1)
2761 rec->insn->setSrc(0, cloneShallow(func, rec->insn->getSrc(0)));
2762 rec->offset = rec->insn->getSrc(0)->reg.data.offset = offLd;
2763
2764 d = 0;
2765 } else {
2766 d = j;
2767 }
2768 // move definitions of @ld to @rec->insn
2769 for (j = 0; sizeLd; ++j, ++d) {
2770 sizeLd -= ld->getDef(j)->reg.size;
2771 rec->insn->setDef(d, ld->getDef(j));
2772 }
2773
2774 rec->size = size;
2775 rec->insn->getSrc(0)->reg.size = size;
2776 rec->insn->setType(typeOfSize(size));
2777
2778 delete_Instruction(prog, ld);
2779
2780 return true;
2781 }
2782
2783 bool
2784 MemoryOpt::combineSt(Record *rec, Instruction *st)
2785 {
2786 int32_t offRc = rec->offset;
2787 int32_t offSt = st->getSrc(0)->reg.data.offset;
2788 int sizeRc = rec->size;
2789 int sizeSt = typeSizeof(st->dType);
2790 int s = sizeSt / 4;
2791 int size = sizeRc + sizeSt;
2792 int j, k;
2793 Value *src[4]; // no modifiers in ValueRef allowed for st
2794 Value *extra[3];
2795
2796 if (!prog->getTarget()->
2797 isAccessSupported(st->getSrc(0)->reg.file, typeOfSize(size)))
2798 return false;
2799 // no unaligned stores
2800 if (size == 8 && MIN2(offRc, offSt) & 0x7)
2801 return false;
2802 // for compute indirect stores are not guaranteed to be aligned
2803 if (prog->getType() == Program::TYPE_COMPUTE && rec->rel[0])
2804 return false;
2805
2806 // remove any existing load/store records for the store being merged into
2807 // the existing record.
2808 purgeRecords(st, DATA_FILE_COUNT);
2809
2810 st->takeExtraSources(0, extra); // save predicate and indirect address
2811
2812 if (offRc < offSt) {
2813 // save values from @st
2814 for (s = 0; sizeSt; ++s) {
2815 sizeSt -= st->getSrc(s + 1)->reg.size;
2816 src[s] = st->getSrc(s + 1);
2817 }
2818 // set record's values as low sources of @st
2819 for (j = 1; sizeRc; ++j) {
2820 sizeRc -= rec->insn->getSrc(j)->reg.size;
2821 st->setSrc(j, rec->insn->getSrc(j));
2822 }
2823 // set saved values as high sources of @st
2824 for (k = j, j = 0; j < s; ++j)
2825 st->setSrc(k++, src[j]);
2826
2827 updateLdStOffset(st, offRc, func);
2828 } else {
2829 for (j = 1; sizeSt; ++j)
2830 sizeSt -= st->getSrc(j)->reg.size;
2831 for (s = 1; sizeRc; ++j, ++s) {
2832 sizeRc -= rec->insn->getSrc(s)->reg.size;
2833 st->setSrc(j, rec->insn->getSrc(s));
2834 }
2835 rec->offset = offSt;
2836 }
2837 st->putExtraSources(0, extra); // restore pointer and predicate
2838
2839 delete_Instruction(prog, rec->insn);
2840 rec->insn = st;
2841 rec->size = size;
2842 rec->insn->getSrc(0)->reg.size = size;
2843 rec->insn->setType(typeOfSize(size));
2844 return true;
2845 }
2846
2847 void
2848 MemoryOpt::Record::set(const Instruction *ldst)
2849 {
2850 const Symbol *mem = ldst->getSrc(0)->asSym();
2851 fileIndex = mem->reg.fileIndex;
2852 rel[0] = ldst->getIndirect(0, 0);
2853 rel[1] = ldst->getIndirect(0, 1);
2854 offset = mem->reg.data.offset;
2855 base = mem->getBase();
2856 size = typeSizeof(ldst->sType);
2857 }
2858
2859 void
2860 MemoryOpt::Record::link(Record **list)
2861 {
2862 next = *list;
2863 if (next)
2864 next->prev = this;
2865 prev = NULL;
2866 *list = this;
2867 }
2868
2869 void
2870 MemoryOpt::Record::unlink(Record **list)
2871 {
2872 if (next)
2873 next->prev = prev;
2874 if (prev)
2875 prev->next = next;
2876 else
2877 *list = next;
2878 }
2879
2880 MemoryOpt::Record **
2881 MemoryOpt::getList(const Instruction *insn)
2882 {
2883 if (insn->op == OP_LOAD || insn->op == OP_VFETCH)
2884 return &loads[insn->src(0).getFile()];
2885 return &stores[insn->src(0).getFile()];
2886 }
2887
2888 void
2889 MemoryOpt::addRecord(Instruction *i)
2890 {
2891 Record **list = getList(i);
2892 Record *it = reinterpret_cast<Record *>(recordPool.allocate());
2893
2894 it->link(list);
2895 it->set(i);
2896 it->insn = i;
2897 it->locked = false;
2898 }
2899
2900 MemoryOpt::Record *
2901 MemoryOpt::findRecord(const Instruction *insn, bool load, bool& isAdj) const
2902 {
2903 const Symbol *sym = insn->getSrc(0)->asSym();
2904 const int size = typeSizeof(insn->sType);
2905 Record *rec = NULL;
2906 Record *it = load ? loads[sym->reg.file] : stores[sym->reg.file];
2907
2908 for (; it; it = it->next) {
2909 if (it->locked && insn->op != OP_LOAD && insn->op != OP_VFETCH)
2910 continue;
2911 if ((it->offset >> 4) != (sym->reg.data.offset >> 4) ||
2912 it->rel[0] != insn->getIndirect(0, 0) ||
2913 it->fileIndex != sym->reg.fileIndex ||
2914 it->rel[1] != insn->getIndirect(0, 1))
2915 continue;
2916
2917 if (it->offset < sym->reg.data.offset) {
2918 if (it->offset + it->size >= sym->reg.data.offset) {
2919 isAdj = (it->offset + it->size == sym->reg.data.offset);
2920 if (!isAdj)
2921 return it;
2922 if (!(it->offset & 0x7))
2923 rec = it;
2924 }
2925 } else {
2926 isAdj = it->offset != sym->reg.data.offset;
2927 if (size <= it->size && !isAdj)
2928 return it;
2929 else
2930 if (!(sym->reg.data.offset & 0x7))
2931 if (it->offset - size <= sym->reg.data.offset)
2932 rec = it;
2933 }
2934 }
2935 return rec;
2936 }
2937
2938 bool
2939 MemoryOpt::replaceLdFromSt(Instruction *ld, Record *rec)
2940 {
2941 Instruction *st = rec->insn;
2942 int32_t offSt = rec->offset;
2943 int32_t offLd = ld->getSrc(0)->reg.data.offset;
2944 int d, s;
2945
2946 for (s = 1; offSt != offLd && st->srcExists(s); ++s)
2947 offSt += st->getSrc(s)->reg.size;
2948 if (offSt != offLd)
2949 return false;
2950
2951 for (d = 0; ld->defExists(d) && st->srcExists(s); ++d, ++s) {
2952 if (ld->getDef(d)->reg.size != st->getSrc(s)->reg.size)
2953 return false;
2954 if (st->getSrc(s)->reg.file != FILE_GPR)
2955 return false;
2956 ld->def(d).replace(st->src(s), false);
2957 }
2958 ld->bb->remove(ld);
2959 return true;
2960 }
2961
2962 bool
2963 MemoryOpt::replaceLdFromLd(Instruction *ldE, Record *rec)
2964 {
2965 Instruction *ldR = rec->insn;
2966 int32_t offR = rec->offset;
2967 int32_t offE = ldE->getSrc(0)->reg.data.offset;
2968 int dR, dE;
2969
2970 assert(offR <= offE);
2971 for (dR = 0; offR < offE && ldR->defExists(dR); ++dR)
2972 offR += ldR->getDef(dR)->reg.size;
2973 if (offR != offE)
2974 return false;
2975
2976 for (dE = 0; ldE->defExists(dE) && ldR->defExists(dR); ++dE, ++dR) {
2977 if (ldE->getDef(dE)->reg.size != ldR->getDef(dR)->reg.size)
2978 return false;
2979 ldE->def(dE).replace(ldR->getDef(dR), false);
2980 }
2981
2982 delete_Instruction(prog, ldE);
2983 return true;
2984 }
2985
2986 bool
2987 MemoryOpt::replaceStFromSt(Instruction *restrict st, Record *rec)
2988 {
2989 const Instruction *const ri = rec->insn;
2990 Value *extra[3];
2991
2992 int32_t offS = st->getSrc(0)->reg.data.offset;
2993 int32_t offR = rec->offset;
2994 int32_t endS = offS + typeSizeof(st->dType);
2995 int32_t endR = offR + typeSizeof(ri->dType);
2996
2997 rec->size = MAX2(endS, endR) - MIN2(offS, offR);
2998
2999 st->takeExtraSources(0, extra);
3000
3001 if (offR < offS) {
3002 Value *vals[10];
3003 int s, n;
3004 int k = 0;
3005 // get non-replaced sources of ri
3006 for (s = 1; offR < offS; offR += ri->getSrc(s)->reg.size, ++s)
3007 vals[k++] = ri->getSrc(s);
3008 n = s;
3009 // get replaced sources of st
3010 for (s = 1; st->srcExists(s); offS += st->getSrc(s)->reg.size, ++s)
3011 vals[k++] = st->getSrc(s);
3012 // skip replaced sources of ri
3013 for (s = n; offR < endS; offR += ri->getSrc(s)->reg.size, ++s);
3014 // get non-replaced sources after values covered by st
3015 for (; offR < endR; offR += ri->getSrc(s)->reg.size, ++s)
3016 vals[k++] = ri->getSrc(s);
3017 assert((unsigned int)k <= ARRAY_SIZE(vals));
3018 for (s = 0; s < k; ++s)
3019 st->setSrc(s + 1, vals[s]);
3020 st->setSrc(0, ri->getSrc(0));
3021 } else
3022 if (endR > endS) {
3023 int j, s;
3024 for (j = 1; offR < endS; offR += ri->getSrc(j++)->reg.size);
3025 for (s = 1; offS < endS; offS += st->getSrc(s++)->reg.size);
3026 for (; offR < endR; offR += ri->getSrc(j++)->reg.size)
3027 st->setSrc(s++, ri->getSrc(j));
3028 }
3029 st->putExtraSources(0, extra);
3030
3031 delete_Instruction(prog, rec->insn);
3032
3033 rec->insn = st;
3034 rec->offset = st->getSrc(0)->reg.data.offset;
3035
3036 st->setType(typeOfSize(rec->size));
3037
3038 return true;
3039 }
3040
3041 bool
3042 MemoryOpt::Record::overlaps(const Instruction *ldst) const
3043 {
3044 Record that;
3045 that.set(ldst);
3046
3047 // This assumes that images/buffers can't overlap. They can.
3048 // TODO: Plumb the restrict logic through, and only skip when it's a
3049 // restrict situation, or there can implicitly be no writes.
3050 if (this->fileIndex != that.fileIndex && this->rel[1] == that.rel[1])
3051 return false;
3052
3053 if (this->rel[0] || that.rel[0])
3054 return this->base == that.base;
3055
3056 return
3057 (this->offset < that.offset + that.size) &&
3058 (this->offset + this->size > that.offset);
3059 }
3060
3061 // We must not eliminate stores that affect the result of @ld if
3062 // we find later stores to the same location, and we may no longer
3063 // merge them with later stores.
3064 // The stored value can, however, still be used to determine the value
3065 // returned by future loads.
3066 void
3067 MemoryOpt::lockStores(Instruction *const ld)
3068 {
3069 for (Record *r = stores[ld->src(0).getFile()]; r; r = r->next)
3070 if (!r->locked && r->overlaps(ld))
3071 r->locked = true;
3072 }
3073
3074 // Prior loads from the location of @st are no longer valid.
3075 // Stores to the location of @st may no longer be used to derive
3076 // the value at it nor be coalesced into later stores.
3077 void
3078 MemoryOpt::purgeRecords(Instruction *const st, DataFile f)
3079 {
3080 if (st)
3081 f = st->src(0).getFile();
3082
3083 for (Record *r = loads[f]; r; r = r->next)
3084 if (!st || r->overlaps(st))
3085 r->unlink(&loads[f]);
3086
3087 for (Record *r = stores[f]; r; r = r->next)
3088 if (!st || r->overlaps(st))
3089 r->unlink(&stores[f]);
3090 }
3091
3092 bool
3093 MemoryOpt::visit(BasicBlock *bb)
3094 {
3095 bool ret = runOpt(bb);
3096 // Run again, one pass won't combine 4 32 bit ld/st to a single 128 bit ld/st
3097 // where 96 bit memory operations are forbidden.
3098 if (ret)
3099 ret = runOpt(bb);
3100 return ret;
3101 }
3102
3103 bool
3104 MemoryOpt::runOpt(BasicBlock *bb)
3105 {
3106 Instruction *ldst, *next;
3107 Record *rec;
3108 bool isAdjacent = true;
3109
3110 for (ldst = bb->getEntry(); ldst; ldst = next) {
3111 bool keep = true;
3112 bool isLoad = true;
3113 next = ldst->next;
3114
3115 if (ldst->op == OP_LOAD || ldst->op == OP_VFETCH) {
3116 if (ldst->isDead()) {
3117 // might have been produced by earlier optimization
3118 delete_Instruction(prog, ldst);
3119 continue;
3120 }
3121 } else
3122 if (ldst->op == OP_STORE || ldst->op == OP_EXPORT) {
3123 if (typeSizeof(ldst->dType) == 4 &&
3124 ldst->src(1).getFile() == FILE_GPR &&
3125 ldst->getSrc(1)->getInsn()->op == OP_NOP) {
3126 delete_Instruction(prog, ldst);
3127 continue;
3128 }
3129 isLoad = false;
3130 } else {
3131 // TODO: maybe have all fixed ops act as barrier ?
3132 if (ldst->op == OP_CALL ||
3133 ldst->op == OP_BAR ||
3134 ldst->op == OP_MEMBAR) {
3135 purgeRecords(NULL, FILE_MEMORY_LOCAL);
3136 purgeRecords(NULL, FILE_MEMORY_GLOBAL);
3137 purgeRecords(NULL, FILE_MEMORY_SHARED);
3138 purgeRecords(NULL, FILE_SHADER_OUTPUT);
3139 } else
3140 if (ldst->op == OP_ATOM || ldst->op == OP_CCTL) {
3141 if (ldst->src(0).getFile() == FILE_MEMORY_GLOBAL) {
3142 purgeRecords(NULL, FILE_MEMORY_LOCAL);
3143 purgeRecords(NULL, FILE_MEMORY_GLOBAL);
3144 purgeRecords(NULL, FILE_MEMORY_SHARED);
3145 } else {
3146 purgeRecords(NULL, ldst->src(0).getFile());
3147 }
3148 } else
3149 if (ldst->op == OP_EMIT || ldst->op == OP_RESTART) {
3150 purgeRecords(NULL, FILE_SHADER_OUTPUT);
3151 }
3152 continue;
3153 }
3154 if (ldst->getPredicate()) // TODO: handle predicated ld/st
3155 continue;
3156 if (ldst->perPatch) // TODO: create separate per-patch lists
3157 continue;
3158
3159 if (isLoad) {
3160 DataFile file = ldst->src(0).getFile();
3161
3162 // if ld l[]/g[] look for previous store to eliminate the reload
3163 if (file == FILE_MEMORY_GLOBAL || file == FILE_MEMORY_LOCAL) {
3164 // TODO: shared memory ?
3165 rec = findRecord(ldst, false, isAdjacent);
3166 if (rec && !isAdjacent)
3167 keep = !replaceLdFromSt(ldst, rec);
3168 }
3169
3170 // or look for ld from the same location and replace this one
3171 rec = keep ? findRecord(ldst, true, isAdjacent) : NULL;
3172 if (rec) {
3173 if (!isAdjacent)
3174 keep = !replaceLdFromLd(ldst, rec);
3175 else
3176 // or combine a previous load with this one
3177 keep = !combineLd(rec, ldst);
3178 }
3179 if (keep)
3180 lockStores(ldst);
3181 } else {
3182 rec = findRecord(ldst, false, isAdjacent);
3183 if (rec) {
3184 if (!isAdjacent)
3185 keep = !replaceStFromSt(ldst, rec);
3186 else
3187 keep = !combineSt(rec, ldst);
3188 }
3189 if (keep)
3190 purgeRecords(ldst, DATA_FILE_COUNT);
3191 }
3192 if (keep)
3193 addRecord(ldst);
3194 }
3195 reset();
3196
3197 return true;
3198 }
3199
3200 // =============================================================================
3201
3202 // Turn control flow into predicated instructions (after register allocation !).
3203 // TODO:
3204 // Could move this to before register allocation on NVC0 and also handle nested
3205 // constructs.
3206 class FlatteningPass : public Pass
3207 {
3208 private:
3209 virtual bool visit(Function *);
3210 virtual bool visit(BasicBlock *);
3211
3212 bool tryPredicateConditional(BasicBlock *);
3213 void predicateInstructions(BasicBlock *, Value *pred, CondCode cc);
3214 void tryPropagateBranch(BasicBlock *);
3215 inline bool isConstantCondition(Value *pred);
3216 inline bool mayPredicate(const Instruction *, const Value *pred) const;
3217 inline void removeFlow(Instruction *);
3218
3219 uint8_t gpr_unit;
3220 };
3221
3222 bool
3223 FlatteningPass::isConstantCondition(Value *pred)
3224 {
3225 Instruction *insn = pred->getUniqueInsn();
3226 assert(insn);
3227 if (insn->op != OP_SET || insn->srcExists(2))
3228 return false;
3229
3230 for (int s = 0; s < 2 && insn->srcExists(s); ++s) {
3231 Instruction *ld = insn->getSrc(s)->getUniqueInsn();
3232 DataFile file;
3233 if (ld) {
3234 if (ld->op != OP_MOV && ld->op != OP_LOAD)
3235 return false;
3236 if (ld->src(0).isIndirect(0))
3237 return false;
3238 file = ld->src(0).getFile();
3239 } else {
3240 file = insn->src(s).getFile();
3241 // catch $r63 on NVC0 and $r63/$r127 on NV50. Unfortunately maxGPR is
3242 // in register "units", which can vary between targets.
3243 if (file == FILE_GPR) {
3244 Value *v = insn->getSrc(s);
3245 int bytes = v->reg.data.id * MIN2(v->reg.size, 4);
3246 int units = bytes >> gpr_unit;
3247 if (units > prog->maxGPR)
3248 file = FILE_IMMEDIATE;
3249 }
3250 }
3251 if (file != FILE_IMMEDIATE && file != FILE_MEMORY_CONST)
3252 return false;
3253 }
3254 return true;
3255 }
3256
3257 void
3258 FlatteningPass::removeFlow(Instruction *insn)
3259 {
3260 FlowInstruction *term = insn ? insn->asFlow() : NULL;
3261 if (!term)
3262 return;
3263 Graph::Edge::Type ty = term->bb->cfg.outgoing().getType();
3264
3265 if (term->op == OP_BRA) {
3266 // TODO: this might get more difficult when we get arbitrary BRAs
3267 if (ty == Graph::Edge::CROSS || ty == Graph::Edge::BACK)
3268 return;
3269 } else
3270 if (term->op != OP_JOIN)
3271 return;
3272
3273 Value *pred = term->getPredicate();
3274
3275 delete_Instruction(prog, term);
3276
3277 if (pred && pred->refCount() == 0) {
3278 Instruction *pSet = pred->getUniqueInsn();
3279 pred->join->reg.data.id = -1; // deallocate
3280 if (pSet->isDead())
3281 delete_Instruction(prog, pSet);
3282 }
3283 }
3284
3285 void
3286 FlatteningPass::predicateInstructions(BasicBlock *bb, Value *pred, CondCode cc)
3287 {
3288 for (Instruction *i = bb->getEntry(); i; i = i->next) {
3289 if (i->isNop())
3290 continue;
3291 assert(!i->getPredicate());
3292 i->setPredicate(cc, pred);
3293 }
3294 removeFlow(bb->getExit());
3295 }
3296
3297 bool
3298 FlatteningPass::mayPredicate(const Instruction *insn, const Value *pred) const
3299 {
3300 if (insn->isPseudo())
3301 return true;
3302 // TODO: calls where we don't know which registers are modified
3303
3304 if (!prog->getTarget()->mayPredicate(insn, pred))
3305 return false;
3306 for (int d = 0; insn->defExists(d); ++d)
3307 if (insn->getDef(d)->equals(pred))
3308 return false;
3309 return true;
3310 }
3311
3312 // If we jump to BRA/RET/EXIT, replace the jump with it.
3313 // NOTE: We do not update the CFG anymore here !
3314 //
3315 // TODO: Handle cases where we skip over a branch (maybe do that elsewhere ?):
3316 // BB:0
3317 // @p0 bra BB:2 -> @!p0 bra BB:3 iff (!) BB:2 immediately adjoins BB:1
3318 // BB1:
3319 // bra BB:3
3320 // BB2:
3321 // ...
3322 // BB3:
3323 // ...
3324 void
3325 FlatteningPass::tryPropagateBranch(BasicBlock *bb)
3326 {
3327 for (Instruction *i = bb->getExit(); i && i->op == OP_BRA; i = i->prev) {
3328 BasicBlock *bf = i->asFlow()->target.bb;
3329
3330 if (bf->getInsnCount() != 1)
3331 continue;
3332
3333 FlowInstruction *bra = i->asFlow();
3334 FlowInstruction *rep = bf->getExit()->asFlow();
3335
3336 if (!rep || rep->getPredicate())
3337 continue;
3338 if (rep->op != OP_BRA &&
3339 rep->op != OP_JOIN &&
3340 rep->op != OP_EXIT)
3341 continue;
3342
3343 // TODO: If there are multiple branches to @rep, only the first would
3344 // be replaced, so only remove them after this pass is done ?
3345 // Also, need to check all incident blocks for fall-through exits and
3346 // add the branch there.
3347 bra->op = rep->op;
3348 bra->target.bb = rep->target.bb;
3349 if (bf->cfg.incidentCount() == 1)
3350 bf->remove(rep);
3351 }
3352 }
3353
3354 bool
3355 FlatteningPass::visit(Function *fn)
3356 {
3357 gpr_unit = prog->getTarget()->getFileUnit(FILE_GPR);
3358
3359 return true;
3360 }
3361
3362 bool
3363 FlatteningPass::visit(BasicBlock *bb)
3364 {
3365 if (tryPredicateConditional(bb))
3366 return true;
3367
3368 // try to attach join to previous instruction
3369 if (prog->getTarget()->hasJoin) {
3370 Instruction *insn = bb->getExit();
3371 if (insn && insn->op == OP_JOIN && !insn->getPredicate()) {
3372 insn = insn->prev;
3373 if (insn && !insn->getPredicate() &&
3374 !insn->asFlow() &&
3375 insn->op != OP_DISCARD &&
3376 insn->op != OP_TEXBAR &&
3377 !isTextureOp(insn->op) && // probably just nve4
3378 !isSurfaceOp(insn->op) && // not confirmed
3379 insn->op != OP_LINTERP && // probably just nve4
3380 insn->op != OP_PINTERP && // probably just nve4
3381 ((insn->op != OP_LOAD && insn->op != OP_STORE && insn->op != OP_ATOM) ||
3382 (typeSizeof(insn->dType) <= 4 && !insn->src(0).isIndirect(0))) &&
3383 !insn->isNop()) {
3384 insn->join = 1;
3385 bb->remove(bb->getExit());
3386 return true;
3387 }
3388 }
3389 }
3390
3391 tryPropagateBranch(bb);
3392
3393 return true;
3394 }
3395
3396 bool
3397 FlatteningPass::tryPredicateConditional(BasicBlock *bb)
3398 {
3399 BasicBlock *bL = NULL, *bR = NULL;
3400 unsigned int nL = 0, nR = 0, limit = 12;
3401 Instruction *insn;
3402 unsigned int mask;
3403
3404 mask = bb->initiatesSimpleConditional();
3405 if (!mask)
3406 return false;
3407
3408 assert(bb->getExit());
3409 Value *pred = bb->getExit()->getPredicate();
3410 assert(pred);
3411
3412 if (isConstantCondition(pred))
3413 limit = 4;
3414
3415 Graph::EdgeIterator ei = bb->cfg.outgoing();
3416
3417 if (mask & 1) {
3418 bL = BasicBlock::get(ei.getNode());
3419 for (insn = bL->getEntry(); insn; insn = insn->next, ++nL)
3420 if (!mayPredicate(insn, pred))
3421 return false;
3422 if (nL > limit)
3423 return false; // too long, do a real branch
3424 }
3425 ei.next();
3426
3427 if (mask & 2) {
3428 bR = BasicBlock::get(ei.getNode());
3429 for (insn = bR->getEntry(); insn; insn = insn->next, ++nR)
3430 if (!mayPredicate(insn, pred))
3431 return false;
3432 if (nR > limit)
3433 return false; // too long, do a real branch
3434 }
3435
3436 if (bL)
3437 predicateInstructions(bL, pred, bb->getExit()->cc);
3438 if (bR)
3439 predicateInstructions(bR, pred, inverseCondCode(bb->getExit()->cc));
3440
3441 if (bb->joinAt) {
3442 bb->remove(bb->joinAt);
3443 bb->joinAt = NULL;
3444 }
3445 removeFlow(bb->getExit()); // delete the branch/join at the fork point
3446
3447 // remove potential join operations at the end of the conditional
3448 if (prog->getTarget()->joinAnterior) {
3449 bb = BasicBlock::get((bL ? bL : bR)->cfg.outgoing().getNode());
3450 if (bb->getEntry() && bb->getEntry()->op == OP_JOIN)
3451 removeFlow(bb->getEntry());
3452 }
3453
3454 return true;
3455 }
3456
3457 // =============================================================================
3458
3459 // Fold Immediate into MAD; must be done after register allocation due to
3460 // constraint SDST == SSRC2
3461 // TODO:
3462 // Does NVC0+ have other situations where this pass makes sense?
3463 class PostRaLoadPropagation : public Pass
3464 {
3465 private:
3466 virtual bool visit(Instruction *);
3467
3468 void handleMADforNV50(Instruction *);
3469 void handleMADforNVC0(Instruction *);
3470 };
3471
3472 static bool
3473 post_ra_dead(Instruction *i)
3474 {
3475 for (int d = 0; i->defExists(d); ++d)
3476 if (i->getDef(d)->refCount())
3477 return false;
3478 return true;
3479 }
3480
3481 // Fold Immediate into MAD; must be done after register allocation due to
3482 // constraint SDST == SSRC2
3483 void
3484 PostRaLoadPropagation::handleMADforNV50(Instruction *i)
3485 {
3486 if (i->def(0).getFile() != FILE_GPR ||
3487 i->src(0).getFile() != FILE_GPR ||
3488 i->src(1).getFile() != FILE_GPR ||
3489 i->src(2).getFile() != FILE_GPR ||
3490 i->getDef(0)->reg.data.id != i->getSrc(2)->reg.data.id)
3491 return;
3492
3493 if (i->getDef(0)->reg.data.id >= 64 ||
3494 i->getSrc(0)->reg.data.id >= 64)
3495 return;
3496
3497 if (i->flagsSrc >= 0 && i->getSrc(i->flagsSrc)->reg.data.id != 0)
3498 return;
3499
3500 if (i->getPredicate())
3501 return;
3502
3503 Value *vtmp;
3504 Instruction *def = i->getSrc(1)->getInsn();
3505
3506 if (def && def->op == OP_SPLIT && typeSizeof(def->sType) == 4)
3507 def = def->getSrc(0)->getInsn();
3508 if (def && def->op == OP_MOV && def->src(0).getFile() == FILE_IMMEDIATE) {
3509 vtmp = i->getSrc(1);
3510 if (isFloatType(i->sType)) {
3511 i->setSrc(1, def->getSrc(0));
3512 } else {
3513 ImmediateValue val;
3514 // getImmediate() has side-effects on the argument so this *shouldn't*
3515 // be folded into the assert()
3516 MAYBE_UNUSED bool ret = def->src(0).getImmediate(val);
3517 assert(ret);
3518 if (i->getSrc(1)->reg.data.id & 1)
3519 val.reg.data.u32 >>= 16;
3520 val.reg.data.u32 &= 0xffff;
3521 i->setSrc(1, new_ImmediateValue(prog, val.reg.data.u32));
3522 }
3523
3524 /* There's no post-RA dead code elimination, so do it here
3525 * XXX: if we add more code-removing post-RA passes, we might
3526 * want to create a post-RA dead-code elim pass */
3527 if (post_ra_dead(vtmp->getInsn())) {
3528 Value *src = vtmp->getInsn()->getSrc(0);
3529 // Careful -- splits will have already been removed from the
3530 // functions. Don't double-delete.
3531 if (vtmp->getInsn()->bb)
3532 delete_Instruction(prog, vtmp->getInsn());
3533 if (src->getInsn() && post_ra_dead(src->getInsn()))
3534 delete_Instruction(prog, src->getInsn());
3535 }
3536 }
3537 }
3538
3539 void
3540 PostRaLoadPropagation::handleMADforNVC0(Instruction *i)
3541 {
3542 if (i->def(0).getFile() != FILE_GPR ||
3543 i->src(0).getFile() != FILE_GPR ||
3544 i->src(1).getFile() != FILE_GPR ||
3545 i->src(2).getFile() != FILE_GPR ||
3546 i->getDef(0)->reg.data.id != i->getSrc(2)->reg.data.id)
3547 return;
3548
3549 // TODO: gm107 can also do this for S32, maybe other chipsets as well
3550 if (i->dType != TYPE_F32)
3551 return;
3552
3553 if ((i->src(2).mod | Modifier(NV50_IR_MOD_NEG)) != Modifier(NV50_IR_MOD_NEG))
3554 return;
3555
3556 ImmediateValue val;
3557 int s;
3558
3559 if (i->src(0).getImmediate(val))
3560 s = 1;
3561 else if (i->src(1).getImmediate(val))
3562 s = 0;
3563 else
3564 return;
3565
3566 if ((i->src(s).mod | Modifier(NV50_IR_MOD_NEG)) != Modifier(NV50_IR_MOD_NEG))
3567 return;
3568
3569 if (s == 1)
3570 i->swapSources(0, 1);
3571
3572 Instruction *imm = i->getSrc(1)->getInsn();
3573 i->setSrc(1, imm->getSrc(0));
3574 if (post_ra_dead(imm))
3575 delete_Instruction(prog, imm);
3576 }
3577
3578 bool
3579 PostRaLoadPropagation::visit(Instruction *i)
3580 {
3581 switch (i->op) {
3582 case OP_FMA:
3583 case OP_MAD:
3584 if (prog->getTarget()->getChipset() < 0xc0)
3585 handleMADforNV50(i);
3586 else
3587 handleMADforNVC0(i);
3588 break;
3589 default:
3590 break;
3591 }
3592
3593 return true;
3594 }
3595
3596 // =============================================================================
3597
3598 // Common subexpression elimination. Stupid O^2 implementation.
3599 class LocalCSE : public Pass
3600 {
3601 private:
3602 virtual bool visit(BasicBlock *);
3603
3604 inline bool tryReplace(Instruction **, Instruction *);
3605
3606 DLList ops[OP_LAST + 1];
3607 };
3608
3609 class GlobalCSE : public Pass
3610 {
3611 private:
3612 virtual bool visit(BasicBlock *);
3613 };
3614
3615 bool
3616 Instruction::isActionEqual(const Instruction *that) const
3617 {
3618 if (this->op != that->op ||
3619 this->dType != that->dType ||
3620 this->sType != that->sType)
3621 return false;
3622 if (this->cc != that->cc)
3623 return false;
3624
3625 if (this->asTex()) {
3626 if (memcmp(&this->asTex()->tex,
3627 &that->asTex()->tex,
3628 sizeof(this->asTex()->tex)))
3629 return false;
3630 } else
3631 if (this->asCmp()) {
3632 if (this->asCmp()->setCond != that->asCmp()->setCond)
3633 return false;
3634 } else
3635 if (this->asFlow()) {
3636 return false;
3637 } else
3638 if (this->op == OP_PHI && this->bb != that->bb) {
3639 /* TODO: we could probably be a bit smarter here by following the
3640 * control flow, but honestly, it is quite painful to check */
3641 return false;
3642 } else {
3643 if (this->ipa != that->ipa ||
3644 this->lanes != that->lanes ||
3645 this->perPatch != that->perPatch)
3646 return false;
3647 if (this->postFactor != that->postFactor)
3648 return false;
3649 }
3650
3651 if (this->subOp != that->subOp ||
3652 this->saturate != that->saturate ||
3653 this->rnd != that->rnd ||
3654 this->ftz != that->ftz ||
3655 this->dnz != that->dnz ||
3656 this->cache != that->cache ||
3657 this->mask != that->mask)
3658 return false;
3659
3660 return true;
3661 }
3662
3663 bool
3664 Instruction::isResultEqual(const Instruction *that) const
3665 {
3666 unsigned int d, s;
3667
3668 // NOTE: location of discard only affects tex with liveOnly and quadops
3669 if (!this->defExists(0) && this->op != OP_DISCARD)
3670 return false;
3671
3672 if (!isActionEqual(that))
3673 return false;
3674
3675 if (this->predSrc != that->predSrc)
3676 return false;
3677
3678 for (d = 0; this->defExists(d); ++d) {
3679 if (!that->defExists(d) ||
3680 !this->getDef(d)->equals(that->getDef(d), false))
3681 return false;
3682 }
3683 if (that->defExists(d))
3684 return false;
3685
3686 for (s = 0; this->srcExists(s); ++s) {
3687 if (!that->srcExists(s))
3688 return false;
3689 if (this->src(s).mod != that->src(s).mod)
3690 return false;
3691 if (!this->getSrc(s)->equals(that->getSrc(s), true))
3692 return false;
3693 }
3694 if (that->srcExists(s))
3695 return false;
3696
3697 if (op == OP_LOAD || op == OP_VFETCH || op == OP_ATOM) {
3698 switch (src(0).getFile()) {
3699 case FILE_MEMORY_CONST:
3700 case FILE_SHADER_INPUT:
3701 return true;
3702 case FILE_SHADER_OUTPUT:
3703 return bb->getProgram()->getType() == Program::TYPE_TESSELLATION_EVAL;
3704 default:
3705 return false;
3706 }
3707 }
3708
3709 return true;
3710 }
3711
3712 // pull through common expressions from different in-blocks
3713 bool
3714 GlobalCSE::visit(BasicBlock *bb)
3715 {
3716 Instruction *phi, *next, *ik;
3717 int s;
3718
3719 // TODO: maybe do this with OP_UNION, too
3720
3721 for (phi = bb->getPhi(); phi && phi->op == OP_PHI; phi = next) {
3722 next = phi->next;
3723 if (phi->getSrc(0)->refCount() > 1)
3724 continue;
3725 ik = phi->getSrc(0)->getInsn();
3726 if (!ik)
3727 continue; // probably a function input
3728 if (ik->defCount(0xff) > 1)
3729 continue; // too painful to check if we can really push this forward
3730 for (s = 1; phi->srcExists(s); ++s) {
3731 if (phi->getSrc(s)->refCount() > 1)
3732 break;
3733 if (!phi->getSrc(s)->getInsn() ||
3734 !phi->getSrc(s)->getInsn()->isResultEqual(ik))
3735 break;
3736 }
3737 if (!phi->srcExists(s)) {
3738 assert(ik->op != OP_PHI);
3739 Instruction *entry = bb->getEntry();
3740 ik->bb->remove(ik);
3741 if (!entry || entry->op != OP_JOIN)
3742 bb->insertHead(ik);
3743 else
3744 bb->insertAfter(entry, ik);
3745 ik->setDef(0, phi->getDef(0));
3746 delete_Instruction(prog, phi);
3747 }
3748 }
3749
3750 return true;
3751 }
3752
3753 bool
3754 LocalCSE::tryReplace(Instruction **ptr, Instruction *i)
3755 {
3756 Instruction *old = *ptr;
3757
3758 // TODO: maybe relax this later (causes trouble with OP_UNION)
3759 if (i->isPredicated())
3760 return false;
3761
3762 if (!old->isResultEqual(i))
3763 return false;
3764
3765 for (int d = 0; old->defExists(d); ++d)
3766 old->def(d).replace(i->getDef(d), false);
3767 delete_Instruction(prog, old);
3768 *ptr = NULL;
3769 return true;
3770 }
3771
3772 bool
3773 LocalCSE::visit(BasicBlock *bb)
3774 {
3775 unsigned int replaced;
3776
3777 do {
3778 Instruction *ir, *next;
3779
3780 replaced = 0;
3781
3782 // will need to know the order of instructions
3783 int serial = 0;
3784 for (ir = bb->getFirst(); ir; ir = ir->next)
3785 ir->serial = serial++;
3786
3787 for (ir = bb->getFirst(); ir; ir = next) {
3788 int s;
3789 Value *src = NULL;
3790
3791 next = ir->next;
3792
3793 if (ir->fixed) {
3794 ops[ir->op].insert(ir);
3795 continue;
3796 }
3797
3798 for (s = 0; ir->srcExists(s); ++s)
3799 if (ir->getSrc(s)->asLValue())
3800 if (!src || ir->getSrc(s)->refCount() < src->refCount())
3801 src = ir->getSrc(s);
3802
3803 if (src) {
3804 for (Value::UseIterator it = src->uses.begin();
3805 it != src->uses.end(); ++it) {
3806 Instruction *ik = (*it)->getInsn();
3807 if (ik && ik->bb == ir->bb && ik->serial < ir->serial)
3808 if (tryReplace(&ir, ik))
3809 break;
3810 }
3811 } else {
3812 DLLIST_FOR_EACH(&ops[ir->op], iter)
3813 {
3814 Instruction *ik = reinterpret_cast<Instruction *>(iter.get());
3815 if (tryReplace(&ir, ik))
3816 break;
3817 }
3818 }
3819
3820 if (ir)
3821 ops[ir->op].insert(ir);
3822 else
3823 ++replaced;
3824 }
3825 for (unsigned int i = 0; i <= OP_LAST; ++i)
3826 ops[i].clear();
3827
3828 } while (replaced);
3829
3830 return true;
3831 }
3832
3833 // =============================================================================
3834
3835 // Remove computations of unused values.
3836 class DeadCodeElim : public Pass
3837 {
3838 public:
3839 bool buryAll(Program *);
3840
3841 private:
3842 virtual bool visit(BasicBlock *);
3843
3844 void checkSplitLoad(Instruction *ld); // for partially dead loads
3845
3846 unsigned int deadCount;
3847 };
3848
3849 bool
3850 DeadCodeElim::buryAll(Program *prog)
3851 {
3852 do {
3853 deadCount = 0;
3854 if (!this->run(prog, false, false))
3855 return false;
3856 } while (deadCount);
3857
3858 return true;
3859 }
3860
3861 bool
3862 DeadCodeElim::visit(BasicBlock *bb)
3863 {
3864 Instruction *prev;
3865
3866 for (Instruction *i = bb->getExit(); i; i = prev) {
3867 prev = i->prev;
3868 if (i->isDead()) {
3869 ++deadCount;
3870 delete_Instruction(prog, i);
3871 } else
3872 if (i->defExists(1) &&
3873 i->subOp == 0 &&
3874 (i->op == OP_VFETCH || i->op == OP_LOAD)) {
3875 checkSplitLoad(i);
3876 } else
3877 if (i->defExists(0) && !i->getDef(0)->refCount()) {
3878 if (i->op == OP_ATOM ||
3879 i->op == OP_SUREDP ||
3880 i->op == OP_SUREDB) {
3881 i->setDef(0, NULL);
3882 if (i->op == OP_ATOM && i->subOp == NV50_IR_SUBOP_ATOM_EXCH) {
3883 i->cache = CACHE_CV;
3884 i->op = OP_STORE;
3885 i->subOp = 0;
3886 }
3887 } else if (i->op == OP_LOAD && i->subOp == NV50_IR_SUBOP_LOAD_LOCKED) {
3888 i->setDef(0, i->getDef(1));
3889 i->setDef(1, NULL);
3890 }
3891 }
3892 }
3893 return true;
3894 }
3895
3896 // Each load can go into up to 4 destinations, any of which might potentially
3897 // be dead (i.e. a hole). These can always be split into 2 loads, independent
3898 // of where the holes are. We find the first contiguous region, put it into
3899 // the first load, and then put the second contiguous region into the second
3900 // load. There can be at most 2 contiguous regions.
3901 //
3902 // Note that there are some restrictions, for example it's not possible to do
3903 // a 64-bit load that's not 64-bit aligned, so such a load has to be split
3904 // up. Also hardware doesn't support 96-bit loads, so those also have to be
3905 // split into a 64-bit and 32-bit load.
3906 void
3907 DeadCodeElim::checkSplitLoad(Instruction *ld1)
3908 {
3909 Instruction *ld2 = NULL; // can get at most 2 loads
3910 Value *def1[4];
3911 Value *def2[4];
3912 int32_t addr1, addr2;
3913 int32_t size1, size2;
3914 int d, n1, n2;
3915 uint32_t mask = 0xffffffff;
3916
3917 for (d = 0; ld1->defExists(d); ++d)
3918 if (!ld1->getDef(d)->refCount() && ld1->getDef(d)->reg.data.id < 0)
3919 mask &= ~(1 << d);
3920 if (mask == 0xffffffff)
3921 return;
3922
3923 addr1 = ld1->getSrc(0)->reg.data.offset;
3924 n1 = n2 = 0;
3925 size1 = size2 = 0;
3926
3927 // Compute address/width for first load
3928 for (d = 0; ld1->defExists(d); ++d) {
3929 if (mask & (1 << d)) {
3930 if (size1 && (addr1 & 0x7))
3931 break;
3932 def1[n1] = ld1->getDef(d);
3933 size1 += def1[n1++]->reg.size;
3934 } else
3935 if (!n1) {
3936 addr1 += ld1->getDef(d)->reg.size;
3937 } else {
3938 break;
3939 }
3940 }
3941
3942 // Scale back the size of the first load until it can be loaded. This
3943 // typically happens for TYPE_B96 loads.
3944 while (n1 &&
3945 !prog->getTarget()->isAccessSupported(ld1->getSrc(0)->reg.file,
3946 typeOfSize(size1))) {
3947 size1 -= def1[--n1]->reg.size;
3948 d--;
3949 }
3950
3951 // Compute address/width for second load
3952 for (addr2 = addr1 + size1; ld1->defExists(d); ++d) {
3953 if (mask & (1 << d)) {
3954 assert(!size2 || !(addr2 & 0x7));
3955 def2[n2] = ld1->getDef(d);
3956 size2 += def2[n2++]->reg.size;
3957 } else if (!n2) {
3958 assert(!n2);
3959 addr2 += ld1->getDef(d)->reg.size;
3960 } else {
3961 break;
3962 }
3963 }
3964
3965 // Make sure that we've processed all the values
3966 for (; ld1->defExists(d); ++d)
3967 assert(!(mask & (1 << d)));
3968
3969 updateLdStOffset(ld1, addr1, func);
3970 ld1->setType(typeOfSize(size1));
3971 for (d = 0; d < 4; ++d)
3972 ld1->setDef(d, (d < n1) ? def1[d] : NULL);
3973
3974 if (!n2)
3975 return;
3976
3977 ld2 = cloneShallow(func, ld1);
3978 updateLdStOffset(ld2, addr2, func);
3979 ld2->setType(typeOfSize(size2));
3980 for (d = 0; d < 4; ++d)
3981 ld2->setDef(d, (d < n2) ? def2[d] : NULL);
3982
3983 ld1->bb->insertAfter(ld1, ld2);
3984 }
3985
3986 // =============================================================================
3987
3988 #define RUN_PASS(l, n, f) \
3989 if (level >= (l)) { \
3990 if (dbgFlags & NV50_IR_DEBUG_VERBOSE) \
3991 INFO("PEEPHOLE: %s\n", #n); \
3992 n pass; \
3993 if (!pass.f(this)) \
3994 return false; \
3995 }
3996
3997 bool
3998 Program::optimizeSSA(int level)
3999 {
4000 RUN_PASS(1, DeadCodeElim, buryAll);
4001 RUN_PASS(1, CopyPropagation, run);
4002 RUN_PASS(1, MergeSplits, run);
4003 RUN_PASS(2, GlobalCSE, run);
4004 RUN_PASS(1, LocalCSE, run);
4005 RUN_PASS(2, AlgebraicOpt, run);
4006 RUN_PASS(2, ModifierFolding, run); // before load propagation -> less checks
4007 RUN_PASS(1, ConstantFolding, foldAll);
4008 RUN_PASS(0, Split64BitOpPreRA, run);
4009 RUN_PASS(2, LateAlgebraicOpt, run);
4010 RUN_PASS(1, LoadPropagation, run);
4011 RUN_PASS(1, IndirectPropagation, run);
4012 RUN_PASS(2, MemoryOpt, run);
4013 RUN_PASS(2, LocalCSE, run);
4014 RUN_PASS(0, DeadCodeElim, buryAll);
4015
4016 return true;
4017 }
4018
4019 bool
4020 Program::optimizePostRA(int level)
4021 {
4022 RUN_PASS(2, FlatteningPass, run);
4023 RUN_PASS(2, PostRaLoadPropagation, run);
4024
4025 return true;
4026 }
4027
4028 }