2 * Copyright 2011 Christoph Bumiller
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:
11 * The above copyright notice and this permission notice shall be included in
12 * all copies or substantial portions of the Software.
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.
23 #include "codegen/nv50_ir.h"
24 #include "codegen/nv50_ir_target.h"
25 #include "codegen/nv50_ir_build_util.h"
28 #include "util/u_math.h"
34 Instruction::isNop() const
36 if (op == OP_PHI || op == OP_SPLIT || op == OP_MERGE || op == OP_CONSTRAINT)
38 if (terminator || join) // XXX: should terminator imply flow ?
42 if (!fixed && op == OP_NOP)
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");
52 if (op == OP_MOV || op == OP_UNION) {
53 if (!getDef(0)->equals(getSrc(0)))
56 if (!def(0).rep()->equals(getSrc(1)))
64 bool Instruction::isDead() const
69 op == OP_SUSTB || op == OP_SUSTP || op == OP_SUREDP || op == OP_SUREDB ||
73 for (int d = 0; defExists(d); ++d)
74 if (getDef(d)->refCount() || getDef(d)->reg.data.id >= 0)
77 if (terminator || asFlow())
85 // =============================================================================
87 class CopyPropagation : public Pass
90 virtual bool visit(BasicBlock *);
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.
97 CopyPropagation::visit(BasicBlock *bb)
99 Instruction *mov, *si, *next;
101 for (mov = bb->getEntry(); mov; mov = next) {
103 if (mov->op != OP_MOV || mov->fixed || !mov->getSrc(0)->asLValue())
105 if (mov->getPredicate())
107 if (mov->def(0).getFile() != mov->src(0).getFile())
109 si = mov->getSrc(0)->getInsn();
110 if (mov->getDef(0)->reg.data.id < 0 && si && si->op != OP_PHI) {
112 mov->def(0).replace(mov->getSrc(0), false);
113 delete_Instruction(prog, mov);
119 // =============================================================================
121 class MergeSplits : public Pass
124 virtual bool visit(BasicBlock *);
127 // For SPLIT / MERGE pairs that operate on the same registers, replace the
128 // post-merge def with the SPLIT's source.
130 MergeSplits::visit(BasicBlock *bb)
132 Instruction *i, *next, *si;
134 for (i = bb->getEntry(); i; i = next) {
136 if (i->op != OP_MERGE || typeSizeof(i->dType) != 8)
138 si = i->getSrc(0)->getInsn();
139 if (si->op != OP_SPLIT || si != i->getSrc(1)->getInsn())
141 i->def(0).replace(si->getSrc(0), false);
142 delete_Instruction(prog, i);
148 // =============================================================================
150 class LoadPropagation : public Pass
153 virtual bool visit(BasicBlock *);
155 void checkSwapSrc01(Instruction *);
157 bool isCSpaceLoad(Instruction *);
158 bool isImmd32Load(Instruction *);
159 bool isAttribOrSharedLoad(Instruction *);
163 LoadPropagation::isCSpaceLoad(Instruction *ld)
165 return ld && ld->op == OP_LOAD && ld->src(0).getFile() == FILE_MEMORY_CONST;
169 LoadPropagation::isImmd32Load(Instruction *ld)
171 if (!ld || (ld->op != OP_MOV) || (typeSizeof(ld->dType) != 4))
173 return ld->src(0).getFile() == FILE_IMMEDIATE;
177 LoadPropagation::isAttribOrSharedLoad(Instruction *ld)
180 (ld->op == OP_VFETCH ||
181 (ld->op == OP_LOAD &&
182 (ld->src(0).getFile() == FILE_SHADER_INPUT ||
183 ld->src(0).getFile() == FILE_MEMORY_SHARED)));
187 LoadPropagation::checkSwapSrc01(Instruction *insn)
189 if (!prog->getTarget()->getOpInfo(insn).commutative)
190 if (insn->op != OP_SET && insn->op != OP_SLCT)
192 if (insn->src(1).getFile() != FILE_GPR)
195 Instruction *i0 = insn->getSrc(0)->getInsn();
196 Instruction *i1 = insn->getSrc(1)->getInsn();
198 if (isCSpaceLoad(i0)) {
199 if (!isCSpaceLoad(i1))
200 insn->swapSources(0, 1);
204 if (isImmd32Load(i0)) {
205 if (!isCSpaceLoad(i1) && !isImmd32Load(i1))
206 insn->swapSources(0, 1);
210 if (isAttribOrSharedLoad(i1)) {
211 if (!isAttribOrSharedLoad(i0))
212 insn->swapSources(0, 1);
219 if (insn->op == OP_SET || insn->op == OP_SET_AND ||
220 insn->op == OP_SET_OR || insn->op == OP_SET_XOR)
221 insn->asCmp()->setCond = reverseCondCode(insn->asCmp()->setCond);
223 if (insn->op == OP_SLCT)
224 insn->asCmp()->setCond = inverseCondCode(insn->asCmp()->setCond);
228 LoadPropagation::visit(BasicBlock *bb)
230 const Target *targ = prog->getTarget();
233 for (Instruction *i = bb->getEntry(); i; i = next) {
236 if (i->op == OP_CALL) // calls have args as sources, they must be in regs
239 if (i->op == OP_PFETCH) // pfetch expects arg1 to be a reg
245 for (int s = 0; i->srcExists(s); ++s) {
246 Instruction *ld = i->getSrc(s)->getInsn();
248 if (!ld || ld->fixed || (ld->op != OP_LOAD && ld->op != OP_MOV))
250 if (!targ->insnCanLoad(i, s, ld))
254 i->setSrc(s, ld->getSrc(0));
255 if (ld->src(0).isIndirect(0))
256 i->setIndirect(s, 0, ld->getIndirect(0, 0));
258 if (ld->getDef(0)->refCount() == 0)
259 delete_Instruction(prog, ld);
265 // =============================================================================
267 // Evaluate constant expressions.
268 class ConstantFolding : public Pass
271 bool foldAll(Program *);
274 virtual bool visit(BasicBlock *);
276 void expr(Instruction *, ImmediateValue&, ImmediateValue&);
277 void expr(Instruction *, ImmediateValue&, ImmediateValue&, ImmediateValue&);
278 void opnd(Instruction *, ImmediateValue&, int s);
280 void unary(Instruction *, const ImmediateValue&);
282 void tryCollapseChainedMULs(Instruction *, const int s, ImmediateValue&);
284 CmpInstruction *findOriginForTestWithZero(Value *);
286 unsigned int foldCount;
291 // TODO: remember generated immediates and only revisit these
293 ConstantFolding::foldAll(Program *prog)
295 unsigned int iterCount = 0;
300 } while (foldCount && ++iterCount < 2);
305 ConstantFolding::visit(BasicBlock *bb)
307 Instruction *i, *next;
309 for (i = bb->getEntry(); i; i = next) {
311 if (i->op == OP_MOV || i->op == OP_CALL)
314 ImmediateValue src0, src1, src2;
316 if (i->srcExists(2) &&
317 i->src(0).getImmediate(src0) &&
318 i->src(1).getImmediate(src1) &&
319 i->src(2).getImmediate(src2))
320 expr(i, src0, src1, src2);
322 if (i->srcExists(1) &&
323 i->src(0).getImmediate(src0) && i->src(1).getImmediate(src1))
326 if (i->srcExists(0) && i->src(0).getImmediate(src0))
329 if (i->srcExists(1) && i->src(1).getImmediate(src1))
336 ConstantFolding::findOriginForTestWithZero(Value *value)
340 Instruction *insn = value->getInsn();
342 if (insn->asCmp() && insn->op != OP_SLCT)
343 return insn->asCmp();
345 /* Sometimes mov's will sneak in as a result of other folding. This gets
348 if (insn->op == OP_MOV)
349 return findOriginForTestWithZero(insn->getSrc(0));
351 /* Deal with AND 1.0 here since nv50 can't fold into boolean float */
352 if (insn->op == OP_AND) {
355 if (!insn->src(s).getImmediate(imm)) {
357 if (!insn->src(s).getImmediate(imm))
360 if (imm.reg.data.f32 != 1.0f)
362 /* TODO: Come up with a way to handle the condition being inverted */
363 if (insn->src(!s).mod != Modifier(0))
365 return findOriginForTestWithZero(insn->getSrc(!s));
372 Modifier::applyTo(ImmediateValue& imm) const
374 if (!bits) // avoid failure if imm.reg.type is unhandled (e.g. b128)
376 switch (imm.reg.type) {
378 if (bits & NV50_IR_MOD_ABS)
379 imm.reg.data.f32 = fabsf(imm.reg.data.f32);
380 if (bits & NV50_IR_MOD_NEG)
381 imm.reg.data.f32 = -imm.reg.data.f32;
382 if (bits & NV50_IR_MOD_SAT) {
383 if (imm.reg.data.f32 < 0.0f)
384 imm.reg.data.f32 = 0.0f;
386 if (imm.reg.data.f32 > 1.0f)
387 imm.reg.data.f32 = 1.0f;
389 assert(!(bits & NV50_IR_MOD_NOT));
392 case TYPE_S8: // NOTE: will be extended
395 case TYPE_U8: // NOTE: treated as signed
398 if (bits & NV50_IR_MOD_ABS)
399 imm.reg.data.s32 = (imm.reg.data.s32 >= 0) ?
400 imm.reg.data.s32 : -imm.reg.data.s32;
401 if (bits & NV50_IR_MOD_NEG)
402 imm.reg.data.s32 = -imm.reg.data.s32;
403 if (bits & NV50_IR_MOD_NOT)
404 imm.reg.data.s32 = ~imm.reg.data.s32;
408 if (bits & NV50_IR_MOD_ABS)
409 imm.reg.data.f64 = fabs(imm.reg.data.f64);
410 if (bits & NV50_IR_MOD_NEG)
411 imm.reg.data.f64 = -imm.reg.data.f64;
412 if (bits & NV50_IR_MOD_SAT) {
413 if (imm.reg.data.f64 < 0.0)
414 imm.reg.data.f64 = 0.0;
416 if (imm.reg.data.f64 > 1.0)
417 imm.reg.data.f64 = 1.0;
419 assert(!(bits & NV50_IR_MOD_NOT));
423 assert(!"invalid/unhandled type");
424 imm.reg.data.u64 = 0;
430 Modifier::getOp() const
433 case NV50_IR_MOD_ABS: return OP_ABS;
434 case NV50_IR_MOD_NEG: return OP_NEG;
435 case NV50_IR_MOD_SAT: return OP_SAT;
436 case NV50_IR_MOD_NOT: return OP_NOT;
445 ConstantFolding::expr(Instruction *i,
446 ImmediateValue &imm0, ImmediateValue &imm1)
448 struct Storage *const a = &imm0.reg, *const b = &imm1.reg;
451 memset(&res.data, 0, sizeof(res.data));
457 if (i->dnz && i->dType == TYPE_F32) {
458 if (!isfinite(a->data.f32))
460 if (!isfinite(b->data.f32))
465 res.data.f32 = a->data.f32 * b->data.f32 * exp2f(i->postFactor);
467 case TYPE_F64: res.data.f64 = a->data.f64 * b->data.f64; break;
469 if (i->subOp == NV50_IR_SUBOP_MUL_HIGH) {
470 res.data.s32 = ((int64_t)a->data.s32 * b->data.s32) >> 32;
475 if (i->subOp == NV50_IR_SUBOP_MUL_HIGH) {
476 res.data.u32 = ((uint64_t)a->data.u32 * b->data.u32) >> 32;
479 res.data.u32 = a->data.u32 * b->data.u32; break;
485 if (b->data.u32 == 0)
488 case TYPE_F32: res.data.f32 = a->data.f32 / b->data.f32; break;
489 case TYPE_F64: res.data.f64 = a->data.f64 / b->data.f64; break;
490 case TYPE_S32: res.data.s32 = a->data.s32 / b->data.s32; break;
491 case TYPE_U32: res.data.u32 = a->data.u32 / b->data.u32; break;
498 case TYPE_F32: res.data.f32 = a->data.f32 + b->data.f32; break;
499 case TYPE_F64: res.data.f64 = a->data.f64 + b->data.f64; break;
501 case TYPE_U32: res.data.u32 = a->data.u32 + b->data.u32; break;
508 case TYPE_F32: res.data.f32 = pow(a->data.f32, b->data.f32); break;
509 case TYPE_F64: res.data.f64 = pow(a->data.f64, b->data.f64); break;
516 case TYPE_F32: res.data.f32 = MAX2(a->data.f32, b->data.f32); break;
517 case TYPE_F64: res.data.f64 = MAX2(a->data.f64, b->data.f64); break;
518 case TYPE_S32: res.data.s32 = MAX2(a->data.s32, b->data.s32); break;
519 case TYPE_U32: res.data.u32 = MAX2(a->data.u32, b->data.u32); break;
526 case TYPE_F32: res.data.f32 = MIN2(a->data.f32, b->data.f32); break;
527 case TYPE_F64: res.data.f64 = MIN2(a->data.f64, b->data.f64); break;
528 case TYPE_S32: res.data.s32 = MIN2(a->data.s32, b->data.s32); break;
529 case TYPE_U32: res.data.u32 = MIN2(a->data.u32, b->data.u32); break;
535 res.data.u64 = a->data.u64 & b->data.u64;
538 res.data.u64 = a->data.u64 | b->data.u64;
541 res.data.u64 = a->data.u64 ^ b->data.u64;
544 res.data.u32 = a->data.u32 << b->data.u32;
548 case TYPE_S32: res.data.s32 = a->data.s32 >> b->data.u32; break;
549 case TYPE_U32: res.data.u32 = a->data.u32 >> b->data.u32; break;
555 if (a->data.u32 != b->data.u32)
557 res.data.u32 = a->data.u32;
560 int offset = b->data.u32 & 0xff;
561 int width = (b->data.u32 >> 8) & 0xff;
568 if (width + offset < 32) {
570 lshift = 32 - width - offset;
572 if (i->subOp == NV50_IR_SUBOP_EXTBF_REV)
573 res.data.u32 = util_bitreverse(a->data.u32);
575 res.data.u32 = a->data.u32;
577 case TYPE_S32: res.data.s32 = (res.data.s32 << lshift) >> rshift; break;
578 case TYPE_U32: res.data.u32 = (res.data.u32 << lshift) >> rshift; break;
585 res.data.u32 = util_bitcount(a->data.u32 & b->data.u32);
588 // The two arguments to pfetch are logically added together. Normally
589 // the second argument will not be constant, but that can happen.
590 res.data.u32 = a->data.u32 + b->data.u32;
597 i->src(0).mod = Modifier(0);
598 i->src(1).mod = Modifier(0);
601 i->setSrc(0, new_ImmediateValue(i->bb->getProgram(), res.data.u32));
604 i->getSrc(0)->reg.data = res.data;
611 /* Move the immediate to the second arg, otherwise the ADD operation
614 i->setSrc(1, i->getSrc(0));
615 i->setSrc(0, i->getSrc(2));
616 i->src(0).mod = i->src(2).mod;
620 if (i->src(0).getImmediate(src0))
621 expr(i, src0, *i->getSrc(1)->asImm());
622 if (i->saturate && !prog->getTarget()->isSatSupported(i)) {
623 bld.setPosition(i, false);
624 i->setSrc(1, bld.loadImm(NULL, res.data.u32));
629 // Leave PFETCH alone... we just folded its 2 args into 1.
632 i->op = i->saturate ? OP_SAT : OP_MOV; /* SAT handled by unary() */
639 ConstantFolding::expr(Instruction *i,
640 ImmediateValue &imm0,
641 ImmediateValue &imm1,
642 ImmediateValue &imm2)
644 struct Storage *const a = &imm0.reg, *const b = &imm1.reg, *const c = &imm2.reg;
647 memset(&res.data, 0, sizeof(res.data));
651 int offset = b->data.u32 & 0xff;
652 int width = (b->data.u32 >> 8) & 0xff;
653 unsigned bitmask = ((1 << width) - 1) << offset;
654 res.data.u32 = ((a->data.u32 << offset) & bitmask) | (c->data.u32 & ~bitmask);
662 i->src(0).mod = Modifier(0);
663 i->src(1).mod = Modifier(0);
664 i->src(2).mod = Modifier(0);
666 i->setSrc(0, new_ImmediateValue(i->bb->getProgram(), res.data.u32));
670 i->getSrc(0)->reg.data = res.data;
676 ConstantFolding::unary(Instruction *i, const ImmediateValue &imm)
680 if (i->dType != TYPE_F32)
683 case OP_NEG: res.data.f32 = -imm.reg.data.f32; break;
684 case OP_ABS: res.data.f32 = fabsf(imm.reg.data.f32); break;
685 case OP_SAT: res.data.f32 = CLAMP(imm.reg.data.f32, 0.0f, 1.0f); break;
686 case OP_RCP: res.data.f32 = 1.0f / imm.reg.data.f32; break;
687 case OP_RSQ: res.data.f32 = 1.0f / sqrtf(imm.reg.data.f32); break;
688 case OP_LG2: res.data.f32 = log2f(imm.reg.data.f32); break;
689 case OP_EX2: res.data.f32 = exp2f(imm.reg.data.f32); break;
690 case OP_SIN: res.data.f32 = sinf(imm.reg.data.f32); break;
691 case OP_COS: res.data.f32 = cosf(imm.reg.data.f32); break;
692 case OP_SQRT: res.data.f32 = sqrtf(imm.reg.data.f32); break;
695 // these should be handled in subsequent OP_SIN/COS/EX2
696 res.data.f32 = imm.reg.data.f32;
702 i->setSrc(0, new_ImmediateValue(i->bb->getProgram(), res.data.f32));
703 i->src(0).mod = Modifier(0);
707 ConstantFolding::tryCollapseChainedMULs(Instruction *mul2,
708 const int s, ImmediateValue& imm2)
710 const int t = s ? 0 : 1;
712 Instruction *mul1 = NULL; // mul1 before mul2
714 float f = imm2.reg.data.f32 * exp2f(mul2->postFactor);
717 assert(mul2->op == OP_MUL && mul2->dType == TYPE_F32);
719 if (mul2->getSrc(t)->refCount() == 1) {
720 insn = mul2->getSrc(t)->getInsn();
721 if (!mul2->src(t).mod && insn->op == OP_MUL && insn->dType == TYPE_F32)
723 if (mul1 && !mul1->saturate) {
726 if (mul1->src(s1 = 0).getImmediate(imm1) ||
727 mul1->src(s1 = 1).getImmediate(imm1)) {
728 bld.setPosition(mul1, false);
730 // d = mul a, imm2 -> d = mul r, (imm1 * imm2)
731 mul1->setSrc(s1, bld.loadImm(NULL, f * imm1.reg.data.f32));
732 mul1->src(s1).mod = Modifier(0);
733 mul2->def(0).replace(mul1->getDef(0), false);
734 mul1->saturate = mul2->saturate;
736 if (prog->getTarget()->isPostMultiplySupported(OP_MUL, f, e)) {
738 // d = mul c, imm -> d = mul_x_imm a, b
739 mul1->postFactor = e;
740 mul2->def(0).replace(mul1->getDef(0), false);
742 mul1->src(0).mod *= Modifier(NV50_IR_MOD_NEG);
743 mul1->saturate = mul2->saturate;
748 if (mul2->getDef(0)->refCount() == 1 && !mul2->saturate) {
750 // d = mul b, c -> d = mul_x_imm a, c
752 insn = (*mul2->getDef(0)->uses.begin())->getInsn();
757 s2 = insn->getSrc(0) == mul1->getDef(0) ? 0 : 1;
759 if (insn->op == OP_MUL && insn->dType == TYPE_F32)
760 if (!insn->src(s2).mod && !insn->src(t2).getImmediate(imm1))
762 if (mul2 && prog->getTarget()->isPostMultiplySupported(OP_MUL, f, e)) {
763 mul2->postFactor = e;
764 mul2->setSrc(s2, mul1->src(t));
766 mul2->src(s2).mod *= Modifier(NV50_IR_MOD_NEG);
772 ConstantFolding::opnd(Instruction *i, ImmediateValue &imm0, int s)
775 const operation op = i->op;
776 Instruction *newi = i;
780 if (i->dType == TYPE_F32)
781 tryCollapseChainedMULs(i, s, imm0);
783 if (i->subOp == NV50_IR_SUBOP_MUL_HIGH) {
784 assert(!isFloatType(i->sType));
785 if (imm0.isInteger(1) && i->dType == TYPE_S32) {
786 bld.setPosition(i, false);
787 // Need to set to the sign value, which is a compare.
788 newi = bld.mkCmp(OP_SET, CC_LT, TYPE_S32, i->getDef(0),
789 TYPE_S32, i->getSrc(t), bld.mkImm(0));
790 delete_Instruction(prog, i);
791 } else if (imm0.isInteger(0) || imm0.isInteger(1)) {
792 // The high bits can't be set in this case (either mul by 0 or
796 i->setSrc(0, new_ImmediateValue(prog, 0u));
797 i->src(0).mod = Modifier(0);
799 } else if (!imm0.isNegative() && imm0.isPow2()) {
800 // Translate into a shift
804 imm0.reg.data.u32 = 32 - imm0.reg.data.u32;
805 i->setSrc(0, i->getSrc(t));
806 i->src(0).mod = i->src(t).mod;
807 i->setSrc(1, new_ImmediateValue(prog, imm0.reg.data.u32));
811 if (imm0.isInteger(0)) {
813 i->setSrc(0, new_ImmediateValue(prog, 0u));
814 i->src(0).mod = Modifier(0);
818 if (!i->postFactor && (imm0.isInteger(1) || imm0.isInteger(-1))) {
819 if (imm0.isNegative())
820 i->src(t).mod = i->src(t).mod ^ Modifier(NV50_IR_MOD_NEG);
821 i->op = i->src(t).mod.getOp();
823 i->setSrc(0, i->getSrc(1));
824 i->src(0).mod = i->src(1).mod;
831 if (!i->postFactor && (imm0.isInteger(2) || imm0.isInteger(-2))) {
832 if (imm0.isNegative())
833 i->src(t).mod = i->src(t).mod ^ Modifier(NV50_IR_MOD_NEG);
835 i->setSrc(s, i->getSrc(t));
836 i->src(s).mod = i->src(t).mod;
838 if (!isFloatType(i->sType) && !imm0.isNegative() && imm0.isPow2()) {
841 i->setSrc(0, i->getSrc(t));
842 i->src(0).mod = i->src(t).mod;
843 i->setSrc(1, new_ImmediateValue(prog, imm0.reg.data.u32));
848 if (imm0.isInteger(0)) {
849 i->setSrc(0, i->getSrc(2));
850 i->src(0).mod = i->src(2).mod;
853 i->op = i->src(0).mod.getOp();
857 if (imm0.isInteger(1) || imm0.isInteger(-1)) {
858 if (imm0.isNegative())
859 i->src(t).mod = i->src(t).mod ^ Modifier(NV50_IR_MOD_NEG);
861 i->setSrc(0, i->getSrc(1));
862 i->src(0).mod = i->src(1).mod;
864 i->setSrc(1, i->getSrc(2));
865 i->src(1).mod = i->src(2).mod;
873 if (imm0.isInteger(0)) {
875 i->setSrc(0, i->getSrc(1));
876 i->src(0).mod = i->src(1).mod;
879 i->op = i->src(0).mod.getOp();
881 i->src(0).mod = Modifier(0);
886 if (s != 1 || (i->dType != TYPE_S32 && i->dType != TYPE_U32))
888 bld.setPosition(i, false);
889 if (imm0.reg.data.u32 == 0) {
892 if (imm0.reg.data.u32 == 1) {
896 if (i->dType == TYPE_U32 && imm0.isPow2()) {
898 i->setSrc(1, bld.mkImm(util_logbase2(imm0.reg.data.u32)));
900 if (i->dType == TYPE_U32) {
903 const uint32_t d = imm0.reg.data.u32;
906 uint32_t l = util_logbase2(d);
907 if (((uint32_t)1 << l) < d)
909 m = (((uint64_t)1 << 32) * (((uint64_t)1 << l) - d)) / d + 1;
915 mul = bld.mkOp2(OP_MUL, TYPE_U32, tA, i->getSrc(0),
916 bld.loadImm(NULL, m));
917 mul->subOp = NV50_IR_SUBOP_MUL_HIGH;
918 bld.mkOp2(OP_SUB, TYPE_U32, tB, i->getSrc(0), tA);
921 bld.mkOp2(OP_SHR, TYPE_U32, tA, tB, bld.mkImm(r));
924 tB = s ? bld.getSSA() : i->getDef(0);
925 newi = bld.mkOp2(OP_ADD, TYPE_U32, tB, mul->getDef(0), tA);
927 bld.mkOp2(OP_SHR, TYPE_U32, i->getDef(0), tB, bld.mkImm(s));
929 delete_Instruction(prog, i);
931 if (imm0.reg.data.s32 == -1) {
937 const int32_t d = imm0.reg.data.s32;
939 int32_t l = util_logbase2(static_cast<unsigned>(abs(d)));
940 if ((1 << l) < abs(d))
944 m = ((uint64_t)1 << (32 + l - 1)) / abs(d) + 1 - ((uint64_t)1 << 32);
948 bld.mkOp3(OP_MAD, TYPE_S32, tA, i->getSrc(0), bld.loadImm(NULL, m),
949 i->getSrc(0))->subOp = NV50_IR_SUBOP_MUL_HIGH;
951 bld.mkOp2(OP_SHR, TYPE_S32, tB, tA, bld.mkImm(l - 1));
955 bld.mkCmp(OP_SET, CC_LT, TYPE_S32, tA, TYPE_S32, i->getSrc(0), bld.mkImm(0));
956 tD = (d < 0) ? bld.getSSA() : i->getDef(0)->asLValue();
957 newi = bld.mkOp2(OP_SUB, TYPE_U32, tD, tB, tA);
959 bld.mkOp1(OP_NEG, TYPE_S32, i->getDef(0), tB);
961 delete_Instruction(prog, i);
966 if (i->sType == TYPE_U32 && imm0.isPow2()) {
967 bld.setPosition(i, false);
969 i->setSrc(1, bld.loadImm(NULL, imm0.reg.data.u32 - 1));
973 case OP_SET: // TODO: SET_AND,OR,XOR
975 /* This optimizes the case where the output of a set is being compared
976 * to zero. Since the set can only produce 0/-1 (int) or 0/1 (float), we
977 * can be a lot cleverer in our comparison.
979 CmpInstruction *si = findOriginForTestWithZero(i->getSrc(t));
981 if (imm0.reg.data.u32 != 0 || !si)
984 ccZ = (CondCode)((unsigned int)i->asCmp()->setCond & ~CC_U);
985 // We do everything assuming var (cmp) 0, reverse the condition if 0 is
988 ccZ = reverseCondCode(ccZ);
989 // If there is a negative modifier, we need to undo that, by flipping
990 // the comparison to zero.
991 if (i->src(t).mod.neg())
992 ccZ = reverseCondCode(ccZ);
993 // If this is a signed comparison, we expect the input to be a regular
994 // boolean, i.e. 0/-1. However the rest of the logic assumes that true
995 // is positive, so just flip the sign.
996 if (i->sType == TYPE_S32) {
997 assert(!isFloatType(si->dType));
998 ccZ = reverseCondCode(ccZ);
1001 case CC_LT: cc = CC_FL; break; // bool < 0 -- this is never true
1002 case CC_GE: cc = CC_TR; break; // bool >= 0 -- this is always true
1003 case CC_EQ: cc = inverseCondCode(cc); break; // bool == 0 -- !bool
1004 case CC_LE: cc = inverseCondCode(cc); break; // bool <= 0 -- !bool
1005 case CC_GT: break; // bool > 0 -- bool
1006 case CC_NE: break; // bool != 0 -- bool
1011 // Update the condition of this SET to be identical to the origin set,
1012 // but with the updated condition code. The original SET should get
1015 i->asCmp()->setCond = cc;
1016 i->setSrc(0, si->src(0));
1017 i->setSrc(1, si->src(1));
1018 if (si->srcExists(2))
1019 i->setSrc(2, si->src(2));
1020 i->sType = si->sType;
1026 CmpInstruction *cmp = i->getSrc(t)->getInsn()->asCmp();
1027 if (!cmp || cmp->op == OP_SLCT || cmp->getDef(0)->refCount() > 1)
1029 if (!prog->getTarget()->isOpSupported(cmp->op, TYPE_F32))
1031 if (imm0.reg.data.f32 != 1.0)
1033 if (i->getSrc(t)->getInsn()->dType != TYPE_U32)
1036 i->getSrc(t)->getInsn()->dType = TYPE_F32;
1037 if (i->src(t).mod != Modifier(0)) {
1038 assert(i->src(t).mod == Modifier(NV50_IR_MOD_NOT));
1039 i->src(t).mod = Modifier(0);
1040 cmp->setCond = inverseCondCode(cmp->setCond);
1045 i->setSrc(0, i->getSrc(t));
1053 if (s != 1 || i->src(0).mod != Modifier(0))
1055 // try to concatenate shifts
1056 Instruction *si = i->getSrc(0)->getInsn();
1057 if (!si || si->op != OP_SHL)
1059 ImmediateValue imm1;
1060 if (si->src(1).getImmediate(imm1)) {
1061 bld.setPosition(i, false);
1062 i->setSrc(0, si->getSrc(0));
1063 i->setSrc(1, bld.loadImm(NULL, imm0.reg.data.u32 + imm1.reg.data.u32));
1085 case TYPE_S32: res = util_last_bit_signed(imm0.reg.data.s32) - 1; break;
1086 case TYPE_U32: res = util_last_bit(imm0.reg.data.u32) - 1; break;
1090 if (i->subOp == NV50_IR_SUBOP_BFIND_SAMT && res >= 0)
1092 bld.setPosition(i, false); /* make sure bld is init'ed */
1093 i->setSrc(0, bld.mkImm(res));
1100 // Only deal with 1-arg POPCNT here
1101 if (i->srcExists(1))
1103 uint32_t res = util_bitcount(imm0.reg.data.u32);
1104 i->setSrc(0, new_ImmediateValue(i->bb->getProgram(), res));
1116 // =============================================================================
1118 // Merge modifier operations (ABS, NEG, NOT) into ValueRefs where allowed.
1119 class ModifierFolding : public Pass
1122 virtual bool visit(BasicBlock *);
1126 ModifierFolding::visit(BasicBlock *bb)
1128 const Target *target = prog->getTarget();
1130 Instruction *i, *next, *mi;
1133 for (i = bb->getEntry(); i; i = next) {
1136 if (0 && i->op == OP_SUB) {
1137 // turn "sub" into "add neg" (do we really want this ?)
1139 i->src(0).mod = i->src(0).mod ^ Modifier(NV50_IR_MOD_NEG);
1142 for (int s = 0; s < 3 && i->srcExists(s); ++s) {
1143 mi = i->getSrc(s)->getInsn();
1145 mi->predSrc >= 0 || mi->getDef(0)->refCount() > 8)
1147 if (i->sType == TYPE_U32 && mi->dType == TYPE_S32) {
1148 if ((i->op != OP_ADD &&
1150 (mi->op != OP_ABS &&
1154 if (i->sType != mi->dType) {
1157 if ((mod = Modifier(mi->op)) == Modifier(0))
1159 mod *= mi->src(0).mod;
1161 if ((i->op == OP_ABS) || i->src(s).mod.abs()) {
1162 // abs neg [abs] = abs
1163 mod = mod & Modifier(~(NV50_IR_MOD_NEG | NV50_IR_MOD_ABS));
1165 if ((i->op == OP_NEG) && mod.neg()) {
1167 // neg as both opcode and modifier on same insn is prohibited
1168 // neg neg abs = abs, neg neg = identity
1169 mod = mod & Modifier(~NV50_IR_MOD_NEG);
1170 i->op = mod.getOp();
1171 mod = mod & Modifier(~NV50_IR_MOD_ABS);
1172 if (mod == Modifier(0))
1176 if (target->isModSupported(i, s, mod)) {
1177 i->setSrc(s, mi->getSrc(0));
1178 i->src(s).mod *= mod;
1182 if (i->op == OP_SAT) {
1183 mi = i->getSrc(0)->getInsn();
1185 mi->getDef(0)->refCount() <= 1 && target->isSatSupported(mi)) {
1187 mi->setDef(0, i->getDef(0));
1188 delete_Instruction(prog, i);
1196 // =============================================================================
1198 // MUL + ADD -> MAD/FMA
1199 // MIN/MAX(a, a) -> a, etc.
1200 // SLCT(a, b, const) -> cc(const) ? a : b
1202 // MUL(MUL(a, b), const) -> MUL_Xconst(a, b)
1203 class AlgebraicOpt : public Pass
1206 virtual bool visit(BasicBlock *);
1208 void handleABS(Instruction *);
1209 bool handleADD(Instruction *);
1210 bool tryADDToMADOrSAD(Instruction *, operation toOp);
1211 void handleMINMAX(Instruction *);
1212 void handleRCP(Instruction *);
1213 void handleSLCT(Instruction *);
1214 void handleLOGOP(Instruction *);
1215 void handleCVT(Instruction *);
1216 void handleSUCLAMP(Instruction *);
1222 AlgebraicOpt::handleABS(Instruction *abs)
1224 Instruction *sub = abs->getSrc(0)->getInsn();
1227 !prog->getTarget()->isOpSupported(OP_SAD, abs->dType))
1229 // expect not to have mods yet, if we do, bail
1230 if (sub->src(0).mod || sub->src(1).mod)
1232 // hidden conversion ?
1233 ty = intTypeToSigned(sub->dType);
1234 if (abs->dType != abs->sType || ty != abs->sType)
1237 if ((sub->op != OP_ADD && sub->op != OP_SUB) ||
1238 sub->src(0).getFile() != FILE_GPR || sub->src(0).mod ||
1239 sub->src(1).getFile() != FILE_GPR || sub->src(1).mod)
1242 Value *src0 = sub->getSrc(0);
1243 Value *src1 = sub->getSrc(1);
1245 if (sub->op == OP_ADD) {
1246 Instruction *neg = sub->getSrc(1)->getInsn();
1247 if (neg && neg->op != OP_NEG) {
1248 neg = sub->getSrc(0)->getInsn();
1249 src0 = sub->getSrc(1);
1251 if (!neg || neg->op != OP_NEG ||
1252 neg->dType != neg->sType || neg->sType != ty)
1254 src1 = neg->getSrc(0);
1258 abs->moveSources(1, 2); // move sources >=1 up by 2
1260 abs->setType(sub->dType);
1261 abs->setSrc(0, src0);
1262 abs->setSrc(1, src1);
1263 bld.setPosition(abs, false);
1264 abs->setSrc(2, bld.loadImm(bld.getSSA(typeSizeof(ty)), 0));
1268 AlgebraicOpt::handleADD(Instruction *add)
1270 Value *src0 = add->getSrc(0);
1271 Value *src1 = add->getSrc(1);
1273 if (src0->reg.file != FILE_GPR || src1->reg.file != FILE_GPR)
1276 bool changed = false;
1277 if (!changed && prog->getTarget()->isOpSupported(OP_MAD, add->dType))
1278 changed = tryADDToMADOrSAD(add, OP_MAD);
1279 if (!changed && prog->getTarget()->isOpSupported(OP_SAD, add->dType))
1280 changed = tryADDToMADOrSAD(add, OP_SAD);
1284 // ADD(SAD(a,b,0), c) -> SAD(a,b,c)
1285 // ADD(MUL(a,b), c) -> MAD(a,b,c)
1287 AlgebraicOpt::tryADDToMADOrSAD(Instruction *add, operation toOp)
1289 Value *src0 = add->getSrc(0);
1290 Value *src1 = add->getSrc(1);
1293 const operation srcOp = toOp == OP_SAD ? OP_SAD : OP_MUL;
1294 const Modifier modBad = Modifier(~((toOp == OP_MAD) ? NV50_IR_MOD_NEG : 0));
1297 if (src0->refCount() == 1 &&
1298 src0->getUniqueInsn() && src0->getUniqueInsn()->op == srcOp)
1301 if (src1->refCount() == 1 &&
1302 src1->getUniqueInsn() && src1->getUniqueInsn()->op == srcOp)
1307 if ((src0->getUniqueInsn() && src0->getUniqueInsn()->bb != add->bb) ||
1308 (src1->getUniqueInsn() && src1->getUniqueInsn()->bb != add->bb))
1311 src = add->getSrc(s);
1313 if (src->getInsn()->postFactor)
1315 if (toOp == OP_SAD) {
1317 if (!src->getInsn()->src(2).getImmediate(imm))
1319 if (!imm.isInteger(0))
1323 mod[0] = add->src(0).mod;
1324 mod[1] = add->src(1).mod;
1325 mod[2] = src->getUniqueInsn()->src(0).mod;
1326 mod[3] = src->getUniqueInsn()->src(1).mod;
1328 if (((mod[0] | mod[1]) | (mod[2] | mod[3])) & modBad)
1332 add->subOp = src->getInsn()->subOp; // potentially mul-high
1334 add->setSrc(2, add->src(s ? 0 : 1));
1336 add->setSrc(0, src->getInsn()->getSrc(0));
1337 add->src(0).mod = mod[2] ^ mod[s];
1338 add->setSrc(1, src->getInsn()->getSrc(1));
1339 add->src(1).mod = mod[3];
1345 AlgebraicOpt::handleMINMAX(Instruction *minmax)
1347 Value *src0 = minmax->getSrc(0);
1348 Value *src1 = minmax->getSrc(1);
1350 if (src0 != src1 || src0->reg.file != FILE_GPR)
1352 if (minmax->src(0).mod == minmax->src(1).mod) {
1353 if (minmax->def(0).mayReplace(minmax->src(0))) {
1354 minmax->def(0).replace(minmax->src(0), false);
1355 minmax->bb->remove(minmax);
1357 minmax->op = OP_CVT;
1358 minmax->setSrc(1, NULL);
1362 // min(x, -x) = -abs(x)
1363 // min(x, -abs(x)) = -abs(x)
1364 // min(x, abs(x)) = x
1365 // max(x, -abs(x)) = x
1366 // max(x, abs(x)) = abs(x)
1367 // max(x, -x) = abs(x)
1372 AlgebraicOpt::handleRCP(Instruction *rcp)
1374 Instruction *si = rcp->getSrc(0)->getUniqueInsn();
1376 if (si && si->op == OP_RCP) {
1377 Modifier mod = rcp->src(0).mod * si->src(0).mod;
1378 rcp->op = mod.getOp();
1379 rcp->setSrc(0, si->getSrc(0));
1384 AlgebraicOpt::handleSLCT(Instruction *slct)
1386 if (slct->getSrc(2)->reg.file == FILE_IMMEDIATE) {
1387 if (slct->getSrc(2)->asImm()->compare(slct->asCmp()->setCond, 0.0f))
1388 slct->setSrc(0, slct->getSrc(1));
1390 if (slct->getSrc(0) != slct->getSrc(1)) {
1394 slct->setSrc(1, NULL);
1395 slct->setSrc(2, NULL);
1399 AlgebraicOpt::handleLOGOP(Instruction *logop)
1401 Value *src0 = logop->getSrc(0);
1402 Value *src1 = logop->getSrc(1);
1404 if (src0->reg.file != FILE_GPR || src1->reg.file != FILE_GPR)
1408 if ((logop->op == OP_AND || logop->op == OP_OR) &&
1409 logop->def(0).mayReplace(logop->src(0))) {
1410 logop->def(0).replace(logop->src(0), false);
1411 delete_Instruction(prog, logop);
1414 // try AND(SET, SET) -> SET_AND(SET)
1415 Instruction *set0 = src0->getInsn();
1416 Instruction *set1 = src1->getInsn();
1418 if (!set0 || set0->fixed || !set1 || set1->fixed)
1420 if (set1->op != OP_SET) {
1421 Instruction *xchg = set0;
1424 if (set1->op != OP_SET)
1427 operation redOp = (logop->op == OP_AND ? OP_SET_AND :
1428 logop->op == OP_XOR ? OP_SET_XOR : OP_SET_OR);
1429 if (!prog->getTarget()->isOpSupported(redOp, set1->sType))
1431 if (set0->op != OP_SET &&
1432 set0->op != OP_SET_AND &&
1433 set0->op != OP_SET_OR &&
1434 set0->op != OP_SET_XOR)
1436 if (set0->getDef(0)->refCount() > 1 &&
1437 set1->getDef(0)->refCount() > 1)
1439 if (set0->getPredicate() || set1->getPredicate())
1441 // check that they don't source each other
1442 for (int s = 0; s < 2; ++s)
1443 if (set0->getSrc(s) == set1->getDef(0) ||
1444 set1->getSrc(s) == set0->getDef(0))
1447 set0 = cloneForward(func, set0);
1448 set1 = cloneShallow(func, set1);
1449 logop->bb->insertAfter(logop, set1);
1450 logop->bb->insertAfter(logop, set0);
1452 set0->dType = TYPE_U8;
1453 set0->getDef(0)->reg.file = FILE_PREDICATE;
1454 set0->getDef(0)->reg.size = 1;
1455 set1->setSrc(2, set0->getDef(0));
1457 set1->setDef(0, logop->getDef(0));
1458 delete_Instruction(prog, logop);
1462 // F2I(NEG(SET with result 1.0f/0.0f)) -> SET with result -1/0
1464 // F2I(NEG(I2F(ABS(SET))))
1466 AlgebraicOpt::handleCVT(Instruction *cvt)
1468 if (cvt->sType != TYPE_F32 ||
1469 cvt->dType != TYPE_S32 || cvt->src(0).mod != Modifier(0))
1471 Instruction *insn = cvt->getSrc(0)->getInsn();
1472 if (!insn || insn->op != OP_NEG || insn->dType != TYPE_F32)
1474 if (insn->src(0).mod != Modifier(0))
1476 insn = insn->getSrc(0)->getInsn();
1478 // check for nv50 SET(-1,0) -> SET(1.0f/0.0f) chain and nvc0's f32 SET
1479 if (insn && insn->op == OP_CVT &&
1480 insn->dType == TYPE_F32 &&
1481 insn->sType == TYPE_S32) {
1482 insn = insn->getSrc(0)->getInsn();
1483 if (!insn || insn->op != OP_ABS || insn->sType != TYPE_S32 ||
1486 insn = insn->getSrc(0)->getInsn();
1487 if (!insn || insn->op != OP_SET || insn->dType != TYPE_U32)
1490 if (!insn || insn->op != OP_SET || insn->dType != TYPE_F32) {
1494 Instruction *bset = cloneShallow(func, insn);
1495 bset->dType = TYPE_U32;
1496 bset->setDef(0, cvt->getDef(0));
1497 cvt->bb->insertAfter(cvt, bset);
1498 delete_Instruction(prog, cvt);
1501 // SUCLAMP dst, (ADD b imm), k, 0 -> SUCLAMP dst, b, k, imm (if imm fits s6)
1503 AlgebraicOpt::handleSUCLAMP(Instruction *insn)
1506 int32_t val = insn->getSrc(2)->asImm()->reg.data.s32;
1510 assert(insn->srcExists(0) && insn->src(0).getFile() == FILE_GPR);
1512 // look for ADD (TODO: only count references by non-SUCLAMP)
1513 if (insn->getSrc(0)->refCount() > 1)
1515 add = insn->getSrc(0)->getInsn();
1516 if (!add || add->op != OP_ADD ||
1517 (add->dType != TYPE_U32 &&
1518 add->dType != TYPE_S32))
1521 // look for immediate
1522 for (s = 0; s < 2; ++s)
1523 if (add->src(s).getImmediate(imm))
1528 // determine if immediate fits
1529 val += imm.reg.data.s32;
1530 if (val > 31 || val < -32)
1532 // determine if other addend fits
1533 if (add->src(s).getFile() != FILE_GPR || add->src(s).mod != Modifier(0))
1536 bld.setPosition(insn, false); // make sure bld is init'ed
1538 insn->setSrc(2, bld.mkImm(val));
1539 insn->setSrc(0, add->getSrc(s));
1543 AlgebraicOpt::visit(BasicBlock *bb)
1546 for (Instruction *i = bb->getEntry(); i; i = next) {
1584 // =============================================================================
1587 updateLdStOffset(Instruction *ldst, int32_t offset, Function *fn)
1589 if (offset != ldst->getSrc(0)->reg.data.offset) {
1590 if (ldst->getSrc(0)->refCount() > 1)
1591 ldst->setSrc(0, cloneShallow(fn, ldst->getSrc(0)));
1592 ldst->getSrc(0)->reg.data.offset = offset;
1596 // Combine loads and stores, forward stores to loads where possible.
1597 class MemoryOpt : public Pass
1605 const Value *rel[2];
1613 bool overlaps(const Instruction *ldst) const;
1615 inline void link(Record **);
1616 inline void unlink(Record **);
1617 inline void set(const Instruction *ldst);
1623 Record *loads[DATA_FILE_COUNT];
1624 Record *stores[DATA_FILE_COUNT];
1626 MemoryPool recordPool;
1629 virtual bool visit(BasicBlock *);
1630 bool runOpt(BasicBlock *);
1632 Record **getList(const Instruction *);
1634 Record *findRecord(const Instruction *, bool load, bool& isAdjacent) const;
1636 // merge @insn into load/store instruction from @rec
1637 bool combineLd(Record *rec, Instruction *ld);
1638 bool combineSt(Record *rec, Instruction *st);
1640 bool replaceLdFromLd(Instruction *ld, Record *ldRec);
1641 bool replaceLdFromSt(Instruction *ld, Record *stRec);
1642 bool replaceStFromSt(Instruction *restrict st, Record *stRec);
1644 void addRecord(Instruction *ldst);
1645 void purgeRecords(Instruction *const st, DataFile);
1646 void lockStores(Instruction *const ld);
1653 MemoryOpt::MemoryOpt() : recordPool(sizeof(MemoryOpt::Record), 6)
1655 for (int i = 0; i < DATA_FILE_COUNT; ++i) {
1665 for (unsigned int i = 0; i < DATA_FILE_COUNT; ++i) {
1667 for (it = loads[i]; it; it = next) {
1669 recordPool.release(it);
1672 for (it = stores[i]; it; it = next) {
1674 recordPool.release(it);
1681 MemoryOpt::combineLd(Record *rec, Instruction *ld)
1683 int32_t offRc = rec->offset;
1684 int32_t offLd = ld->getSrc(0)->reg.data.offset;
1685 int sizeRc = rec->size;
1686 int sizeLd = typeSizeof(ld->dType);
1687 int size = sizeRc + sizeLd;
1690 if (!prog->getTarget()->
1691 isAccessSupported(ld->getSrc(0)->reg.file, typeOfSize(size)))
1693 // no unaligned loads
1694 if (((size == 0x8) && (MIN2(offLd, offRc) & 0x7)) ||
1695 ((size == 0xc) && (MIN2(offLd, offRc) & 0xf)))
1698 assert(sizeRc + sizeLd <= 16 && offRc != offLd);
1700 for (j = 0; sizeRc; sizeRc -= rec->insn->getDef(j)->reg.size, ++j);
1702 if (offLd < offRc) {
1704 for (sz = 0, d = 0; sz < sizeLd; sz += ld->getDef(d)->reg.size, ++d);
1705 // d: nr of definitions in ld
1706 // j: nr of definitions in rec->insn, move:
1707 for (d = d + j - 1; j > 0; --j, --d)
1708 rec->insn->setDef(d, rec->insn->getDef(j - 1));
1710 if (rec->insn->getSrc(0)->refCount() > 1)
1711 rec->insn->setSrc(0, cloneShallow(func, rec->insn->getSrc(0)));
1712 rec->offset = rec->insn->getSrc(0)->reg.data.offset = offLd;
1718 // move definitions of @ld to @rec->insn
1719 for (j = 0; sizeLd; ++j, ++d) {
1720 sizeLd -= ld->getDef(j)->reg.size;
1721 rec->insn->setDef(d, ld->getDef(j));
1725 rec->insn->getSrc(0)->reg.size = size;
1726 rec->insn->setType(typeOfSize(size));
1728 delete_Instruction(prog, ld);
1734 MemoryOpt::combineSt(Record *rec, Instruction *st)
1736 int32_t offRc = rec->offset;
1737 int32_t offSt = st->getSrc(0)->reg.data.offset;
1738 int sizeRc = rec->size;
1739 int sizeSt = typeSizeof(st->dType);
1741 int size = sizeRc + sizeSt;
1743 Value *src[4]; // no modifiers in ValueRef allowed for st
1746 if (!prog->getTarget()->
1747 isAccessSupported(st->getSrc(0)->reg.file, typeOfSize(size)))
1749 if (size == 8 && MIN2(offRc, offSt) & 0x7)
1752 st->takeExtraSources(0, extra); // save predicate and indirect address
1754 if (offRc < offSt) {
1755 // save values from @st
1756 for (s = 0; sizeSt; ++s) {
1757 sizeSt -= st->getSrc(s + 1)->reg.size;
1758 src[s] = st->getSrc(s + 1);
1760 // set record's values as low sources of @st
1761 for (j = 1; sizeRc; ++j) {
1762 sizeRc -= rec->insn->getSrc(j)->reg.size;
1763 st->setSrc(j, rec->insn->getSrc(j));
1765 // set saved values as high sources of @st
1766 for (k = j, j = 0; j < s; ++j)
1767 st->setSrc(k++, src[j]);
1769 updateLdStOffset(st, offRc, func);
1771 for (j = 1; sizeSt; ++j)
1772 sizeSt -= st->getSrc(j)->reg.size;
1773 for (s = 1; sizeRc; ++j, ++s) {
1774 sizeRc -= rec->insn->getSrc(s)->reg.size;
1775 st->setSrc(j, rec->insn->getSrc(s));
1777 rec->offset = offSt;
1779 st->putExtraSources(0, extra); // restore pointer and predicate
1781 delete_Instruction(prog, rec->insn);
1784 rec->insn->getSrc(0)->reg.size = size;
1785 rec->insn->setType(typeOfSize(size));
1790 MemoryOpt::Record::set(const Instruction *ldst)
1792 const Symbol *mem = ldst->getSrc(0)->asSym();
1793 fileIndex = mem->reg.fileIndex;
1794 rel[0] = ldst->getIndirect(0, 0);
1795 rel[1] = ldst->getIndirect(0, 1);
1796 offset = mem->reg.data.offset;
1797 base = mem->getBase();
1798 size = typeSizeof(ldst->sType);
1802 MemoryOpt::Record::link(Record **list)
1812 MemoryOpt::Record::unlink(Record **list)
1822 MemoryOpt::Record **
1823 MemoryOpt::getList(const Instruction *insn)
1825 if (insn->op == OP_LOAD || insn->op == OP_VFETCH)
1826 return &loads[insn->src(0).getFile()];
1827 return &stores[insn->src(0).getFile()];
1831 MemoryOpt::addRecord(Instruction *i)
1833 Record **list = getList(i);
1834 Record *it = reinterpret_cast<Record *>(recordPool.allocate());
1843 MemoryOpt::findRecord(const Instruction *insn, bool load, bool& isAdj) const
1845 const Symbol *sym = insn->getSrc(0)->asSym();
1846 const int size = typeSizeof(insn->sType);
1848 Record *it = load ? loads[sym->reg.file] : stores[sym->reg.file];
1850 for (; it; it = it->next) {
1851 if (it->locked && insn->op != OP_LOAD)
1853 if ((it->offset >> 4) != (sym->reg.data.offset >> 4) ||
1854 it->rel[0] != insn->getIndirect(0, 0) ||
1855 it->fileIndex != sym->reg.fileIndex ||
1856 it->rel[1] != insn->getIndirect(0, 1))
1859 if (it->offset < sym->reg.data.offset) {
1860 if (it->offset + it->size >= sym->reg.data.offset) {
1861 isAdj = (it->offset + it->size == sym->reg.data.offset);
1864 if (!(it->offset & 0x7))
1868 isAdj = it->offset != sym->reg.data.offset;
1869 if (size <= it->size && !isAdj)
1872 if (!(sym->reg.data.offset & 0x7))
1873 if (it->offset - size <= sym->reg.data.offset)
1881 MemoryOpt::replaceLdFromSt(Instruction *ld, Record *rec)
1883 Instruction *st = rec->insn;
1884 int32_t offSt = rec->offset;
1885 int32_t offLd = ld->getSrc(0)->reg.data.offset;
1888 for (s = 1; offSt != offLd && st->srcExists(s); ++s)
1889 offSt += st->getSrc(s)->reg.size;
1893 for (d = 0; ld->defExists(d) && st->srcExists(s); ++d, ++s) {
1894 if (ld->getDef(d)->reg.size != st->getSrc(s)->reg.size)
1896 if (st->getSrc(s)->reg.file != FILE_GPR)
1898 ld->def(d).replace(st->src(s), false);
1905 MemoryOpt::replaceLdFromLd(Instruction *ldE, Record *rec)
1907 Instruction *ldR = rec->insn;
1908 int32_t offR = rec->offset;
1909 int32_t offE = ldE->getSrc(0)->reg.data.offset;
1912 assert(offR <= offE);
1913 for (dR = 0; offR < offE && ldR->defExists(dR); ++dR)
1914 offR += ldR->getDef(dR)->reg.size;
1918 for (dE = 0; ldE->defExists(dE) && ldR->defExists(dR); ++dE, ++dR) {
1919 if (ldE->getDef(dE)->reg.size != ldR->getDef(dR)->reg.size)
1921 ldE->def(dE).replace(ldR->getDef(dR), false);
1924 delete_Instruction(prog, ldE);
1929 MemoryOpt::replaceStFromSt(Instruction *restrict st, Record *rec)
1931 const Instruction *const ri = rec->insn;
1934 int32_t offS = st->getSrc(0)->reg.data.offset;
1935 int32_t offR = rec->offset;
1936 int32_t endS = offS + typeSizeof(st->dType);
1937 int32_t endR = offR + typeSizeof(ri->dType);
1939 rec->size = MAX2(endS, endR) - MIN2(offS, offR);
1941 st->takeExtraSources(0, extra);
1947 // get non-replaced sources of ri
1948 for (s = 1; offR < offS; offR += ri->getSrc(s)->reg.size, ++s)
1949 vals[k++] = ri->getSrc(s);
1951 // get replaced sources of st
1952 for (s = 1; st->srcExists(s); offS += st->getSrc(s)->reg.size, ++s)
1953 vals[k++] = st->getSrc(s);
1954 // skip replaced sources of ri
1955 for (s = n; offR < endS; offR += ri->getSrc(s)->reg.size, ++s);
1956 // get non-replaced sources after values covered by st
1957 for (; offR < endR; offR += ri->getSrc(s)->reg.size, ++s)
1958 vals[k++] = ri->getSrc(s);
1959 assert((unsigned int)k <= Elements(vals));
1960 for (s = 0; s < k; ++s)
1961 st->setSrc(s + 1, vals[s]);
1962 st->setSrc(0, ri->getSrc(0));
1966 for (j = 1; offR < endS; offR += ri->getSrc(j++)->reg.size);
1967 for (s = 1; offS < endS; offS += st->getSrc(s++)->reg.size);
1968 for (; offR < endR; offR += ri->getSrc(j++)->reg.size)
1969 st->setSrc(s++, ri->getSrc(j));
1971 st->putExtraSources(0, extra);
1973 delete_Instruction(prog, rec->insn);
1976 rec->offset = st->getSrc(0)->reg.data.offset;
1978 st->setType(typeOfSize(rec->size));
1984 MemoryOpt::Record::overlaps(const Instruction *ldst) const
1989 if (this->fileIndex != that.fileIndex)
1992 if (this->rel[0] || that.rel[0])
1993 return this->base == that.base;
1995 (this->offset < that.offset + that.size) &&
1996 (this->offset + this->size > that.offset);
1999 // We must not eliminate stores that affect the result of @ld if
2000 // we find later stores to the same location, and we may no longer
2001 // merge them with later stores.
2002 // The stored value can, however, still be used to determine the value
2003 // returned by future loads.
2005 MemoryOpt::lockStores(Instruction *const ld)
2007 for (Record *r = stores[ld->src(0).getFile()]; r; r = r->next)
2008 if (!r->locked && r->overlaps(ld))
2012 // Prior loads from the location of @st are no longer valid.
2013 // Stores to the location of @st may no longer be used to derive
2014 // the value at it nor be coalesced into later stores.
2016 MemoryOpt::purgeRecords(Instruction *const st, DataFile f)
2019 f = st->src(0).getFile();
2021 for (Record *r = loads[f]; r; r = r->next)
2022 if (!st || r->overlaps(st))
2023 r->unlink(&loads[f]);
2025 for (Record *r = stores[f]; r; r = r->next)
2026 if (!st || r->overlaps(st))
2027 r->unlink(&stores[f]);
2031 MemoryOpt::visit(BasicBlock *bb)
2033 bool ret = runOpt(bb);
2034 // Run again, one pass won't combine 4 32 bit ld/st to a single 128 bit ld/st
2035 // where 96 bit memory operations are forbidden.
2042 MemoryOpt::runOpt(BasicBlock *bb)
2044 Instruction *ldst, *next;
2046 bool isAdjacent = true;
2048 for (ldst = bb->getEntry(); ldst; ldst = next) {
2053 if (ldst->op == OP_LOAD || ldst->op == OP_VFETCH) {
2054 if (ldst->isDead()) {
2055 // might have been produced by earlier optimization
2056 delete_Instruction(prog, ldst);
2060 if (ldst->op == OP_STORE || ldst->op == OP_EXPORT) {
2063 // TODO: maybe have all fixed ops act as barrier ?
2064 if (ldst->op == OP_CALL ||
2065 ldst->op == OP_BAR ||
2066 ldst->op == OP_MEMBAR) {
2067 purgeRecords(NULL, FILE_MEMORY_LOCAL);
2068 purgeRecords(NULL, FILE_MEMORY_GLOBAL);
2069 purgeRecords(NULL, FILE_MEMORY_SHARED);
2070 purgeRecords(NULL, FILE_SHADER_OUTPUT);
2072 if (ldst->op == OP_ATOM || ldst->op == OP_CCTL) {
2073 if (ldst->src(0).getFile() == FILE_MEMORY_GLOBAL) {
2074 purgeRecords(NULL, FILE_MEMORY_LOCAL);
2075 purgeRecords(NULL, FILE_MEMORY_GLOBAL);
2076 purgeRecords(NULL, FILE_MEMORY_SHARED);
2078 purgeRecords(NULL, ldst->src(0).getFile());
2081 if (ldst->op == OP_EMIT || ldst->op == OP_RESTART) {
2082 purgeRecords(NULL, FILE_SHADER_OUTPUT);
2086 if (ldst->getPredicate()) // TODO: handle predicated ld/st
2090 DataFile file = ldst->src(0).getFile();
2092 // if ld l[]/g[] look for previous store to eliminate the reload
2093 if (file == FILE_MEMORY_GLOBAL || file == FILE_MEMORY_LOCAL) {
2094 // TODO: shared memory ?
2095 rec = findRecord(ldst, false, isAdjacent);
2096 if (rec && !isAdjacent)
2097 keep = !replaceLdFromSt(ldst, rec);
2100 // or look for ld from the same location and replace this one
2101 rec = keep ? findRecord(ldst, true, isAdjacent) : NULL;
2104 keep = !replaceLdFromLd(ldst, rec);
2106 // or combine a previous load with this one
2107 keep = !combineLd(rec, ldst);
2112 rec = findRecord(ldst, false, isAdjacent);
2115 keep = !replaceStFromSt(ldst, rec);
2117 keep = !combineSt(rec, ldst);
2120 purgeRecords(ldst, DATA_FILE_COUNT);
2130 // =============================================================================
2132 // Turn control flow into predicated instructions (after register allocation !).
2134 // Could move this to before register allocation on NVC0 and also handle nested
2136 class FlatteningPass : public Pass
2139 virtual bool visit(BasicBlock *);
2141 bool tryPredicateConditional(BasicBlock *);
2142 void predicateInstructions(BasicBlock *, Value *pred, CondCode cc);
2143 void tryPropagateBranch(BasicBlock *);
2144 inline bool isConstantCondition(Value *pred);
2145 inline bool mayPredicate(const Instruction *, const Value *pred) const;
2146 inline void removeFlow(Instruction *);
2150 FlatteningPass::isConstantCondition(Value *pred)
2152 Instruction *insn = pred->getUniqueInsn();
2154 if (insn->op != OP_SET || insn->srcExists(2))
2157 for (int s = 0; s < 2 && insn->srcExists(s); ++s) {
2158 Instruction *ld = insn->getSrc(s)->getUniqueInsn();
2161 if (ld->op != OP_MOV && ld->op != OP_LOAD)
2163 if (ld->src(0).isIndirect(0))
2165 file = ld->src(0).getFile();
2167 file = insn->src(s).getFile();
2168 // catch $r63 on NVC0
2169 if (file == FILE_GPR && insn->getSrc(s)->reg.data.id > prog->maxGPR)
2170 file = FILE_IMMEDIATE;
2172 if (file != FILE_IMMEDIATE && file != FILE_MEMORY_CONST)
2179 FlatteningPass::removeFlow(Instruction *insn)
2181 FlowInstruction *term = insn ? insn->asFlow() : NULL;
2184 Graph::Edge::Type ty = term->bb->cfg.outgoing().getType();
2186 if (term->op == OP_BRA) {
2187 // TODO: this might get more difficult when we get arbitrary BRAs
2188 if (ty == Graph::Edge::CROSS || ty == Graph::Edge::BACK)
2191 if (term->op != OP_JOIN)
2194 Value *pred = term->getPredicate();
2196 delete_Instruction(prog, term);
2198 if (pred && pred->refCount() == 0) {
2199 Instruction *pSet = pred->getUniqueInsn();
2200 pred->join->reg.data.id = -1; // deallocate
2202 delete_Instruction(prog, pSet);
2207 FlatteningPass::predicateInstructions(BasicBlock *bb, Value *pred, CondCode cc)
2209 for (Instruction *i = bb->getEntry(); i; i = i->next) {
2212 assert(!i->getPredicate());
2213 i->setPredicate(cc, pred);
2215 removeFlow(bb->getExit());
2219 FlatteningPass::mayPredicate(const Instruction *insn, const Value *pred) const
2221 if (insn->isPseudo())
2223 // TODO: calls where we don't know which registers are modified
2225 if (!prog->getTarget()->mayPredicate(insn, pred))
2227 for (int d = 0; insn->defExists(d); ++d)
2228 if (insn->getDef(d)->equals(pred))
2233 // If we jump to BRA/RET/EXIT, replace the jump with it.
2234 // NOTE: We do not update the CFG anymore here !
2236 // TODO: Handle cases where we skip over a branch (maybe do that elsewhere ?):
2238 // @p0 bra BB:2 -> @!p0 bra BB:3 iff (!) BB:2 immediately adjoins BB:1
2246 FlatteningPass::tryPropagateBranch(BasicBlock *bb)
2248 for (Instruction *i = bb->getExit(); i && i->op == OP_BRA; i = i->prev) {
2249 BasicBlock *bf = i->asFlow()->target.bb;
2251 if (bf->getInsnCount() != 1)
2254 FlowInstruction *bra = i->asFlow();
2255 FlowInstruction *rep = bf->getExit()->asFlow();
2257 if (!rep || rep->getPredicate())
2259 if (rep->op != OP_BRA &&
2260 rep->op != OP_JOIN &&
2264 // TODO: If there are multiple branches to @rep, only the first would
2265 // be replaced, so only remove them after this pass is done ?
2266 // Also, need to check all incident blocks for fall-through exits and
2267 // add the branch there.
2269 bra->target.bb = rep->target.bb;
2270 if (bf->cfg.incidentCount() == 1)
2276 FlatteningPass::visit(BasicBlock *bb)
2278 if (tryPredicateConditional(bb))
2281 // try to attach join to previous instruction
2282 if (prog->getTarget()->hasJoin) {
2283 Instruction *insn = bb->getExit();
2284 if (insn && insn->op == OP_JOIN && !insn->getPredicate()) {
2286 if (insn && !insn->getPredicate() &&
2288 insn->op != OP_TEXBAR &&
2289 !isTextureOp(insn->op) && // probably just nve4
2290 !isSurfaceOp(insn->op) && // not confirmed
2291 insn->op != OP_LINTERP && // probably just nve4
2292 insn->op != OP_PINTERP && // probably just nve4
2293 ((insn->op != OP_LOAD && insn->op != OP_STORE) ||
2294 (typeSizeof(insn->dType) <= 4 && !insn->src(0).isIndirect(0))) &&
2297 bb->remove(bb->getExit());
2303 tryPropagateBranch(bb);
2309 FlatteningPass::tryPredicateConditional(BasicBlock *bb)
2311 BasicBlock *bL = NULL, *bR = NULL;
2312 unsigned int nL = 0, nR = 0, limit = 12;
2316 mask = bb->initiatesSimpleConditional();
2320 assert(bb->getExit());
2321 Value *pred = bb->getExit()->getPredicate();
2324 if (isConstantCondition(pred))
2327 Graph::EdgeIterator ei = bb->cfg.outgoing();
2330 bL = BasicBlock::get(ei.getNode());
2331 for (insn = bL->getEntry(); insn; insn = insn->next, ++nL)
2332 if (!mayPredicate(insn, pred))
2335 return false; // too long, do a real branch
2340 bR = BasicBlock::get(ei.getNode());
2341 for (insn = bR->getEntry(); insn; insn = insn->next, ++nR)
2342 if (!mayPredicate(insn, pred))
2345 return false; // too long, do a real branch
2349 predicateInstructions(bL, pred, bb->getExit()->cc);
2351 predicateInstructions(bR, pred, inverseCondCode(bb->getExit()->cc));
2354 bb->remove(bb->joinAt);
2357 removeFlow(bb->getExit()); // delete the branch/join at the fork point
2359 // remove potential join operations at the end of the conditional
2360 if (prog->getTarget()->joinAnterior) {
2361 bb = BasicBlock::get((bL ? bL : bR)->cfg.outgoing().getNode());
2362 if (bb->getEntry() && bb->getEntry()->op == OP_JOIN)
2363 removeFlow(bb->getEntry());
2369 // =============================================================================
2371 // Fold Immediate into MAD; must be done after register allocation due to
2372 // constraint SDST == SSRC2
2374 // Does NVC0+ have other situations where this pass makes sense?
2375 class NV50PostRaConstantFolding : public Pass
2378 virtual bool visit(BasicBlock *);
2382 NV50PostRaConstantFolding::visit(BasicBlock *bb)
2387 for (Instruction *i = bb->getFirst(); i; i = i->next) {
2390 if (i->def(0).getFile() != FILE_GPR ||
2391 i->src(0).getFile() != FILE_GPR ||
2392 i->src(1).getFile() != FILE_GPR ||
2393 i->src(2).getFile() != FILE_GPR ||
2394 i->getDef(0)->reg.data.id != i->getSrc(2)->reg.data.id ||
2395 !isFloatType(i->dType))
2398 def = i->getSrc(1)->getInsn();
2399 if (def->op == OP_MOV && def->src(0).getFile() == FILE_IMMEDIATE) {
2400 vtmp = i->getSrc(1);
2401 i->setSrc(1, def->getSrc(0));
2403 /* There's no post-RA dead code elimination, so do it here
2404 * XXX: if we add more code-removing post-RA passes, we might
2405 * want to create a post-RA dead-code elim pass */
2406 if (vtmp->refCount() == 0)
2407 delete_Instruction(bb->getProgram(), def);
2420 // =============================================================================
2422 // Common subexpression elimination. Stupid O^2 implementation.
2423 class LocalCSE : public Pass
2426 virtual bool visit(BasicBlock *);
2428 inline bool tryReplace(Instruction **, Instruction *);
2430 DLList ops[OP_LAST + 1];
2433 class GlobalCSE : public Pass
2436 virtual bool visit(BasicBlock *);
2440 Instruction::isActionEqual(const Instruction *that) const
2442 if (this->op != that->op ||
2443 this->dType != that->dType ||
2444 this->sType != that->sType)
2446 if (this->cc != that->cc)
2449 if (this->asTex()) {
2450 if (memcmp(&this->asTex()->tex,
2451 &that->asTex()->tex,
2452 sizeof(this->asTex()->tex)))
2455 if (this->asCmp()) {
2456 if (this->asCmp()->setCond != that->asCmp()->setCond)
2459 if (this->asFlow()) {
2462 if (this->ipa != that->ipa ||
2463 this->lanes != that->lanes ||
2464 this->perPatch != that->perPatch)
2466 if (this->postFactor != that->postFactor)
2470 if (this->subOp != that->subOp ||
2471 this->saturate != that->saturate ||
2472 this->rnd != that->rnd ||
2473 this->ftz != that->ftz ||
2474 this->dnz != that->dnz ||
2475 this->cache != that->cache ||
2476 this->mask != that->mask)
2483 Instruction::isResultEqual(const Instruction *that) const
2487 // NOTE: location of discard only affects tex with liveOnly and quadops
2488 if (!this->defExists(0) && this->op != OP_DISCARD)
2491 if (!isActionEqual(that))
2494 if (this->predSrc != that->predSrc)
2497 for (d = 0; this->defExists(d); ++d) {
2498 if (!that->defExists(d) ||
2499 !this->getDef(d)->equals(that->getDef(d), false))
2502 if (that->defExists(d))
2505 for (s = 0; this->srcExists(s); ++s) {
2506 if (!that->srcExists(s))
2508 if (this->src(s).mod != that->src(s).mod)
2510 if (!this->getSrc(s)->equals(that->getSrc(s), true))
2513 if (that->srcExists(s))
2516 if (op == OP_LOAD || op == OP_VFETCH) {
2517 switch (src(0).getFile()) {
2518 case FILE_MEMORY_CONST:
2519 case FILE_SHADER_INPUT:
2529 // pull through common expressions from different in-blocks
2531 GlobalCSE::visit(BasicBlock *bb)
2533 Instruction *phi, *next, *ik;
2536 // TODO: maybe do this with OP_UNION, too
2538 for (phi = bb->getPhi(); phi && phi->op == OP_PHI; phi = next) {
2540 if (phi->getSrc(0)->refCount() > 1)
2542 ik = phi->getSrc(0)->getInsn();
2544 continue; // probably a function input
2545 for (s = 1; phi->srcExists(s); ++s) {
2546 if (phi->getSrc(s)->refCount() > 1)
2548 if (!phi->getSrc(s)->getInsn() ||
2549 !phi->getSrc(s)->getInsn()->isResultEqual(ik))
2552 if (!phi->srcExists(s)) {
2553 Instruction *entry = bb->getEntry();
2555 if (!entry || entry->op != OP_JOIN)
2558 bb->insertAfter(entry, ik);
2559 ik->setDef(0, phi->getDef(0));
2560 delete_Instruction(prog, phi);
2568 LocalCSE::tryReplace(Instruction **ptr, Instruction *i)
2570 Instruction *old = *ptr;
2572 // TODO: maybe relax this later (causes trouble with OP_UNION)
2573 if (i->isPredicated())
2576 if (!old->isResultEqual(i))
2579 for (int d = 0; old->defExists(d); ++d)
2580 old->def(d).replace(i->getDef(d), false);
2581 delete_Instruction(prog, old);
2587 LocalCSE::visit(BasicBlock *bb)
2589 unsigned int replaced;
2592 Instruction *ir, *next;
2596 // will need to know the order of instructions
2598 for (ir = bb->getFirst(); ir; ir = ir->next)
2599 ir->serial = serial++;
2601 for (ir = bb->getEntry(); ir; ir = next) {
2608 ops[ir->op].insert(ir);
2612 for (s = 0; ir->srcExists(s); ++s)
2613 if (ir->getSrc(s)->asLValue())
2614 if (!src || ir->getSrc(s)->refCount() < src->refCount())
2615 src = ir->getSrc(s);
2618 for (Value::UseIterator it = src->uses.begin();
2619 it != src->uses.end(); ++it) {
2620 Instruction *ik = (*it)->getInsn();
2621 if (ik && ik->bb == ir->bb && ik->serial < ir->serial)
2622 if (tryReplace(&ir, ik))
2626 DLLIST_FOR_EACH(&ops[ir->op], iter)
2628 Instruction *ik = reinterpret_cast<Instruction *>(iter.get());
2629 if (tryReplace(&ir, ik))
2635 ops[ir->op].insert(ir);
2639 for (unsigned int i = 0; i <= OP_LAST; ++i)
2647 // =============================================================================
2649 // Remove computations of unused values.
2650 class DeadCodeElim : public Pass
2653 bool buryAll(Program *);
2656 virtual bool visit(BasicBlock *);
2658 void checkSplitLoad(Instruction *ld); // for partially dead loads
2660 unsigned int deadCount;
2664 DeadCodeElim::buryAll(Program *prog)
2668 if (!this->run(prog, false, false))
2670 } while (deadCount);
2676 DeadCodeElim::visit(BasicBlock *bb)
2680 for (Instruction *i = bb->getFirst(); i; i = next) {
2684 delete_Instruction(prog, i);
2686 if (i->defExists(1) && (i->op == OP_VFETCH || i->op == OP_LOAD)) {
2689 if (i->defExists(0) && !i->getDef(0)->refCount()) {
2690 if (i->op == OP_ATOM ||
2691 i->op == OP_SUREDP ||
2700 DeadCodeElim::checkSplitLoad(Instruction *ld1)
2702 Instruction *ld2 = NULL; // can get at most 2 loads
2705 int32_t addr1, addr2;
2706 int32_t size1, size2;
2708 uint32_t mask = 0xffffffff;
2710 for (d = 0; ld1->defExists(d); ++d)
2711 if (!ld1->getDef(d)->refCount() && ld1->getDef(d)->reg.data.id < 0)
2713 if (mask == 0xffffffff)
2716 addr1 = ld1->getSrc(0)->reg.data.offset;
2719 for (d = 0; ld1->defExists(d); ++d) {
2720 if (mask & (1 << d)) {
2721 if (size1 && (addr1 & 0x7))
2723 def1[n1] = ld1->getDef(d);
2724 size1 += def1[n1++]->reg.size;
2727 addr1 += ld1->getDef(d)->reg.size;
2732 for (addr2 = addr1 + size1; ld1->defExists(d); ++d) {
2733 if (mask & (1 << d)) {
2734 def2[n2] = ld1->getDef(d);
2735 size2 += def2[n2++]->reg.size;
2738 addr2 += ld1->getDef(d)->reg.size;
2742 updateLdStOffset(ld1, addr1, func);
2743 ld1->setType(typeOfSize(size1));
2744 for (d = 0; d < 4; ++d)
2745 ld1->setDef(d, (d < n1) ? def1[d] : NULL);
2750 ld2 = cloneShallow(func, ld1);
2751 updateLdStOffset(ld2, addr2, func);
2752 ld2->setType(typeOfSize(size2));
2753 for (d = 0; d < 4; ++d)
2754 ld2->setDef(d, (d < n2) ? def2[d] : NULL);
2756 ld1->bb->insertAfter(ld1, ld2);
2759 // =============================================================================
2761 #define RUN_PASS(l, n, f) \
2762 if (level >= (l)) { \
2763 if (dbgFlags & NV50_IR_DEBUG_VERBOSE) \
2764 INFO("PEEPHOLE: %s\n", #n); \
2766 if (!pass.f(this)) \
2771 Program::optimizeSSA(int level)
2773 RUN_PASS(1, DeadCodeElim, buryAll);
2774 RUN_PASS(1, CopyPropagation, run);
2775 RUN_PASS(1, MergeSplits, run);
2776 RUN_PASS(2, GlobalCSE, run);
2777 RUN_PASS(1, LocalCSE, run);
2778 RUN_PASS(2, AlgebraicOpt, run);
2779 RUN_PASS(2, ModifierFolding, run); // before load propagation -> less checks
2780 RUN_PASS(1, ConstantFolding, foldAll);
2781 RUN_PASS(1, LoadPropagation, run);
2782 RUN_PASS(2, MemoryOpt, run);
2783 RUN_PASS(2, LocalCSE, run);
2784 RUN_PASS(0, DeadCodeElim, buryAll);
2790 Program::optimizePostRA(int level)
2792 RUN_PASS(2, FlatteningPass, run);
2793 if (getTarget()->getChipset() < 0xc0)
2794 RUN_PASS(2, NV50PostRaConstantFolding, run);