Path: blob/21.2-virgl/src/gallium/drivers/nouveau/codegen/nv50_ir_peephole.cpp
4574 views
/*1* Copyright 2011 Christoph Bumiller2*3* Permission is hereby granted, free of charge, to any person obtaining a4* copy of this software and associated documentation files (the "Software"),5* to deal in the Software without restriction, including without limitation6* the rights to use, copy, modify, merge, publish, distribute, sublicense,7* and/or sell copies of the Software, and to permit persons to whom the8* Software is furnished to do so, subject to the following conditions:9*10* The above copyright notice and this permission notice shall be included in11* all copies or substantial portions of the Software.12*13* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR14* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,15* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL16* THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR17* OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE,18* ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR19* OTHER DEALINGS IN THE SOFTWARE.20*/2122#include "codegen/nv50_ir.h"23#include "codegen/nv50_ir_target.h"24#include "codegen/nv50_ir_build_util.h"2526extern "C" {27#include "util/u_math.h"28}2930namespace nv50_ir {3132bool33Instruction::isNop() const34{35if (op == OP_PHI || op == OP_SPLIT || op == OP_MERGE || op == OP_CONSTRAINT)36return true;37if (terminator || join) // XXX: should terminator imply flow ?38return false;39if (op == OP_ATOM)40return false;41if (!fixed && op == OP_NOP)42return true;4344if (defExists(0) && def(0).rep()->reg.data.id < 0) {45for (int d = 1; defExists(d); ++d)46if (def(d).rep()->reg.data.id >= 0)47WARN("part of vector result is unused !\n");48return true;49}5051if (op == OP_MOV || op == OP_UNION) {52if (!getDef(0)->equals(getSrc(0)))53return false;54if (op == OP_UNION)55if (!def(0).rep()->equals(getSrc(1)))56return false;57return true;58}5960return false;61}6263bool Instruction::isDead() const64{65if (op == OP_STORE ||66op == OP_EXPORT ||67op == OP_ATOM ||68op == OP_SUSTB || op == OP_SUSTP || op == OP_SUREDP || op == OP_SUREDB ||69op == OP_WRSV)70return false;7172for (int d = 0; defExists(d); ++d)73if (getDef(d)->refCount() || getDef(d)->reg.data.id >= 0)74return false;7576if (terminator || asFlow())77return false;78if (fixed)79return false;8081return true;82};8384// =============================================================================8586class CopyPropagation : public Pass87{88private:89virtual bool visit(BasicBlock *);90};9192// Propagate all MOVs forward to make subsequent optimization easier, except if93// the sources stem from a phi, in which case we don't want to mess up potential94// swaps $rX <-> $rY, i.e. do not create live range overlaps of phi src and def.95bool96CopyPropagation::visit(BasicBlock *bb)97{98Instruction *mov, *si, *next;99100for (mov = bb->getEntry(); mov; mov = next) {101next = mov->next;102if (mov->op != OP_MOV || mov->fixed || !mov->getSrc(0)->asLValue())103continue;104if (mov->getPredicate())105continue;106if (mov->def(0).getFile() != mov->src(0).getFile())107continue;108si = mov->getSrc(0)->getInsn();109if (mov->getDef(0)->reg.data.id < 0 && si && si->op != OP_PHI) {110// propagate111mov->def(0).replace(mov->getSrc(0), false);112delete_Instruction(prog, mov);113}114}115return true;116}117118// =============================================================================119120class MergeSplits : public Pass121{122private:123virtual bool visit(BasicBlock *);124};125126// For SPLIT / MERGE pairs that operate on the same registers, replace the127// post-merge def with the SPLIT's source.128bool129MergeSplits::visit(BasicBlock *bb)130{131Instruction *i, *next, *si;132133for (i = bb->getEntry(); i; i = next) {134next = i->next;135if (i->op != OP_MERGE || typeSizeof(i->dType) != 8)136continue;137si = i->getSrc(0)->getInsn();138if (si->op != OP_SPLIT || si != i->getSrc(1)->getInsn())139continue;140i->def(0).replace(si->getSrc(0), false);141delete_Instruction(prog, i);142}143144return true;145}146147// =============================================================================148149class LoadPropagation : public Pass150{151private:152virtual bool visit(BasicBlock *);153154void checkSwapSrc01(Instruction *);155156bool isCSpaceLoad(Instruction *);157bool isImmdLoad(Instruction *);158bool isAttribOrSharedLoad(Instruction *);159};160161bool162LoadPropagation::isCSpaceLoad(Instruction *ld)163{164return ld && ld->op == OP_LOAD && ld->src(0).getFile() == FILE_MEMORY_CONST;165}166167bool168LoadPropagation::isImmdLoad(Instruction *ld)169{170if (!ld || (ld->op != OP_MOV) ||171((typeSizeof(ld->dType) != 4) && (typeSizeof(ld->dType) != 8)))172return false;173174// A 0 can be replaced with a register, so it doesn't count as an immediate.175ImmediateValue val;176return ld->src(0).getImmediate(val) && !val.isInteger(0);177}178179bool180LoadPropagation::isAttribOrSharedLoad(Instruction *ld)181{182return ld &&183(ld->op == OP_VFETCH ||184(ld->op == OP_LOAD &&185(ld->src(0).getFile() == FILE_SHADER_INPUT ||186ld->src(0).getFile() == FILE_MEMORY_SHARED)));187}188189void190LoadPropagation::checkSwapSrc01(Instruction *insn)191{192const Target *targ = prog->getTarget();193if (!targ->getOpInfo(insn).commutative) {194if (insn->op != OP_SET && insn->op != OP_SLCT &&195insn->op != OP_SUB && insn->op != OP_XMAD)196return;197// XMAD is only commutative if both the CBCC and MRG flags are not set.198if (insn->op == OP_XMAD &&199(insn->subOp & NV50_IR_SUBOP_XMAD_CMODE_MASK) == NV50_IR_SUBOP_XMAD_CBCC)200return;201if (insn->op == OP_XMAD && (insn->subOp & NV50_IR_SUBOP_XMAD_MRG))202return;203}204if (insn->src(1).getFile() != FILE_GPR)205return;206// This is the special OP_SET used for alphatesting, we can't reverse its207// arguments as that will confuse the fixup code.208if (insn->op == OP_SET && insn->subOp)209return;210211Instruction *i0 = insn->getSrc(0)->getInsn();212Instruction *i1 = insn->getSrc(1)->getInsn();213214// Swap sources to inline the less frequently used source. That way,215// optimistically, it will eventually be able to remove the instruction.216int i0refs = insn->getSrc(0)->refCount();217int i1refs = insn->getSrc(1)->refCount();218219if ((isCSpaceLoad(i0) || isImmdLoad(i0)) && targ->insnCanLoad(insn, 1, i0)) {220if ((!isImmdLoad(i1) && !isCSpaceLoad(i1)) ||221!targ->insnCanLoad(insn, 1, i1) ||222i0refs < i1refs)223insn->swapSources(0, 1);224else225return;226} else227if (isAttribOrSharedLoad(i1)) {228if (!isAttribOrSharedLoad(i0))229insn->swapSources(0, 1);230else231return;232} else {233return;234}235236if (insn->op == OP_SET || insn->op == OP_SET_AND ||237insn->op == OP_SET_OR || insn->op == OP_SET_XOR)238insn->asCmp()->setCond = reverseCondCode(insn->asCmp()->setCond);239else240if (insn->op == OP_SLCT)241insn->asCmp()->setCond = inverseCondCode(insn->asCmp()->setCond);242else243if (insn->op == OP_SUB) {244insn->src(0).mod = insn->src(0).mod ^ Modifier(NV50_IR_MOD_NEG);245insn->src(1).mod = insn->src(1).mod ^ Modifier(NV50_IR_MOD_NEG);246} else247if (insn->op == OP_XMAD) {248// swap h1 flags249uint16_t h1 = (insn->subOp >> 1 & NV50_IR_SUBOP_XMAD_H1(0)) |250(insn->subOp << 1 & NV50_IR_SUBOP_XMAD_H1(1));251insn->subOp = (insn->subOp & ~NV50_IR_SUBOP_XMAD_H1_MASK) | h1;252}253}254255bool256LoadPropagation::visit(BasicBlock *bb)257{258const Target *targ = prog->getTarget();259Instruction *next;260261for (Instruction *i = bb->getEntry(); i; i = next) {262next = i->next;263264if (i->op == OP_CALL) // calls have args as sources, they must be in regs265continue;266267if (i->op == OP_PFETCH) // pfetch expects arg1 to be a reg268continue;269270if (i->srcExists(1))271checkSwapSrc01(i);272273for (int s = 0; i->srcExists(s); ++s) {274Instruction *ld = i->getSrc(s)->getInsn();275276if (!ld || ld->fixed || (ld->op != OP_LOAD && ld->op != OP_MOV))277continue;278if (ld->op == OP_LOAD && ld->subOp == NV50_IR_SUBOP_LOAD_LOCKED)279continue;280if (!targ->insnCanLoad(i, s, ld))281continue;282283// propagate !284i->setSrc(s, ld->getSrc(0));285if (ld->src(0).isIndirect(0))286i->setIndirect(s, 0, ld->getIndirect(0, 0));287288if (ld->getDef(0)->refCount() == 0)289delete_Instruction(prog, ld);290}291}292return true;293}294295// =============================================================================296297class IndirectPropagation : public Pass298{299private:300virtual bool visit(BasicBlock *);301302BuildUtil bld;303};304305bool306IndirectPropagation::visit(BasicBlock *bb)307{308const Target *targ = prog->getTarget();309Instruction *next;310311for (Instruction *i = bb->getEntry(); i; i = next) {312next = i->next;313314bld.setPosition(i, false);315316for (int s = 0; i->srcExists(s); ++s) {317Instruction *insn;318ImmediateValue imm;319if (!i->src(s).isIndirect(0))320continue;321insn = i->getIndirect(s, 0)->getInsn();322if (!insn)323continue;324if (insn->op == OP_ADD && !isFloatType(insn->dType)) {325if (insn->src(0).getFile() != targ->nativeFile(FILE_ADDRESS) ||326!insn->src(1).getImmediate(imm) ||327!targ->insnCanLoadOffset(i, s, imm.reg.data.s32))328continue;329i->setIndirect(s, 0, insn->getSrc(0));330i->setSrc(s, cloneShallow(func, i->getSrc(s)));331i->src(s).get()->reg.data.offset += imm.reg.data.u32;332} else if (insn->op == OP_SUB && !isFloatType(insn->dType)) {333if (insn->src(0).getFile() != targ->nativeFile(FILE_ADDRESS) ||334!insn->src(1).getImmediate(imm) ||335!targ->insnCanLoadOffset(i, s, -imm.reg.data.s32))336continue;337i->setIndirect(s, 0, insn->getSrc(0));338i->setSrc(s, cloneShallow(func, i->getSrc(s)));339i->src(s).get()->reg.data.offset -= imm.reg.data.u32;340} else if (insn->op == OP_MOV) {341if (!insn->src(0).getImmediate(imm) ||342!targ->insnCanLoadOffset(i, s, imm.reg.data.s32))343continue;344i->setIndirect(s, 0, NULL);345i->setSrc(s, cloneShallow(func, i->getSrc(s)));346i->src(s).get()->reg.data.offset += imm.reg.data.u32;347} else if (insn->op == OP_SHLADD) {348if (!insn->src(2).getImmediate(imm) ||349!targ->insnCanLoadOffset(i, s, imm.reg.data.s32))350continue;351i->setIndirect(s, 0, bld.mkOp2v(352OP_SHL, TYPE_U32, bld.getSSA(), insn->getSrc(0), insn->getSrc(1)));353i->setSrc(s, cloneShallow(func, i->getSrc(s)));354i->src(s).get()->reg.data.offset += imm.reg.data.u32;355}356}357}358return true;359}360361// =============================================================================362363// Evaluate constant expressions.364class ConstantFolding : public Pass365{366public:367ConstantFolding() : foldCount(0) {}368bool foldAll(Program *);369370private:371virtual bool visit(BasicBlock *);372373void expr(Instruction *, ImmediateValue&, ImmediateValue&);374void expr(Instruction *, ImmediateValue&, ImmediateValue&, ImmediateValue&);375/* true if i was deleted */376bool opnd(Instruction *i, ImmediateValue&, int s);377void opnd3(Instruction *, ImmediateValue&);378379void unary(Instruction *, const ImmediateValue&);380381void tryCollapseChainedMULs(Instruction *, const int s, ImmediateValue&);382383CmpInstruction *findOriginForTestWithZero(Value *);384385bool createMul(DataType ty, Value *def, Value *a, int64_t b, Value *c);386387unsigned int foldCount;388389BuildUtil bld;390};391392// TODO: remember generated immediates and only revisit these393bool394ConstantFolding::foldAll(Program *prog)395{396unsigned int iterCount = 0;397do {398foldCount = 0;399if (!run(prog))400return false;401} while (foldCount && ++iterCount < 2);402return true;403}404405bool406ConstantFolding::visit(BasicBlock *bb)407{408Instruction *i, *next;409410for (i = bb->getEntry(); i; i = next) {411next = i->next;412if (i->op == OP_MOV || i->op == OP_CALL)413continue;414415ImmediateValue src0, src1, src2;416417if (i->srcExists(2) &&418i->src(0).getImmediate(src0) &&419i->src(1).getImmediate(src1) &&420i->src(2).getImmediate(src2)) {421expr(i, src0, src1, src2);422} else423if (i->srcExists(1) &&424i->src(0).getImmediate(src0) && i->src(1).getImmediate(src1)) {425expr(i, src0, src1);426} else427if (i->srcExists(0) && i->src(0).getImmediate(src0)) {428if (opnd(i, src0, 0))429continue;430} else431if (i->srcExists(1) && i->src(1).getImmediate(src1)) {432if (opnd(i, src1, 1))433continue;434}435if (i->srcExists(2) && i->src(2).getImmediate(src2))436opnd3(i, src2);437}438return true;439}440441CmpInstruction *442ConstantFolding::findOriginForTestWithZero(Value *value)443{444if (!value)445return NULL;446Instruction *insn = value->getInsn();447if (!insn)448return NULL;449450if (insn->asCmp() && insn->op != OP_SLCT)451return insn->asCmp();452453/* Sometimes mov's will sneak in as a result of other folding. This gets454* cleaned up later.455*/456if (insn->op == OP_MOV)457return findOriginForTestWithZero(insn->getSrc(0));458459/* Deal with AND 1.0 here since nv50 can't fold into boolean float */460if (insn->op == OP_AND) {461int s = 0;462ImmediateValue imm;463if (!insn->src(s).getImmediate(imm)) {464s = 1;465if (!insn->src(s).getImmediate(imm))466return NULL;467}468if (imm.reg.data.f32 != 1.0f)469return NULL;470/* TODO: Come up with a way to handle the condition being inverted */471if (insn->src(!s).mod != Modifier(0))472return NULL;473return findOriginForTestWithZero(insn->getSrc(!s));474}475476return NULL;477}478479void480Modifier::applyTo(ImmediateValue& imm) const481{482if (!bits) // avoid failure if imm.reg.type is unhandled (e.g. b128)483return;484switch (imm.reg.type) {485case TYPE_F32:486if (bits & NV50_IR_MOD_ABS)487imm.reg.data.f32 = fabsf(imm.reg.data.f32);488if (bits & NV50_IR_MOD_NEG)489imm.reg.data.f32 = -imm.reg.data.f32;490if (bits & NV50_IR_MOD_SAT) {491if (imm.reg.data.f32 < 0.0f)492imm.reg.data.f32 = 0.0f;493else494if (imm.reg.data.f32 > 1.0f)495imm.reg.data.f32 = 1.0f;496}497assert(!(bits & NV50_IR_MOD_NOT));498break;499500case TYPE_S8: // NOTE: will be extended501case TYPE_S16:502case TYPE_S32:503case TYPE_U8: // NOTE: treated as signed504case TYPE_U16:505case TYPE_U32:506if (bits & NV50_IR_MOD_ABS)507imm.reg.data.s32 = (imm.reg.data.s32 >= 0) ?508imm.reg.data.s32 : -imm.reg.data.s32;509if (bits & NV50_IR_MOD_NEG)510imm.reg.data.s32 = -imm.reg.data.s32;511if (bits & NV50_IR_MOD_NOT)512imm.reg.data.s32 = ~imm.reg.data.s32;513break;514515case TYPE_F64:516if (bits & NV50_IR_MOD_ABS)517imm.reg.data.f64 = fabs(imm.reg.data.f64);518if (bits & NV50_IR_MOD_NEG)519imm.reg.data.f64 = -imm.reg.data.f64;520if (bits & NV50_IR_MOD_SAT) {521if (imm.reg.data.f64 < 0.0)522imm.reg.data.f64 = 0.0;523else524if (imm.reg.data.f64 > 1.0)525imm.reg.data.f64 = 1.0;526}527assert(!(bits & NV50_IR_MOD_NOT));528break;529530default:531assert(!"invalid/unhandled type");532imm.reg.data.u64 = 0;533break;534}535}536537operation538Modifier::getOp() const539{540switch (bits) {541case NV50_IR_MOD_ABS: return OP_ABS;542case NV50_IR_MOD_NEG: return OP_NEG;543case NV50_IR_MOD_SAT: return OP_SAT;544case NV50_IR_MOD_NOT: return OP_NOT;545case 0:546return OP_MOV;547default:548return OP_CVT;549}550}551552void553ConstantFolding::expr(Instruction *i,554ImmediateValue &imm0, ImmediateValue &imm1)555{556struct Storage *const a = &imm0.reg, *const b = &imm1.reg;557struct Storage res;558DataType type = i->dType;559560memset(&res.data, 0, sizeof(res.data));561562switch (i->op) {563case OP_SGXT: {564int bits = b->data.u32;565if (bits) {566uint32_t data = a->data.u32 & (0xffffffff >> (32 - bits));567if (bits < 32 && (data & (1 << (bits - 1))))568data = data - (1 << bits);569res.data.u32 = data;570}571break;572}573case OP_BMSK:574res.data.u32 = ((1 << b->data.u32) - 1) << a->data.u32;575break;576case OP_MAD:577case OP_FMA:578case OP_MUL:579if (i->dnz && i->dType == TYPE_F32) {580if (!isfinite(a->data.f32))581a->data.f32 = 0.0f;582if (!isfinite(b->data.f32))583b->data.f32 = 0.0f;584}585switch (i->dType) {586case TYPE_F32:587res.data.f32 = a->data.f32 * b->data.f32 * exp2f(i->postFactor);588break;589case TYPE_F64: res.data.f64 = a->data.f64 * b->data.f64; break;590case TYPE_S32:591if (i->subOp == NV50_IR_SUBOP_MUL_HIGH) {592res.data.s32 = ((int64_t)a->data.s32 * b->data.s32) >> 32;593break;594}595FALLTHROUGH;596case TYPE_U32:597if (i->subOp == NV50_IR_SUBOP_MUL_HIGH) {598res.data.u32 = ((uint64_t)a->data.u32 * b->data.u32) >> 32;599break;600}601res.data.u32 = a->data.u32 * b->data.u32; break;602default:603return;604}605break;606case OP_DIV:607if (b->data.u32 == 0)608break;609switch (i->dType) {610case TYPE_F32: res.data.f32 = a->data.f32 / b->data.f32; break;611case TYPE_F64: res.data.f64 = a->data.f64 / b->data.f64; break;612case TYPE_S32: res.data.s32 = a->data.s32 / b->data.s32; break;613case TYPE_U32: res.data.u32 = a->data.u32 / b->data.u32; break;614default:615return;616}617break;618case OP_ADD:619switch (i->dType) {620case TYPE_F32: res.data.f32 = a->data.f32 + b->data.f32; break;621case TYPE_F64: res.data.f64 = a->data.f64 + b->data.f64; break;622case TYPE_S32:623case TYPE_U32: res.data.u32 = a->data.u32 + b->data.u32; break;624default:625return;626}627break;628case OP_SUB:629switch (i->dType) {630case TYPE_F32: res.data.f32 = a->data.f32 - b->data.f32; break;631case TYPE_F64: res.data.f64 = a->data.f64 - b->data.f64; break;632case TYPE_S32:633case TYPE_U32: res.data.u32 = a->data.u32 - b->data.u32; break;634default:635return;636}637break;638case OP_POW:639switch (i->dType) {640case TYPE_F32: res.data.f32 = pow(a->data.f32, b->data.f32); break;641case TYPE_F64: res.data.f64 = pow(a->data.f64, b->data.f64); break;642default:643return;644}645break;646case OP_MAX:647switch (i->dType) {648case TYPE_F32: res.data.f32 = MAX2(a->data.f32, b->data.f32); break;649case TYPE_F64: res.data.f64 = MAX2(a->data.f64, b->data.f64); break;650case TYPE_S32: res.data.s32 = MAX2(a->data.s32, b->data.s32); break;651case TYPE_U32: res.data.u32 = MAX2(a->data.u32, b->data.u32); break;652default:653return;654}655break;656case OP_MIN:657switch (i->dType) {658case TYPE_F32: res.data.f32 = MIN2(a->data.f32, b->data.f32); break;659case TYPE_F64: res.data.f64 = MIN2(a->data.f64, b->data.f64); break;660case TYPE_S32: res.data.s32 = MIN2(a->data.s32, b->data.s32); break;661case TYPE_U32: res.data.u32 = MIN2(a->data.u32, b->data.u32); break;662default:663return;664}665break;666case OP_AND:667res.data.u64 = a->data.u64 & b->data.u64;668break;669case OP_OR:670res.data.u64 = a->data.u64 | b->data.u64;671break;672case OP_XOR:673res.data.u64 = a->data.u64 ^ b->data.u64;674break;675case OP_SHL:676res.data.u32 = a->data.u32 << b->data.u32;677break;678case OP_SHR:679switch (i->dType) {680case TYPE_S32: res.data.s32 = a->data.s32 >> b->data.u32; break;681case TYPE_U32: res.data.u32 = a->data.u32 >> b->data.u32; break;682default:683return;684}685break;686case OP_SLCT:687if (a->data.u32 != b->data.u32)688return;689res.data.u32 = a->data.u32;690break;691case OP_EXTBF: {692int offset = b->data.u32 & 0xff;693int width = (b->data.u32 >> 8) & 0xff;694int rshift = offset;695int lshift = 0;696if (width == 0) {697res.data.u32 = 0;698break;699}700if (width + offset < 32) {701rshift = 32 - width;702lshift = 32 - width - offset;703}704if (i->subOp == NV50_IR_SUBOP_EXTBF_REV)705res.data.u32 = util_bitreverse(a->data.u32);706else707res.data.u32 = a->data.u32;708switch (i->dType) {709case TYPE_S32: res.data.s32 = (res.data.s32 << lshift) >> rshift; break;710case TYPE_U32: res.data.u32 = (res.data.u32 << lshift) >> rshift; break;711default:712return;713}714break;715}716case OP_POPCNT:717res.data.u32 = util_bitcount(a->data.u32 & b->data.u32);718break;719case OP_PFETCH:720// The two arguments to pfetch are logically added together. Normally721// the second argument will not be constant, but that can happen.722res.data.u32 = a->data.u32 + b->data.u32;723type = TYPE_U32;724break;725case OP_MERGE:726switch (i->dType) {727case TYPE_U64:728case TYPE_S64:729case TYPE_F64:730res.data.u64 = (((uint64_t)b->data.u32) << 32) | a->data.u32;731break;732default:733return;734}735break;736default:737return;738}739++foldCount;740741i->src(0).mod = Modifier(0);742i->src(1).mod = Modifier(0);743i->postFactor = 0;744745i->setSrc(0, new_ImmediateValue(i->bb->getProgram(), res.data.u32));746i->setSrc(1, NULL);747748i->getSrc(0)->reg.data = res.data;749i->getSrc(0)->reg.type = type;750i->getSrc(0)->reg.size = typeSizeof(type);751752switch (i->op) {753case OP_MAD:754case OP_FMA: {755ImmediateValue src0, src1 = *i->getSrc(0)->asImm();756757// Move the immediate into position 1, where we know it might be758// emittable. However it might not be anyways, as there may be other759// restrictions, so move it into a separate LValue.760bld.setPosition(i, false);761i->op = OP_ADD;762i->dnz = 0;763i->setSrc(1, bld.mkMov(bld.getSSA(type), i->getSrc(0), type)->getDef(0));764i->setSrc(0, i->getSrc(2));765i->src(0).mod = i->src(2).mod;766i->setSrc(2, NULL);767768if (i->src(0).getImmediate(src0))769expr(i, src0, src1);770else771opnd(i, src1, 1);772break;773}774case OP_PFETCH:775// Leave PFETCH alone... we just folded its 2 args into 1.776break;777default:778i->op = i->saturate ? OP_SAT : OP_MOV;779if (i->saturate)780unary(i, *i->getSrc(0)->asImm());781break;782}783i->subOp = 0;784}785786void787ConstantFolding::expr(Instruction *i,788ImmediateValue &imm0,789ImmediateValue &imm1,790ImmediateValue &imm2)791{792struct Storage *const a = &imm0.reg, *const b = &imm1.reg, *const c = &imm2.reg;793struct Storage res;794795memset(&res.data, 0, sizeof(res.data));796797switch (i->op) {798case OP_LOP3_LUT:799for (int n = 0; n < 32; n++) {800uint8_t lut = ((a->data.u32 >> n) & 1) << 2 |801((b->data.u32 >> n) & 1) << 1 |802((c->data.u32 >> n) & 1);803res.data.u32 |= !!(i->subOp & (1 << lut)) << n;804}805break;806case OP_PERMT:807if (!i->subOp) {808uint64_t input = (uint64_t)c->data.u32 << 32 | a->data.u32;809uint16_t permt = b->data.u32;810for (int n = 0 ; n < 4; n++, permt >>= 4)811res.data.u32 |= ((input >> ((permt & 0xf) * 8)) & 0xff) << n * 8;812} else813return;814break;815case OP_INSBF: {816int offset = b->data.u32 & 0xff;817int width = (b->data.u32 >> 8) & 0xff;818unsigned bitmask = ((1 << width) - 1) << offset;819res.data.u32 = ((a->data.u32 << offset) & bitmask) | (c->data.u32 & ~bitmask);820break;821}822case OP_MAD:823case OP_FMA: {824switch (i->dType) {825case TYPE_F32:826res.data.f32 = a->data.f32 * b->data.f32 * exp2f(i->postFactor) +827c->data.f32;828break;829case TYPE_F64:830res.data.f64 = a->data.f64 * b->data.f64 + c->data.f64;831break;832case TYPE_S32:833if (i->subOp == NV50_IR_SUBOP_MUL_HIGH) {834res.data.s32 = ((int64_t)a->data.s32 * b->data.s32 >> 32) + c->data.s32;835break;836}837FALLTHROUGH;838case TYPE_U32:839if (i->subOp == NV50_IR_SUBOP_MUL_HIGH) {840res.data.u32 = ((uint64_t)a->data.u32 * b->data.u32 >> 32) + c->data.u32;841break;842}843res.data.u32 = a->data.u32 * b->data.u32 + c->data.u32;844break;845default:846return;847}848break;849}850case OP_SHLADD:851res.data.u32 = (a->data.u32 << b->data.u32) + c->data.u32;852break;853default:854return;855}856857++foldCount;858i->src(0).mod = Modifier(0);859i->src(1).mod = Modifier(0);860i->src(2).mod = Modifier(0);861862i->setSrc(0, new_ImmediateValue(i->bb->getProgram(), res.data.u32));863i->setSrc(1, NULL);864i->setSrc(2, NULL);865866i->getSrc(0)->reg.data = res.data;867i->getSrc(0)->reg.type = i->dType;868i->getSrc(0)->reg.size = typeSizeof(i->dType);869870i->op = OP_MOV;871}872873void874ConstantFolding::unary(Instruction *i, const ImmediateValue &imm)875{876Storage res;877878if (i->dType != TYPE_F32)879return;880switch (i->op) {881case OP_NEG: res.data.f32 = -imm.reg.data.f32; break;882case OP_ABS: res.data.f32 = fabsf(imm.reg.data.f32); break;883case OP_SAT: res.data.f32 = SATURATE(imm.reg.data.f32); break;884case OP_RCP: res.data.f32 = 1.0f / imm.reg.data.f32; break;885case OP_RSQ: res.data.f32 = 1.0f / sqrtf(imm.reg.data.f32); break;886case OP_LG2: res.data.f32 = log2f(imm.reg.data.f32); break;887case OP_EX2: res.data.f32 = exp2f(imm.reg.data.f32); break;888case OP_SIN: res.data.f32 = sinf(imm.reg.data.f32); break;889case OP_COS: res.data.f32 = cosf(imm.reg.data.f32); break;890case OP_SQRT: res.data.f32 = sqrtf(imm.reg.data.f32); break;891case OP_PRESIN:892case OP_PREEX2:893// these should be handled in subsequent OP_SIN/COS/EX2894res.data.f32 = imm.reg.data.f32;895break;896default:897return;898}899i->op = OP_MOV;900i->setSrc(0, new_ImmediateValue(i->bb->getProgram(), res.data.f32));901i->src(0).mod = Modifier(0);902}903904void905ConstantFolding::tryCollapseChainedMULs(Instruction *mul2,906const int s, ImmediateValue& imm2)907{908const int t = s ? 0 : 1;909Instruction *insn;910Instruction *mul1 = NULL; // mul1 before mul2911int e = 0;912float f = imm2.reg.data.f32 * exp2f(mul2->postFactor);913ImmediateValue imm1;914915assert(mul2->op == OP_MUL && mul2->dType == TYPE_F32);916917if (mul2->getSrc(t)->refCount() == 1) {918insn = mul2->getSrc(t)->getInsn();919if (!mul2->src(t).mod && insn->op == OP_MUL && insn->dType == TYPE_F32)920mul1 = insn;921if (mul1 && !mul1->saturate) {922int s1;923924if (mul1->src(s1 = 0).getImmediate(imm1) ||925mul1->src(s1 = 1).getImmediate(imm1)) {926bld.setPosition(mul1, false);927// a = mul r, imm1928// d = mul a, imm2 -> d = mul r, (imm1 * imm2)929mul1->setSrc(s1, bld.loadImm(NULL, f * imm1.reg.data.f32));930mul1->src(s1).mod = Modifier(0);931mul2->def(0).replace(mul1->getDef(0), false);932mul1->saturate = mul2->saturate;933} else934if (prog->getTarget()->isPostMultiplySupported(OP_MUL, f, e)) {935// c = mul a, b936// d = mul c, imm -> d = mul_x_imm a, b937mul1->postFactor = e;938mul2->def(0).replace(mul1->getDef(0), false);939if (f < 0)940mul1->src(0).mod *= Modifier(NV50_IR_MOD_NEG);941mul1->saturate = mul2->saturate;942}943return;944}945}946if (mul2->getDef(0)->refCount() == 1 && !mul2->saturate) {947// b = mul a, imm948// d = mul b, c -> d = mul_x_imm a, c949int s2, t2;950insn = (*mul2->getDef(0)->uses.begin())->getInsn();951if (!insn)952return;953mul1 = mul2;954mul2 = NULL;955s2 = insn->getSrc(0) == mul1->getDef(0) ? 0 : 1;956t2 = s2 ? 0 : 1;957if (insn->op == OP_MUL && insn->dType == TYPE_F32)958if (!insn->src(s2).mod && !insn->src(t2).getImmediate(imm1))959mul2 = insn;960if (mul2 && prog->getTarget()->isPostMultiplySupported(OP_MUL, f, e)) {961mul2->postFactor = e;962mul2->setSrc(s2, mul1->src(t));963if (f < 0)964mul2->src(s2).mod *= Modifier(NV50_IR_MOD_NEG);965}966}967}968969void970ConstantFolding::opnd3(Instruction *i, ImmediateValue &imm2)971{972switch (i->op) {973case OP_MAD:974case OP_FMA:975if (imm2.isInteger(0)) {976i->op = OP_MUL;977i->setSrc(2, NULL);978foldCount++;979return;980}981break;982case OP_SHLADD:983if (imm2.isInteger(0)) {984i->op = OP_SHL;985i->setSrc(2, NULL);986foldCount++;987return;988}989break;990default:991return;992}993}994995bool996ConstantFolding::createMul(DataType ty, Value *def, Value *a, int64_t b, Value *c)997{998const Target *target = prog->getTarget();999int64_t absB = llabs(b);10001001//a * (2^shl) -> a << shl1002if (b >= 0 && util_is_power_of_two_or_zero64(b)) {1003int shl = util_logbase2_64(b);10041005Value *res = c ? bld.getSSA(typeSizeof(ty)) : def;1006bld.mkOp2(OP_SHL, ty, res, a, bld.mkImm(shl));1007if (c)1008bld.mkOp2(OP_ADD, ty, def, res, c);10091010return true;1011}10121013//a * (2^shl + 1) -> a << shl + a1014//a * -(2^shl + 1) -> -a << shl + a1015//a * (2^shl - 1) -> a << shl - a1016//a * -(2^shl - 1) -> -a << shl - a1017if (typeSizeof(ty) == 4 &&1018(util_is_power_of_two_or_zero64(absB - 1) ||1019util_is_power_of_two_or_zero64(absB + 1)) &&1020target->isOpSupported(OP_SHLADD, TYPE_U32)) {1021bool subA = util_is_power_of_two_or_zero64(absB + 1);1022int shl = subA ? util_logbase2_64(absB + 1) : util_logbase2_64(absB - 1);10231024Value *res = c ? bld.getSSA() : def;1025Instruction *insn = bld.mkOp3(OP_SHLADD, TYPE_U32, res, a, bld.mkImm(shl), a);1026if (b < 0)1027insn->src(0).mod = Modifier(NV50_IR_MOD_NEG);1028if (subA)1029insn->src(2).mod = Modifier(NV50_IR_MOD_NEG);10301031if (c)1032bld.mkOp2(OP_ADD, TYPE_U32, def, res, c);10331034return true;1035}10361037if (typeSizeof(ty) == 4 && b >= 0 && b <= 0xffff &&1038target->isOpSupported(OP_XMAD, TYPE_U32)) {1039Value *tmp = bld.mkOp3v(OP_XMAD, TYPE_U32, bld.getSSA(),1040a, bld.mkImm((uint32_t)b), c ? c : bld.mkImm(0));1041bld.mkOp3(OP_XMAD, TYPE_U32, def, a, bld.mkImm((uint32_t)b), tmp)->subOp =1042NV50_IR_SUBOP_XMAD_PSL | NV50_IR_SUBOP_XMAD_H1(0);10431044return true;1045}10461047return false;1048}10491050bool1051ConstantFolding::opnd(Instruction *i, ImmediateValue &imm0, int s)1052{1053const int t = !s;1054const operation op = i->op;1055Instruction *newi = i;1056bool deleted = false;10571058switch (i->op) {1059case OP_SPLIT: {1060bld.setPosition(i, false);10611062uint8_t size = i->getDef(0)->reg.size;1063uint8_t bitsize = size * 8;1064uint32_t mask = (1ULL << bitsize) - 1;1065assert(bitsize <= 32);10661067uint64_t val = imm0.reg.data.u64;1068for (int8_t d = 0; i->defExists(d); ++d) {1069Value *def = i->getDef(d);1070assert(def->reg.size == size);10711072newi = bld.mkMov(def, bld.mkImm((uint32_t)(val & mask)), TYPE_U32);1073val >>= bitsize;1074}1075delete_Instruction(prog, i);1076deleted = true;1077break;1078}1079case OP_MUL:1080if (i->dType == TYPE_F32 && !i->precise)1081tryCollapseChainedMULs(i, s, imm0);10821083if (i->subOp == NV50_IR_SUBOP_MUL_HIGH) {1084assert(!isFloatType(i->sType));1085if (imm0.isInteger(1) && i->dType == TYPE_S32) {1086bld.setPosition(i, false);1087// Need to set to the sign value, which is a compare.1088newi = bld.mkCmp(OP_SET, CC_LT, TYPE_S32, i->getDef(0),1089TYPE_S32, i->getSrc(t), bld.mkImm(0));1090delete_Instruction(prog, i);1091deleted = true;1092} else if (imm0.isInteger(0) || imm0.isInteger(1)) {1093// The high bits can't be set in this case (either mul by 0 or1094// unsigned by 1)1095i->op = OP_MOV;1096i->subOp = 0;1097i->setSrc(0, new_ImmediateValue(prog, 0u));1098i->src(0).mod = Modifier(0);1099i->setSrc(1, NULL);1100} else if (!imm0.isNegative() && imm0.isPow2()) {1101// Translate into a shift1102imm0.applyLog2();1103i->op = OP_SHR;1104i->subOp = 0;1105imm0.reg.data.u32 = 32 - imm0.reg.data.u32;1106i->setSrc(0, i->getSrc(t));1107i->src(0).mod = i->src(t).mod;1108i->setSrc(1, new_ImmediateValue(prog, imm0.reg.data.u32));1109i->src(1).mod = 0;1110}1111} else1112if (imm0.isInteger(0)) {1113i->dnz = 0;1114i->op = OP_MOV;1115i->setSrc(0, new_ImmediateValue(prog, 0u));1116i->src(0).mod = Modifier(0);1117i->postFactor = 0;1118i->setSrc(1, NULL);1119} else1120if (!i->postFactor && (imm0.isInteger(1) || imm0.isInteger(-1))) {1121if (imm0.isNegative())1122i->src(t).mod = i->src(t).mod ^ Modifier(NV50_IR_MOD_NEG);1123i->dnz = 0;1124i->op = i->src(t).mod.getOp();1125if (s == 0) {1126i->setSrc(0, i->getSrc(1));1127i->src(0).mod = i->src(1).mod;1128i->src(1).mod = 0;1129}1130if (i->op != OP_CVT)1131i->src(0).mod = 0;1132i->setSrc(1, NULL);1133} else1134if (!i->postFactor && (imm0.isInteger(2) || imm0.isInteger(-2))) {1135if (imm0.isNegative())1136i->src(t).mod = i->src(t).mod ^ Modifier(NV50_IR_MOD_NEG);1137i->op = OP_ADD;1138i->dnz = 0;1139i->setSrc(s, i->getSrc(t));1140i->src(s).mod = i->src(t).mod;1141} else1142if (!isFloatType(i->dType) && !i->src(t).mod) {1143bld.setPosition(i, false);1144int64_t b = typeSizeof(i->dType) == 8 ? imm0.reg.data.s64 : imm0.reg.data.s32;1145if (createMul(i->dType, i->getDef(0), i->getSrc(t), b, NULL)) {1146delete_Instruction(prog, i);1147deleted = true;1148}1149} else1150if (i->postFactor && i->sType == TYPE_F32) {1151/* Can't emit a postfactor with an immediate, have to fold it in */1152i->setSrc(s, new_ImmediateValue(1153prog, imm0.reg.data.f32 * exp2f(i->postFactor)));1154i->postFactor = 0;1155}1156break;1157case OP_FMA:1158case OP_MAD:1159if (imm0.isInteger(0)) {1160i->setSrc(0, i->getSrc(2));1161i->src(0).mod = i->src(2).mod;1162i->setSrc(1, NULL);1163i->setSrc(2, NULL);1164i->dnz = 0;1165i->op = i->src(0).mod.getOp();1166if (i->op != OP_CVT)1167i->src(0).mod = 0;1168} else1169if (i->subOp != NV50_IR_SUBOP_MUL_HIGH &&1170(imm0.isInteger(1) || imm0.isInteger(-1))) {1171if (imm0.isNegative())1172i->src(t).mod = i->src(t).mod ^ Modifier(NV50_IR_MOD_NEG);1173if (s == 0) {1174i->setSrc(0, i->getSrc(1));1175i->src(0).mod = i->src(1).mod;1176}1177i->setSrc(1, i->getSrc(2));1178i->src(1).mod = i->src(2).mod;1179i->setSrc(2, NULL);1180i->dnz = 0;1181i->op = OP_ADD;1182} else1183if (!isFloatType(i->dType) && !i->subOp && !i->src(t).mod && !i->src(2).mod) {1184bld.setPosition(i, false);1185int64_t b = typeSizeof(i->dType) == 8 ? imm0.reg.data.s64 : imm0.reg.data.s32;1186if (createMul(i->dType, i->getDef(0), i->getSrc(t), b, i->getSrc(2))) {1187delete_Instruction(prog, i);1188deleted = true;1189}1190}1191break;1192case OP_SUB:1193if (imm0.isInteger(0) && s == 0 && typeSizeof(i->dType) == 8 &&1194!isFloatType(i->dType))1195break;1196FALLTHROUGH;1197case OP_ADD:1198if (i->usesFlags())1199break;1200if (imm0.isInteger(0)) {1201if (s == 0) {1202i->setSrc(0, i->getSrc(1));1203i->src(0).mod = i->src(1).mod;1204if (i->op == OP_SUB)1205i->src(0).mod = i->src(0).mod ^ Modifier(NV50_IR_MOD_NEG);1206}1207i->setSrc(1, NULL);1208i->op = i->src(0).mod.getOp();1209if (i->op != OP_CVT)1210i->src(0).mod = Modifier(0);1211}1212break;12131214case OP_DIV:1215if (s != 1 || (i->dType != TYPE_S32 && i->dType != TYPE_U32))1216break;1217bld.setPosition(i, false);1218if (imm0.reg.data.u32 == 0) {1219break;1220} else1221if (imm0.reg.data.u32 == 1) {1222i->op = OP_MOV;1223i->setSrc(1, NULL);1224} else1225if (i->dType == TYPE_U32 && imm0.isPow2()) {1226i->op = OP_SHR;1227i->setSrc(1, bld.mkImm(util_logbase2(imm0.reg.data.u32)));1228} else1229if (i->dType == TYPE_U32) {1230Instruction *mul;1231Value *tA, *tB;1232const uint32_t d = imm0.reg.data.u32;1233uint32_t m;1234int r, s;1235uint32_t l = util_logbase2(d);1236if (((uint32_t)1 << l) < d)1237++l;1238m = (((uint64_t)1 << 32) * (((uint64_t)1 << l) - d)) / d + 1;1239r = l ? 1 : 0;1240s = l ? (l - 1) : 0;12411242tA = bld.getSSA();1243tB = bld.getSSA();1244mul = bld.mkOp2(OP_MUL, TYPE_U32, tA, i->getSrc(0),1245bld.loadImm(NULL, m));1246mul->subOp = NV50_IR_SUBOP_MUL_HIGH;1247bld.mkOp2(OP_SUB, TYPE_U32, tB, i->getSrc(0), tA);1248tA = bld.getSSA();1249if (r)1250bld.mkOp2(OP_SHR, TYPE_U32, tA, tB, bld.mkImm(r));1251else1252tA = tB;1253tB = s ? bld.getSSA() : i->getDef(0);1254newi = bld.mkOp2(OP_ADD, TYPE_U32, tB, mul->getDef(0), tA);1255if (s)1256bld.mkOp2(OP_SHR, TYPE_U32, i->getDef(0), tB, bld.mkImm(s));12571258delete_Instruction(prog, i);1259deleted = true;1260} else1261if (imm0.reg.data.s32 == -1) {1262i->op = OP_NEG;1263i->setSrc(1, NULL);1264} else {1265LValue *tA, *tB;1266LValue *tD;1267const int32_t d = imm0.reg.data.s32;1268int32_t m;1269int32_t l = util_logbase2(static_cast<unsigned>(abs(d)));1270if ((1 << l) < abs(d))1271++l;1272if (!l)1273l = 1;1274m = ((uint64_t)1 << (32 + l - 1)) / abs(d) + 1 - ((uint64_t)1 << 32);12751276tA = bld.getSSA();1277tB = bld.getSSA();1278bld.mkOp3(OP_MAD, TYPE_S32, tA, i->getSrc(0), bld.loadImm(NULL, m),1279i->getSrc(0))->subOp = NV50_IR_SUBOP_MUL_HIGH;1280if (l > 1)1281bld.mkOp2(OP_SHR, TYPE_S32, tB, tA, bld.mkImm(l - 1));1282else1283tB = tA;1284tA = bld.getSSA();1285bld.mkCmp(OP_SET, CC_LT, TYPE_S32, tA, TYPE_S32, i->getSrc(0), bld.mkImm(0));1286tD = (d < 0) ? bld.getSSA() : i->getDef(0)->asLValue();1287newi = bld.mkOp2(OP_SUB, TYPE_U32, tD, tB, tA);1288if (d < 0)1289bld.mkOp1(OP_NEG, TYPE_S32, i->getDef(0), tB);12901291delete_Instruction(prog, i);1292deleted = true;1293}1294break;12951296case OP_MOD:1297if (s == 1 && imm0.isPow2()) {1298bld.setPosition(i, false);1299if (i->sType == TYPE_U32) {1300i->op = OP_AND;1301i->setSrc(1, bld.loadImm(NULL, imm0.reg.data.u32 - 1));1302} else if (i->sType == TYPE_S32) {1303// Do it on the absolute value of the input, and then restore the1304// sign. The only odd case is MIN_INT, but that should work out1305// as well, since MIN_INT mod any power of 2 is 0.1306//1307// Technically we don't have to do any of this since MOD is1308// undefined with negative arguments in GLSL, but this seems like1309// the nice thing to do.1310Value *abs = bld.mkOp1v(OP_ABS, TYPE_S32, bld.getSSA(), i->getSrc(0));1311Value *neg, *v1, *v2;1312bld.mkCmp(OP_SET, CC_LT, TYPE_S32,1313(neg = bld.getSSA(1, prog->getTarget()->nativeFile(FILE_PREDICATE))),1314TYPE_S32, i->getSrc(0), bld.loadImm(NULL, 0));1315Value *mod = bld.mkOp2v(OP_AND, TYPE_U32, bld.getSSA(), abs,1316bld.loadImm(NULL, imm0.reg.data.u32 - 1));1317bld.mkOp1(OP_NEG, TYPE_S32, (v1 = bld.getSSA()), mod)1318->setPredicate(CC_P, neg);1319bld.mkOp1(OP_MOV, TYPE_S32, (v2 = bld.getSSA()), mod)1320->setPredicate(CC_NOT_P, neg);1321newi = bld.mkOp2(OP_UNION, TYPE_S32, i->getDef(0), v1, v2);13221323delete_Instruction(prog, i);1324deleted = true;1325}1326} else if (s == 1) {1327// In this case, we still want the optimized lowering that we get1328// from having division by an immediate.1329//1330// a % b == a - (a/b) * b1331bld.setPosition(i, false);1332Value *div = bld.mkOp2v(OP_DIV, i->sType, bld.getSSA(),1333i->getSrc(0), i->getSrc(1));1334newi = bld.mkOp2(OP_ADD, i->sType, i->getDef(0), i->getSrc(0),1335bld.mkOp2v(OP_MUL, i->sType, bld.getSSA(), div, i->getSrc(1)));1336// TODO: Check that target supports this. In this case, we know that1337// all backends do.1338newi->src(1).mod = Modifier(NV50_IR_MOD_NEG);13391340delete_Instruction(prog, i);1341deleted = true;1342}1343break;13441345case OP_SET: // TODO: SET_AND,OR,XOR1346{1347/* This optimizes the case where the output of a set is being compared1348* to zero. Since the set can only produce 0/-1 (int) or 0/1 (float), we1349* can be a lot cleverer in our comparison.1350*/1351CmpInstruction *si = findOriginForTestWithZero(i->getSrc(t));1352CondCode cc, ccZ;1353if (imm0.reg.data.u32 != 0 || !si)1354return false;1355cc = si->setCond;1356ccZ = (CondCode)((unsigned int)i->asCmp()->setCond & ~CC_U);1357// We do everything assuming var (cmp) 0, reverse the condition if 0 is1358// first.1359if (s == 0)1360ccZ = reverseCondCode(ccZ);1361// If there is a negative modifier, we need to undo that, by flipping1362// the comparison to zero.1363if (i->src(t).mod.neg())1364ccZ = reverseCondCode(ccZ);1365// If this is a signed comparison, we expect the input to be a regular1366// boolean, i.e. 0/-1. However the rest of the logic assumes that true1367// is positive, so just flip the sign.1368if (i->sType == TYPE_S32) {1369assert(!isFloatType(si->dType));1370ccZ = reverseCondCode(ccZ);1371}1372switch (ccZ) {1373case CC_LT: cc = CC_FL; break; // bool < 0 -- this is never true1374case CC_GE: cc = CC_TR; break; // bool >= 0 -- this is always true1375case CC_EQ: cc = inverseCondCode(cc); break; // bool == 0 -- !bool1376case CC_LE: cc = inverseCondCode(cc); break; // bool <= 0 -- !bool1377case CC_GT: break; // bool > 0 -- bool1378case CC_NE: break; // bool != 0 -- bool1379default:1380return false;1381}13821383// Update the condition of this SET to be identical to the origin set,1384// but with the updated condition code. The original SET should get1385// DCE'd, ideally.1386i->op = si->op;1387i->asCmp()->setCond = cc;1388i->setSrc(0, si->src(0));1389i->setSrc(1, si->src(1));1390if (si->srcExists(2))1391i->setSrc(2, si->src(2));1392i->sType = si->sType;1393}1394break;13951396case OP_AND:1397{1398Instruction *src = i->getSrc(t)->getInsn();1399ImmediateValue imm1;1400if (imm0.reg.data.u32 == 0) {1401i->op = OP_MOV;1402i->setSrc(0, new_ImmediateValue(prog, 0u));1403i->src(0).mod = Modifier(0);1404i->setSrc(1, NULL);1405} else if (imm0.reg.data.u32 == ~0U) {1406i->op = i->src(t).mod.getOp();1407if (t) {1408i->setSrc(0, i->getSrc(t));1409i->src(0).mod = i->src(t).mod;1410}1411i->setSrc(1, NULL);1412} else if (src->asCmp()) {1413CmpInstruction *cmp = src->asCmp();1414if (!cmp || cmp->op == OP_SLCT || cmp->getDef(0)->refCount() > 1)1415return false;1416if (!prog->getTarget()->isOpSupported(cmp->op, TYPE_F32))1417return false;1418if (imm0.reg.data.f32 != 1.0)1419return false;1420if (cmp->dType != TYPE_U32)1421return false;14221423cmp->dType = TYPE_F32;1424if (i->src(t).mod != Modifier(0)) {1425assert(i->src(t).mod == Modifier(NV50_IR_MOD_NOT));1426i->src(t).mod = Modifier(0);1427cmp->setCond = inverseCondCode(cmp->setCond);1428}1429i->op = OP_MOV;1430i->setSrc(s, NULL);1431if (t) {1432i->setSrc(0, i->getSrc(t));1433i->setSrc(t, NULL);1434}1435} else if (prog->getTarget()->isOpSupported(OP_EXTBF, TYPE_U32) &&1436src->op == OP_SHR &&1437src->src(1).getImmediate(imm1) &&1438i->src(t).mod == Modifier(0) &&1439util_is_power_of_two_or_zero(imm0.reg.data.u32 + 1)) {1440// low byte = offset, high byte = width1441uint32_t ext = (util_last_bit(imm0.reg.data.u32) << 8) | imm1.reg.data.u32;1442i->op = OP_EXTBF;1443i->setSrc(0, src->getSrc(0));1444i->setSrc(1, new_ImmediateValue(prog, ext));1445} else if (src->op == OP_SHL &&1446src->src(1).getImmediate(imm1) &&1447i->src(t).mod == Modifier(0) &&1448util_is_power_of_two_or_zero(~imm0.reg.data.u32 + 1) &&1449util_last_bit(~imm0.reg.data.u32) <= imm1.reg.data.u32) {1450i->op = OP_MOV;1451i->setSrc(s, NULL);1452if (t) {1453i->setSrc(0, i->getSrc(t));1454i->setSrc(t, NULL);1455}1456}1457}1458break;14591460case OP_SHL:1461{1462if (s != 1 || i->src(0).mod != Modifier(0))1463break;14641465if (imm0.reg.data.u32 == 0) {1466i->op = OP_MOV;1467i->setSrc(1, NULL);1468break;1469}1470// try to concatenate shifts1471Instruction *si = i->getSrc(0)->getInsn();1472if (!si)1473break;1474ImmediateValue imm1;1475switch (si->op) {1476case OP_SHL:1477if (si->src(1).getImmediate(imm1)) {1478bld.setPosition(i, false);1479i->setSrc(0, si->getSrc(0));1480i->setSrc(1, bld.loadImm(NULL, imm0.reg.data.u32 + imm1.reg.data.u32));1481}1482break;1483case OP_SHR:1484if (si->src(1).getImmediate(imm1) && imm0.reg.data.u32 == imm1.reg.data.u32) {1485bld.setPosition(i, false);1486i->op = OP_AND;1487i->setSrc(0, si->getSrc(0));1488i->setSrc(1, bld.loadImm(NULL, ~((1 << imm0.reg.data.u32) - 1)));1489}1490break;1491case OP_MUL:1492int muls;1493if (isFloatType(si->dType))1494return false;1495if (si->subOp)1496return false;1497if (si->src(1).getImmediate(imm1))1498muls = 1;1499else if (si->src(0).getImmediate(imm1))1500muls = 0;1501else1502return false;15031504bld.setPosition(i, false);1505i->op = OP_MUL;1506i->subOp = 0;1507i->dType = si->dType;1508i->sType = si->sType;1509i->setSrc(0, si->getSrc(!muls));1510i->setSrc(1, bld.loadImm(NULL, imm1.reg.data.u32 << imm0.reg.data.u32));1511break;1512case OP_SUB:1513case OP_ADD:1514int adds;1515if (isFloatType(si->dType))1516return false;1517if (si->op != OP_SUB && si->src(0).getImmediate(imm1))1518adds = 0;1519else if (si->src(1).getImmediate(imm1))1520adds = 1;1521else1522return false;1523if (si->src(!adds).mod != Modifier(0))1524return false;1525// SHL(ADD(x, y), z) = ADD(SHL(x, z), SHL(y, z))15261527// This is more operations, but if one of x, y is an immediate, then1528// we can get a situation where (a) we can use ISCADD, or (b)1529// propagate the add bit into an indirect load.1530bld.setPosition(i, false);1531i->op = si->op;1532i->setSrc(adds, bld.loadImm(NULL, imm1.reg.data.u32 << imm0.reg.data.u32));1533i->setSrc(!adds, bld.mkOp2v(OP_SHL, i->dType,1534bld.getSSA(i->def(0).getSize(), i->def(0).getFile()),1535si->getSrc(!adds),1536bld.mkImm(imm0.reg.data.u32)));1537break;1538default:1539return false;1540}1541}1542break;15431544case OP_ABS:1545case OP_NEG:1546case OP_SAT:1547case OP_LG2:1548case OP_RCP:1549case OP_SQRT:1550case OP_RSQ:1551case OP_PRESIN:1552case OP_SIN:1553case OP_COS:1554case OP_PREEX2:1555case OP_EX2:1556unary(i, imm0);1557break;1558case OP_BFIND: {1559int32_t res;1560switch (i->dType) {1561case TYPE_S32: res = util_last_bit_signed(imm0.reg.data.s32) - 1; break;1562case TYPE_U32: res = util_last_bit(imm0.reg.data.u32) - 1; break;1563default:1564return false;1565}1566if (i->subOp == NV50_IR_SUBOP_BFIND_SAMT && res >= 0)1567res = 31 - res;1568bld.setPosition(i, false); /* make sure bld is init'ed */1569i->setSrc(0, bld.mkImm(res));1570i->setSrc(1, NULL);1571i->op = OP_MOV;1572i->subOp = 0;1573break;1574}1575case OP_BREV: {1576uint32_t res = util_bitreverse(imm0.reg.data.u32);1577i->setSrc(0, new_ImmediateValue(i->bb->getProgram(), res));1578i->op = OP_MOV;1579break;1580}1581case OP_POPCNT: {1582// Only deal with 1-arg POPCNT here1583if (i->srcExists(1))1584break;1585uint32_t res = util_bitcount(imm0.reg.data.u32);1586i->setSrc(0, new_ImmediateValue(i->bb->getProgram(), res));1587i->setSrc(1, NULL);1588i->op = OP_MOV;1589break;1590}1591case OP_CVT: {1592Storage res;15931594// TODO: handle 64-bit values properly1595if (typeSizeof(i->dType) == 8 || typeSizeof(i->sType) == 8)1596return false;15971598// TODO: handle single byte/word extractions1599if (i->subOp)1600return false;16011602bld.setPosition(i, true); /* make sure bld is init'ed */16031604#define CASE(type, dst, fmin, fmax, imin, imax, umin, umax) \1605case type: \1606switch (i->sType) { \1607case TYPE_F64: \1608res.data.dst = util_iround(i->saturate ? \1609CLAMP(imm0.reg.data.f64, fmin, fmax) : \1610imm0.reg.data.f64); \1611break; \1612case TYPE_F32: \1613res.data.dst = util_iround(i->saturate ? \1614CLAMP(imm0.reg.data.f32, fmin, fmax) : \1615imm0.reg.data.f32); \1616break; \1617case TYPE_S32: \1618res.data.dst = i->saturate ? \1619CLAMP(imm0.reg.data.s32, imin, imax) : \1620imm0.reg.data.s32; \1621break; \1622case TYPE_U32: \1623res.data.dst = i->saturate ? \1624CLAMP(imm0.reg.data.u32, umin, umax) : \1625imm0.reg.data.u32; \1626break; \1627case TYPE_S16: \1628res.data.dst = i->saturate ? \1629CLAMP(imm0.reg.data.s16, imin, imax) : \1630imm0.reg.data.s16; \1631break; \1632case TYPE_U16: \1633res.data.dst = i->saturate ? \1634CLAMP(imm0.reg.data.u16, umin, umax) : \1635imm0.reg.data.u16; \1636break; \1637default: return false; \1638} \1639i->setSrc(0, bld.mkImm(res.data.dst)); \1640break16411642switch(i->dType) {1643CASE(TYPE_U16, u16, 0, UINT16_MAX, 0, UINT16_MAX, 0, UINT16_MAX);1644CASE(TYPE_S16, s16, INT16_MIN, INT16_MAX, INT16_MIN, INT16_MAX, 0, INT16_MAX);1645CASE(TYPE_U32, u32, 0, UINT32_MAX, 0, INT32_MAX, 0, UINT32_MAX);1646CASE(TYPE_S32, s32, INT32_MIN, INT32_MAX, INT32_MIN, INT32_MAX, 0, INT32_MAX);1647case TYPE_F32:1648switch (i->sType) {1649case TYPE_F64:1650res.data.f32 = i->saturate ?1651SATURATE(imm0.reg.data.f64) :1652imm0.reg.data.f64;1653break;1654case TYPE_F32:1655res.data.f32 = i->saturate ?1656SATURATE(imm0.reg.data.f32) :1657imm0.reg.data.f32;1658break;1659case TYPE_U16: res.data.f32 = (float) imm0.reg.data.u16; break;1660case TYPE_U32: res.data.f32 = (float) imm0.reg.data.u32; break;1661case TYPE_S16: res.data.f32 = (float) imm0.reg.data.s16; break;1662case TYPE_S32: res.data.f32 = (float) imm0.reg.data.s32; break;1663default:1664return false;1665}1666i->setSrc(0, bld.mkImm(res.data.f32));1667break;1668case TYPE_F64:1669switch (i->sType) {1670case TYPE_F64:1671res.data.f64 = i->saturate ?1672SATURATE(imm0.reg.data.f64) :1673imm0.reg.data.f64;1674break;1675case TYPE_F32:1676res.data.f64 = i->saturate ?1677SATURATE(imm0.reg.data.f32) :1678imm0.reg.data.f32;1679break;1680case TYPE_U16: res.data.f64 = (double) imm0.reg.data.u16; break;1681case TYPE_U32: res.data.f64 = (double) imm0.reg.data.u32; break;1682case TYPE_S16: res.data.f64 = (double) imm0.reg.data.s16; break;1683case TYPE_S32: res.data.f64 = (double) imm0.reg.data.s32; break;1684default:1685return false;1686}1687i->setSrc(0, bld.mkImm(res.data.f64));1688break;1689default:1690return false;1691}1692#undef CASE16931694i->setType(i->dType); /* Remove i->sType, which we don't need anymore */1695i->op = OP_MOV;1696i->saturate = 0;1697i->src(0).mod = Modifier(0); /* Clear the already applied modifier */1698break;1699}1700default:1701return false;1702}17031704// This can get left behind some of the optimizations which simplify1705// saturatable values.1706if (newi->op == OP_MOV && newi->saturate) {1707ImmediateValue tmp;1708newi->saturate = 0;1709newi->op = OP_SAT;1710if (newi->src(0).getImmediate(tmp))1711unary(newi, tmp);1712}17131714if (newi->op != op)1715foldCount++;1716return deleted;1717}17181719// =============================================================================17201721// Merge modifier operations (ABS, NEG, NOT) into ValueRefs where allowed.1722class ModifierFolding : public Pass1723{1724private:1725virtual bool visit(BasicBlock *);1726};17271728bool1729ModifierFolding::visit(BasicBlock *bb)1730{1731const Target *target = prog->getTarget();17321733Instruction *i, *next, *mi;1734Modifier mod;17351736for (i = bb->getEntry(); i; i = next) {1737next = i->next;17381739if (0 && i->op == OP_SUB) {1740// turn "sub" into "add neg" (do we really want this ?)1741i->op = OP_ADD;1742i->src(0).mod = i->src(0).mod ^ Modifier(NV50_IR_MOD_NEG);1743}17441745for (int s = 0; s < 3 && i->srcExists(s); ++s) {1746mi = i->getSrc(s)->getInsn();1747if (!mi ||1748mi->predSrc >= 0 || mi->getDef(0)->refCount() > 8)1749continue;1750if (i->sType == TYPE_U32 && mi->dType == TYPE_S32) {1751if ((i->op != OP_ADD &&1752i->op != OP_MUL) ||1753(mi->op != OP_ABS &&1754mi->op != OP_NEG))1755continue;1756} else1757if (i->sType != mi->dType) {1758continue;1759}1760if ((mod = Modifier(mi->op)) == Modifier(0))1761continue;1762mod *= mi->src(0).mod;17631764if ((i->op == OP_ABS) || i->src(s).mod.abs()) {1765// abs neg [abs] = abs1766mod = mod & Modifier(~(NV50_IR_MOD_NEG | NV50_IR_MOD_ABS));1767} else1768if ((i->op == OP_NEG) && mod.neg()) {1769assert(s == 0);1770// neg as both opcode and modifier on same insn is prohibited1771// neg neg abs = abs, neg neg = identity1772mod = mod & Modifier(~NV50_IR_MOD_NEG);1773i->op = mod.getOp();1774mod = mod & Modifier(~NV50_IR_MOD_ABS);1775if (mod == Modifier(0))1776i->op = OP_MOV;1777}17781779if (target->isModSupported(i, s, mod)) {1780i->setSrc(s, mi->getSrc(0));1781i->src(s).mod *= mod;1782}1783}17841785if (i->op == OP_SAT) {1786mi = i->getSrc(0)->getInsn();1787if (mi &&1788mi->getDef(0)->refCount() <= 1 && target->isSatSupported(mi)) {1789mi->saturate = 1;1790mi->setDef(0, i->getDef(0));1791delete_Instruction(prog, i);1792}1793}1794}17951796return true;1797}17981799// =============================================================================18001801// MUL + ADD -> MAD/FMA1802// MIN/MAX(a, a) -> a, etc.1803// SLCT(a, b, const) -> cc(const) ? a : b1804// RCP(RCP(a)) -> a1805// MUL(MUL(a, b), const) -> MUL_Xconst(a, b)1806// EXTBF(RDSV(COMBINED_TID)) -> RDSV(TID)1807class AlgebraicOpt : public Pass1808{1809private:1810virtual bool visit(BasicBlock *);18111812void handleABS(Instruction *);1813bool handleADD(Instruction *);1814bool tryADDToMADOrSAD(Instruction *, operation toOp);1815void handleMINMAX(Instruction *);1816void handleRCP(Instruction *);1817void handleSLCT(Instruction *);1818void handleLOGOP(Instruction *);1819void handleCVT_NEG(Instruction *);1820void handleCVT_CVT(Instruction *);1821void handleCVT_EXTBF(Instruction *);1822void handleSUCLAMP(Instruction *);1823void handleNEG(Instruction *);1824void handleEXTBF_RDSV(Instruction *);18251826BuildUtil bld;1827};18281829void1830AlgebraicOpt::handleABS(Instruction *abs)1831{1832Instruction *sub = abs->getSrc(0)->getInsn();1833DataType ty;1834if (!sub ||1835!prog->getTarget()->isOpSupported(OP_SAD, abs->dType))1836return;1837// expect not to have mods yet, if we do, bail1838if (sub->src(0).mod || sub->src(1).mod)1839return;1840// hidden conversion ?1841ty = intTypeToSigned(sub->dType);1842if (abs->dType != abs->sType || ty != abs->sType)1843return;18441845if ((sub->op != OP_ADD && sub->op != OP_SUB) ||1846sub->src(0).getFile() != FILE_GPR || sub->src(0).mod ||1847sub->src(1).getFile() != FILE_GPR || sub->src(1).mod)1848return;18491850Value *src0 = sub->getSrc(0);1851Value *src1 = sub->getSrc(1);18521853if (sub->op == OP_ADD) {1854Instruction *neg = sub->getSrc(1)->getInsn();1855if (neg && neg->op != OP_NEG) {1856neg = sub->getSrc(0)->getInsn();1857src0 = sub->getSrc(1);1858}1859if (!neg || neg->op != OP_NEG ||1860neg->dType != neg->sType || neg->sType != ty)1861return;1862src1 = neg->getSrc(0);1863}18641865// found ABS(SUB))1866abs->moveSources(1, 2); // move sources >=1 up by 21867abs->op = OP_SAD;1868abs->setType(sub->dType);1869abs->setSrc(0, src0);1870abs->setSrc(1, src1);1871bld.setPosition(abs, false);1872abs->setSrc(2, bld.loadImm(bld.getSSA(typeSizeof(ty)), 0));1873}18741875bool1876AlgebraicOpt::handleADD(Instruction *add)1877{1878Value *src0 = add->getSrc(0);1879Value *src1 = add->getSrc(1);18801881if (src0->reg.file != FILE_GPR || src1->reg.file != FILE_GPR)1882return false;18831884bool changed = false;1885// we can't optimize to MAD if the add is precise1886if (!add->precise && prog->getTarget()->isOpSupported(OP_MAD, add->dType))1887changed = tryADDToMADOrSAD(add, OP_MAD);1888if (!changed && prog->getTarget()->isOpSupported(OP_SAD, add->dType))1889changed = tryADDToMADOrSAD(add, OP_SAD);1890return changed;1891}18921893// ADD(SAD(a,b,0), c) -> SAD(a,b,c)1894// ADD(MUL(a,b), c) -> MAD(a,b,c)1895bool1896AlgebraicOpt::tryADDToMADOrSAD(Instruction *add, operation toOp)1897{1898Value *src0 = add->getSrc(0);1899Value *src1 = add->getSrc(1);1900Value *src;1901int s;1902const operation srcOp = toOp == OP_SAD ? OP_SAD : OP_MUL;1903const Modifier modBad = Modifier(~((toOp == OP_MAD) ? NV50_IR_MOD_NEG : 0));1904Modifier mod[4];19051906if (src0->refCount() == 1 &&1907src0->getUniqueInsn() && src0->getUniqueInsn()->op == srcOp)1908s = 0;1909else1910if (src1->refCount() == 1 &&1911src1->getUniqueInsn() && src1->getUniqueInsn()->op == srcOp)1912s = 1;1913else1914return false;19151916src = add->getSrc(s);19171918if (src->getUniqueInsn() && src->getUniqueInsn()->bb != add->bb)1919return false;19201921if (src->getInsn()->saturate || src->getInsn()->postFactor ||1922src->getInsn()->dnz || src->getInsn()->precise)1923return false;19241925if (toOp == OP_SAD) {1926ImmediateValue imm;1927if (!src->getInsn()->src(2).getImmediate(imm))1928return false;1929if (!imm.isInteger(0))1930return false;1931}19321933if (typeSizeof(add->dType) != typeSizeof(src->getInsn()->dType) ||1934isFloatType(add->dType) != isFloatType(src->getInsn()->dType))1935return false;19361937mod[0] = add->src(0).mod;1938mod[1] = add->src(1).mod;1939mod[2] = src->getUniqueInsn()->src(0).mod;1940mod[3] = src->getUniqueInsn()->src(1).mod;19411942if (((mod[0] | mod[1]) | (mod[2] | mod[3])) & modBad)1943return false;19441945add->op = toOp;1946add->subOp = src->getInsn()->subOp; // potentially mul-high1947add->dnz = src->getInsn()->dnz;1948add->dType = src->getInsn()->dType; // sign matters for imad hi1949add->sType = src->getInsn()->sType;19501951add->setSrc(2, add->src(s ? 0 : 1));19521953add->setSrc(0, src->getInsn()->getSrc(0));1954add->src(0).mod = mod[2] ^ mod[s];1955add->setSrc(1, src->getInsn()->getSrc(1));1956add->src(1).mod = mod[3];19571958return true;1959}19601961void1962AlgebraicOpt::handleMINMAX(Instruction *minmax)1963{1964Value *src0 = minmax->getSrc(0);1965Value *src1 = minmax->getSrc(1);19661967if (src0 != src1 || src0->reg.file != FILE_GPR)1968return;1969if (minmax->src(0).mod == minmax->src(1).mod) {1970if (minmax->def(0).mayReplace(minmax->src(0))) {1971minmax->def(0).replace(minmax->src(0), false);1972delete_Instruction(prog, minmax);1973} else {1974minmax->op = OP_CVT;1975minmax->setSrc(1, NULL);1976}1977} else {1978// TODO:1979// min(x, -x) = -abs(x)1980// min(x, -abs(x)) = -abs(x)1981// min(x, abs(x)) = x1982// max(x, -abs(x)) = x1983// max(x, abs(x)) = abs(x)1984// max(x, -x) = abs(x)1985}1986}19871988// rcp(rcp(a)) = a1989// rcp(sqrt(a)) = rsq(a)1990void1991AlgebraicOpt::handleRCP(Instruction *rcp)1992{1993Instruction *si = rcp->getSrc(0)->getUniqueInsn();19941995if (!si)1996return;19971998if (si->op == OP_RCP) {1999Modifier mod = rcp->src(0).mod * si->src(0).mod;2000rcp->op = mod.getOp();2001rcp->setSrc(0, si->getSrc(0));2002} else if (si->op == OP_SQRT) {2003rcp->op = OP_RSQ;2004rcp->setSrc(0, si->getSrc(0));2005rcp->src(0).mod = rcp->src(0).mod * si->src(0).mod;2006}2007}20082009void2010AlgebraicOpt::handleSLCT(Instruction *slct)2011{2012if (slct->getSrc(2)->reg.file == FILE_IMMEDIATE) {2013if (slct->getSrc(2)->asImm()->compare(slct->asCmp()->setCond, 0.0f))2014slct->setSrc(0, slct->getSrc(1));2015} else2016if (slct->getSrc(0) != slct->getSrc(1)) {2017return;2018}2019slct->op = OP_MOV;2020slct->setSrc(1, NULL);2021slct->setSrc(2, NULL);2022}20232024void2025AlgebraicOpt::handleLOGOP(Instruction *logop)2026{2027Value *src0 = logop->getSrc(0);2028Value *src1 = logop->getSrc(1);20292030if (src0->reg.file != FILE_GPR || src1->reg.file != FILE_GPR)2031return;20322033if (src0 == src1) {2034if ((logop->op == OP_AND || logop->op == OP_OR) &&2035logop->def(0).mayReplace(logop->src(0))) {2036logop->def(0).replace(logop->src(0), false);2037delete_Instruction(prog, logop);2038}2039} else {2040// try AND(SET, SET) -> SET_AND(SET)2041Instruction *set0 = src0->getInsn();2042Instruction *set1 = src1->getInsn();20432044if (!set0 || set0->fixed || !set1 || set1->fixed)2045return;2046if (set1->op != OP_SET) {2047Instruction *xchg = set0;2048set0 = set1;2049set1 = xchg;2050if (set1->op != OP_SET)2051return;2052}2053operation redOp = (logop->op == OP_AND ? OP_SET_AND :2054logop->op == OP_XOR ? OP_SET_XOR : OP_SET_OR);2055if (!prog->getTarget()->isOpSupported(redOp, set1->sType))2056return;2057if (set0->op != OP_SET &&2058set0->op != OP_SET_AND &&2059set0->op != OP_SET_OR &&2060set0->op != OP_SET_XOR)2061return;2062if (set0->getDef(0)->refCount() > 1 &&2063set1->getDef(0)->refCount() > 1)2064return;2065if (set0->getPredicate() || set1->getPredicate())2066return;2067// check that they don't source each other2068for (int s = 0; s < 2; ++s)2069if (set0->getSrc(s) == set1->getDef(0) ||2070set1->getSrc(s) == set0->getDef(0))2071return;20722073set0 = cloneForward(func, set0);2074set1 = cloneShallow(func, set1);2075logop->bb->insertAfter(logop, set1);2076logop->bb->insertAfter(logop, set0);20772078set0->dType = TYPE_U8;2079set0->getDef(0)->reg.file = FILE_PREDICATE;2080set0->getDef(0)->reg.size = 1;2081set1->setSrc(2, set0->getDef(0));2082set1->op = redOp;2083set1->setDef(0, logop->getDef(0));2084delete_Instruction(prog, logop);2085}2086}20872088// F2I(NEG(SET with result 1.0f/0.0f)) -> SET with result -1/02089// nv50:2090// F2I(NEG(I2F(ABS(SET))))2091void2092AlgebraicOpt::handleCVT_NEG(Instruction *cvt)2093{2094Instruction *insn = cvt->getSrc(0)->getInsn();2095if (cvt->sType != TYPE_F32 ||2096cvt->dType != TYPE_S32 || cvt->src(0).mod != Modifier(0))2097return;2098if (!insn || insn->op != OP_NEG || insn->dType != TYPE_F32)2099return;2100if (insn->src(0).mod != Modifier(0))2101return;2102insn = insn->getSrc(0)->getInsn();21032104// check for nv50 SET(-1,0) -> SET(1.0f/0.0f) chain and nvc0's f32 SET2105if (insn && insn->op == OP_CVT &&2106insn->dType == TYPE_F32 &&2107insn->sType == TYPE_S32) {2108insn = insn->getSrc(0)->getInsn();2109if (!insn || insn->op != OP_ABS || insn->sType != TYPE_S32 ||2110insn->src(0).mod)2111return;2112insn = insn->getSrc(0)->getInsn();2113if (!insn || insn->op != OP_SET || insn->dType != TYPE_U32)2114return;2115} else2116if (!insn || insn->op != OP_SET || insn->dType != TYPE_F32) {2117return;2118}21192120Instruction *bset = cloneShallow(func, insn);2121bset->dType = TYPE_U32;2122bset->setDef(0, cvt->getDef(0));2123cvt->bb->insertAfter(cvt, bset);2124delete_Instruction(prog, cvt);2125}21262127// F2I(TRUNC()) and so on can be expressed as a single CVT. If the earlier CVT2128// does a type conversion, this becomes trickier as there might be range2129// changes/etc. We could handle those in theory as long as the range was being2130// reduced or kept the same.2131void2132AlgebraicOpt::handleCVT_CVT(Instruction *cvt)2133{2134Instruction *insn = cvt->getSrc(0)->getInsn();21352136if (!insn ||2137insn->saturate ||2138insn->subOp ||2139insn->dType != insn->sType ||2140insn->dType != cvt->sType)2141return;21422143RoundMode rnd = insn->rnd;2144switch (insn->op) {2145case OP_CEIL:2146rnd = ROUND_PI;2147break;2148case OP_FLOOR:2149rnd = ROUND_MI;2150break;2151case OP_TRUNC:2152rnd = ROUND_ZI;2153break;2154case OP_CVT:2155break;2156default:2157return;2158}21592160if (!isFloatType(cvt->dType) || !isFloatType(insn->sType))2161rnd = (RoundMode)(rnd & 3);21622163cvt->rnd = rnd;2164cvt->setSrc(0, insn->getSrc(0));2165cvt->src(0).mod *= insn->src(0).mod;2166cvt->sType = insn->sType;2167}21682169// Some shaders extract packed bytes out of words and convert them to2170// e.g. float. The Fermi+ CVT instruction can extract those directly, as can2171// nv50 for word sizes.2172//2173// CVT(EXTBF(x, byte/word))2174// CVT(AND(bytemask, x))2175// CVT(AND(bytemask, SHR(x, 8/16/24)))2176// CVT(SHR(x, 16/24))2177void2178AlgebraicOpt::handleCVT_EXTBF(Instruction *cvt)2179{2180Instruction *insn = cvt->getSrc(0)->getInsn();2181ImmediateValue imm;2182Value *arg = NULL;2183unsigned width, offset = 0;2184if ((cvt->sType != TYPE_U32 && cvt->sType != TYPE_S32) || !insn)2185return;2186if (insn->op == OP_EXTBF && insn->src(1).getImmediate(imm)) {2187width = (imm.reg.data.u32 >> 8) & 0xff;2188offset = imm.reg.data.u32 & 0xff;2189arg = insn->getSrc(0);21902191if (width != 8 && width != 16)2192return;2193if (width == 8 && offset & 0x7)2194return;2195if (width == 16 && offset & 0xf)2196return;2197} else if (insn->op == OP_AND) {2198int s;2199if (insn->src(0).getImmediate(imm))2200s = 0;2201else if (insn->src(1).getImmediate(imm))2202s = 1;2203else2204return;22052206if (imm.reg.data.u32 == 0xff)2207width = 8;2208else if (imm.reg.data.u32 == 0xffff)2209width = 16;2210else2211return;22122213arg = insn->getSrc(!s);2214Instruction *shift = arg->getInsn();22152216if (shift && shift->op == OP_SHR &&2217shift->sType == cvt->sType &&2218shift->src(1).getImmediate(imm) &&2219((width == 8 && (imm.reg.data.u32 & 0x7) == 0) ||2220(width == 16 && (imm.reg.data.u32 & 0xf) == 0))) {2221arg = shift->getSrc(0);2222offset = imm.reg.data.u32;2223}2224// We just AND'd the high bits away, which means this is effectively an2225// unsigned value.2226cvt->sType = TYPE_U32;2227} else if (insn->op == OP_SHR &&2228insn->sType == cvt->sType &&2229insn->src(1).getImmediate(imm)) {2230arg = insn->getSrc(0);2231if (imm.reg.data.u32 == 24) {2232width = 8;2233offset = 24;2234} else if (imm.reg.data.u32 == 16) {2235width = 16;2236offset = 16;2237} else {2238return;2239}2240}22412242if (!arg)2243return;22442245// Irrespective of what came earlier, we can undo a shift on the argument2246// by adjusting the offset.2247Instruction *shift = arg->getInsn();2248if (shift && shift->op == OP_SHL &&2249shift->src(1).getImmediate(imm) &&2250((width == 8 && (imm.reg.data.u32 & 0x7) == 0) ||2251(width == 16 && (imm.reg.data.u32 & 0xf) == 0)) &&2252imm.reg.data.u32 <= offset) {2253arg = shift->getSrc(0);2254offset -= imm.reg.data.u32;2255}22562257// The unpackSnorm lowering still leaves a few shifts behind, but it's too2258// annoying to detect them.22592260if (width == 8) {2261cvt->sType = cvt->sType == TYPE_U32 ? TYPE_U8 : TYPE_S8;2262} else {2263assert(width == 16);2264cvt->sType = cvt->sType == TYPE_U32 ? TYPE_U16 : TYPE_S16;2265}2266cvt->setSrc(0, arg);2267cvt->subOp = offset >> 3;2268}22692270// SUCLAMP dst, (ADD b imm), k, 0 -> SUCLAMP dst, b, k, imm (if imm fits s6)2271void2272AlgebraicOpt::handleSUCLAMP(Instruction *insn)2273{2274ImmediateValue imm;2275int32_t val = insn->getSrc(2)->asImm()->reg.data.s32;2276int s;2277Instruction *add;22782279assert(insn->srcExists(0) && insn->src(0).getFile() == FILE_GPR);22802281// look for ADD (TODO: only count references by non-SUCLAMP)2282if (insn->getSrc(0)->refCount() > 1)2283return;2284add = insn->getSrc(0)->getInsn();2285if (!add || add->op != OP_ADD ||2286(add->dType != TYPE_U32 &&2287add->dType != TYPE_S32))2288return;22892290// look for immediate2291for (s = 0; s < 2; ++s)2292if (add->src(s).getImmediate(imm))2293break;2294if (s >= 2)2295return;2296s = s ? 0 : 1;2297// determine if immediate fits2298val += imm.reg.data.s32;2299if (val > 31 || val < -32)2300return;2301// determine if other addend fits2302if (add->src(s).getFile() != FILE_GPR || add->src(s).mod != Modifier(0))2303return;23042305bld.setPosition(insn, false); // make sure bld is init'ed2306// replace sources2307insn->setSrc(2, bld.mkImm(val));2308insn->setSrc(0, add->getSrc(s));2309}23102311// NEG(AND(SET, 1)) -> SET2312void2313AlgebraicOpt::handleNEG(Instruction *i) {2314Instruction *src = i->getSrc(0)->getInsn();2315ImmediateValue imm;2316int b;23172318if (isFloatType(i->sType) || !src || src->op != OP_AND)2319return;23202321if (src->src(0).getImmediate(imm))2322b = 1;2323else if (src->src(1).getImmediate(imm))2324b = 0;2325else2326return;23272328if (!imm.isInteger(1))2329return;23302331Instruction *set = src->getSrc(b)->getInsn();2332if ((set->op == OP_SET || set->op == OP_SET_AND ||2333set->op == OP_SET_OR || set->op == OP_SET_XOR) &&2334!isFloatType(set->dType)) {2335i->def(0).replace(set->getDef(0), false);2336}2337}23382339// EXTBF(RDSV(COMBINED_TID)) -> RDSV(TID)2340void2341AlgebraicOpt::handleEXTBF_RDSV(Instruction *i)2342{2343Instruction *rdsv = i->getSrc(0)->getUniqueInsn();2344if (rdsv->op != OP_RDSV ||2345rdsv->getSrc(0)->asSym()->reg.data.sv.sv != SV_COMBINED_TID)2346return;2347// Avoid creating more RDSV instructions2348if (rdsv->getDef(0)->refCount() > 1)2349return;23502351ImmediateValue imm;2352if (!i->src(1).getImmediate(imm))2353return;23542355int index;2356if (imm.isInteger(0x1000))2357index = 0;2358else2359if (imm.isInteger(0x0a10))2360index = 1;2361else2362if (imm.isInteger(0x061a))2363index = 2;2364else2365return;23662367bld.setPosition(i, false);23682369i->op = OP_RDSV;2370i->setSrc(0, bld.mkSysVal(SV_TID, index));2371i->setSrc(1, NULL);2372}23732374bool2375AlgebraicOpt::visit(BasicBlock *bb)2376{2377Instruction *next;2378for (Instruction *i = bb->getEntry(); i; i = next) {2379next = i->next;2380switch (i->op) {2381case OP_ABS:2382handleABS(i);2383break;2384case OP_ADD:2385handleADD(i);2386break;2387case OP_RCP:2388handleRCP(i);2389break;2390case OP_MIN:2391case OP_MAX:2392handleMINMAX(i);2393break;2394case OP_SLCT:2395handleSLCT(i);2396break;2397case OP_AND:2398case OP_OR:2399case OP_XOR:2400handleLOGOP(i);2401break;2402case OP_CVT:2403handleCVT_NEG(i);2404handleCVT_CVT(i);2405if (prog->getTarget()->isOpSupported(OP_EXTBF, TYPE_U32))2406handleCVT_EXTBF(i);2407break;2408case OP_SUCLAMP:2409handleSUCLAMP(i);2410break;2411case OP_NEG:2412handleNEG(i);2413break;2414case OP_EXTBF:2415handleEXTBF_RDSV(i);2416break;2417default:2418break;2419}2420}24212422return true;2423}24242425// =============================================================================24262427// ADD(SHL(a, b), c) -> SHLADD(a, b, c)2428// MUL(a, b) -> a few XMADs2429// MAD/FMA(a, b, c) -> a few XMADs2430class LateAlgebraicOpt : public Pass2431{2432private:2433virtual bool visit(Instruction *);24342435void handleADD(Instruction *);2436void handleMULMAD(Instruction *);2437bool tryADDToSHLADD(Instruction *);24382439BuildUtil bld;2440};24412442void2443LateAlgebraicOpt::handleADD(Instruction *add)2444{2445Value *src0 = add->getSrc(0);2446Value *src1 = add->getSrc(1);24472448if (src0->reg.file != FILE_GPR || src1->reg.file != FILE_GPR)2449return;24502451if (prog->getTarget()->isOpSupported(OP_SHLADD, add->dType))2452tryADDToSHLADD(add);2453}24542455// ADD(SHL(a, b), c) -> SHLADD(a, b, c)2456bool2457LateAlgebraicOpt::tryADDToSHLADD(Instruction *add)2458{2459Value *src0 = add->getSrc(0);2460Value *src1 = add->getSrc(1);2461ImmediateValue imm;2462Instruction *shl;2463Value *src;2464int s;24652466if (add->saturate || add->usesFlags() || typeSizeof(add->dType) == 82467|| isFloatType(add->dType))2468return false;24692470if (src0->getUniqueInsn() && src0->getUniqueInsn()->op == OP_SHL)2471s = 0;2472else2473if (src1->getUniqueInsn() && src1->getUniqueInsn()->op == OP_SHL)2474s = 1;2475else2476return false;24772478src = add->getSrc(s);2479shl = src->getUniqueInsn();24802481if (shl->bb != add->bb || shl->usesFlags() || shl->subOp || shl->src(0).mod)2482return false;24832484if (!shl->src(1).getImmediate(imm))2485return false;24862487add->op = OP_SHLADD;2488add->setSrc(2, add->src(!s));2489// SHL can't have any modifiers, but the ADD source may have had2490// one. Preserve it.2491add->setSrc(0, shl->getSrc(0));2492if (s == 1)2493add->src(0).mod = add->src(1).mod;2494add->setSrc(1, new_ImmediateValue(shl->bb->getProgram(), imm.reg.data.u32));2495add->src(1).mod = Modifier(0);24962497return true;2498}24992500// MUL(a, b) -> a few XMADs2501// MAD/FMA(a, b, c) -> a few XMADs2502void2503LateAlgebraicOpt::handleMULMAD(Instruction *i)2504{2505// TODO: handle NV50_IR_SUBOP_MUL_HIGH2506if (!prog->getTarget()->isOpSupported(OP_XMAD, TYPE_U32))2507return;2508if (isFloatType(i->dType) || typeSizeof(i->dType) != 4)2509return;2510if (i->subOp || i->usesFlags() || i->flagsDef >= 0)2511return;25122513assert(!i->src(0).mod);2514assert(!i->src(1).mod);2515assert(i->op == OP_MUL ? 1 : !i->src(2).mod);25162517bld.setPosition(i, false);25182519Value *a = i->getSrc(0);2520Value *b = i->getSrc(1);2521Value *c = i->op == OP_MUL ? bld.mkImm(0) : i->getSrc(2);25222523Value *tmp0 = bld.getSSA();2524Value *tmp1 = bld.getSSA();25252526Instruction *insn = bld.mkOp3(OP_XMAD, TYPE_U32, tmp0, b, a, c);2527insn->setPredicate(i->cc, i->getPredicate());25282529insn = bld.mkOp3(OP_XMAD, TYPE_U32, tmp1, b, a, bld.mkImm(0));2530insn->setPredicate(i->cc, i->getPredicate());2531insn->subOp = NV50_IR_SUBOP_XMAD_MRG | NV50_IR_SUBOP_XMAD_H1(1);25322533Value *pred = i->getPredicate();2534i->setPredicate(i->cc, NULL);25352536i->op = OP_XMAD;2537i->setSrc(0, b);2538i->setSrc(1, tmp1);2539i->setSrc(2, tmp0);2540i->subOp = NV50_IR_SUBOP_XMAD_PSL | NV50_IR_SUBOP_XMAD_CBCC;2541i->subOp |= NV50_IR_SUBOP_XMAD_H1(0) | NV50_IR_SUBOP_XMAD_H1(1);25422543i->setPredicate(i->cc, pred);2544}25452546bool2547LateAlgebraicOpt::visit(Instruction *i)2548{2549switch (i->op) {2550case OP_ADD:2551handleADD(i);2552break;2553case OP_MUL:2554case OP_MAD:2555case OP_FMA:2556handleMULMAD(i);2557break;2558default:2559break;2560}25612562return true;2563}25642565// =============================================================================25662567// Split 64-bit MUL and MAD2568class Split64BitOpPreRA : public Pass2569{2570private:2571virtual bool visit(BasicBlock *);2572void split64MulMad(Function *, Instruction *, DataType);25732574BuildUtil bld;2575};25762577bool2578Split64BitOpPreRA::visit(BasicBlock *bb)2579{2580Instruction *i, *next;2581Modifier mod;25822583for (i = bb->getEntry(); i; i = next) {2584next = i->next;25852586DataType hTy;2587switch (i->dType) {2588case TYPE_U64: hTy = TYPE_U32; break;2589case TYPE_S64: hTy = TYPE_S32; break;2590default:2591continue;2592}25932594if (i->op == OP_MAD || i->op == OP_MUL)2595split64MulMad(func, i, hTy);2596}25972598return true;2599}26002601void2602Split64BitOpPreRA::split64MulMad(Function *fn, Instruction *i, DataType hTy)2603{2604assert(i->op == OP_MAD || i->op == OP_MUL);2605assert(!isFloatType(i->dType) && !isFloatType(i->sType));2606assert(typeSizeof(hTy) == 4);26072608bld.setPosition(i, true);26092610Value *zero = bld.mkImm(0u);2611Value *carry = bld.getSSA(1, FILE_FLAGS);26122613// We want to compute `d = a * b (+ c)?`, where a, b, c and d are 64-bit2614// values (a, b and c might be 32-bit values), using 32-bit operations. This2615// gives the following operations:2616// * `d.low = low(a.low * b.low) (+ c.low)?`2617// * `d.high = low(a.high * b.low) + low(a.low * b.high)2618// + high(a.low * b.low) (+ c.high)?`2619//2620// To compute the high bits, we can split in the following operations:2621// * `tmp1 = low(a.high * b.low) (+ c.high)?`2622// * `tmp2 = low(a.low * b.high) + tmp1`2623// * `d.high = high(a.low * b.low) + tmp2`2624//2625// mkSplit put lower bits at index 0 and higher bits at index 126262627Value *op1[2];2628if (i->getSrc(0)->reg.size == 8)2629bld.mkSplit(op1, 4, i->getSrc(0));2630else {2631op1[0] = i->getSrc(0);2632op1[1] = zero;2633}2634Value *op2[2];2635if (i->getSrc(1)->reg.size == 8)2636bld.mkSplit(op2, 4, i->getSrc(1));2637else {2638op2[0] = i->getSrc(1);2639op2[1] = zero;2640}26412642Value *op3[2] = { NULL, NULL };2643if (i->op == OP_MAD) {2644if (i->getSrc(2)->reg.size == 8)2645bld.mkSplit(op3, 4, i->getSrc(2));2646else {2647op3[0] = i->getSrc(2);2648op3[1] = zero;2649}2650}26512652Value *tmpRes1Hi = bld.getSSA();2653if (i->op == OP_MAD)2654bld.mkOp3(OP_MAD, hTy, tmpRes1Hi, op1[1], op2[0], op3[1]);2655else2656bld.mkOp2(OP_MUL, hTy, tmpRes1Hi, op1[1], op2[0]);26572658Value *tmpRes2Hi = bld.mkOp3v(OP_MAD, hTy, bld.getSSA(), op1[0], op2[1], tmpRes1Hi);26592660Value *def[2] = { bld.getSSA(), bld.getSSA() };26612662// If it was a MAD, add the carry from the low bits2663// It is not needed if it was a MUL, since we added high(a.low * b.low) to2664// d.high2665if (i->op == OP_MAD)2666bld.mkOp3(OP_MAD, hTy, def[0], op1[0], op2[0], op3[0])->setFlagsDef(1, carry);2667else2668bld.mkOp2(OP_MUL, hTy, def[0], op1[0], op2[0]);26692670Instruction *hiPart3 = bld.mkOp3(OP_MAD, hTy, def[1], op1[0], op2[0], tmpRes2Hi);2671hiPart3->subOp = NV50_IR_SUBOP_MUL_HIGH;2672if (i->op == OP_MAD)2673hiPart3->setFlagsSrc(3, carry);26742675bld.mkOp2(OP_MERGE, i->dType, i->getDef(0), def[0], def[1]);26762677delete_Instruction(fn->getProgram(), i);2678}26792680// =============================================================================26812682static inline void2683updateLdStOffset(Instruction *ldst, int32_t offset, Function *fn)2684{2685if (offset != ldst->getSrc(0)->reg.data.offset) {2686if (ldst->getSrc(0)->refCount() > 1)2687ldst->setSrc(0, cloneShallow(fn, ldst->getSrc(0)));2688ldst->getSrc(0)->reg.data.offset = offset;2689}2690}26912692// Combine loads and stores, forward stores to loads where possible.2693class MemoryOpt : public Pass2694{2695private:2696class Record2697{2698public:2699Record *next;2700Instruction *insn;2701const Value *rel[2];2702const Value *base;2703int32_t offset;2704int8_t fileIndex;2705uint8_t size;2706bool locked;2707Record *prev;27082709bool overlaps(const Instruction *ldst) const;27102711inline void link(Record **);2712inline void unlink(Record **);2713inline void set(const Instruction *ldst);2714};27152716public:2717MemoryOpt();27182719Record *loads[DATA_FILE_COUNT];2720Record *stores[DATA_FILE_COUNT];27212722MemoryPool recordPool;27232724private:2725virtual bool visit(BasicBlock *);2726bool runOpt(BasicBlock *);27272728Record **getList(const Instruction *);27292730Record *findRecord(const Instruction *, bool load, bool& isAdjacent) const;27312732// merge @insn into load/store instruction from @rec2733bool combineLd(Record *rec, Instruction *ld);2734bool combineSt(Record *rec, Instruction *st);27352736bool replaceLdFromLd(Instruction *ld, Record *ldRec);2737bool replaceLdFromSt(Instruction *ld, Record *stRec);2738bool replaceStFromSt(Instruction *restrict st, Record *stRec);27392740void addRecord(Instruction *ldst);2741void purgeRecords(Instruction *const st, DataFile);2742void lockStores(Instruction *const ld);2743void reset();27442745private:2746Record *prevRecord;2747};27482749MemoryOpt::MemoryOpt() : recordPool(sizeof(MemoryOpt::Record), 6)2750{2751for (int i = 0; i < DATA_FILE_COUNT; ++i) {2752loads[i] = NULL;2753stores[i] = NULL;2754}2755prevRecord = NULL;2756}27572758void2759MemoryOpt::reset()2760{2761for (unsigned int i = 0; i < DATA_FILE_COUNT; ++i) {2762Record *it, *next;2763for (it = loads[i]; it; it = next) {2764next = it->next;2765recordPool.release(it);2766}2767loads[i] = NULL;2768for (it = stores[i]; it; it = next) {2769next = it->next;2770recordPool.release(it);2771}2772stores[i] = NULL;2773}2774}27752776bool2777MemoryOpt::combineLd(Record *rec, Instruction *ld)2778{2779int32_t offRc = rec->offset;2780int32_t offLd = ld->getSrc(0)->reg.data.offset;2781int sizeRc = rec->size;2782int sizeLd = typeSizeof(ld->dType);2783int size = sizeRc + sizeLd;2784int d, j;27852786if (!prog->getTarget()->2787isAccessSupported(ld->getSrc(0)->reg.file, typeOfSize(size)))2788return false;2789// no unaligned loads2790if (((size == 0x8) && (MIN2(offLd, offRc) & 0x7)) ||2791((size == 0xc) && (MIN2(offLd, offRc) & 0xf)))2792return false;2793// for compute indirect loads are not guaranteed to be aligned2794if (prog->getType() == Program::TYPE_COMPUTE && rec->rel[0])2795return false;27962797assert(sizeRc + sizeLd <= 16 && offRc != offLd);27982799// lock any stores that overlap with the load being merged into the2800// existing record.2801lockStores(ld);28022803for (j = 0; sizeRc; sizeRc -= rec->insn->getDef(j)->reg.size, ++j);28042805if (offLd < offRc) {2806int sz;2807for (sz = 0, d = 0; sz < sizeLd; sz += ld->getDef(d)->reg.size, ++d);2808// d: nr of definitions in ld2809// j: nr of definitions in rec->insn, move:2810for (d = d + j - 1; j > 0; --j, --d)2811rec->insn->setDef(d, rec->insn->getDef(j - 1));28122813if (rec->insn->getSrc(0)->refCount() > 1)2814rec->insn->setSrc(0, cloneShallow(func, rec->insn->getSrc(0)));2815rec->offset = rec->insn->getSrc(0)->reg.data.offset = offLd;28162817d = 0;2818} else {2819d = j;2820}2821// move definitions of @ld to @rec->insn2822for (j = 0; sizeLd; ++j, ++d) {2823sizeLd -= ld->getDef(j)->reg.size;2824rec->insn->setDef(d, ld->getDef(j));2825}28262827rec->size = size;2828rec->insn->getSrc(0)->reg.size = size;2829rec->insn->setType(typeOfSize(size));28302831delete_Instruction(prog, ld);28322833return true;2834}28352836bool2837MemoryOpt::combineSt(Record *rec, Instruction *st)2838{2839int32_t offRc = rec->offset;2840int32_t offSt = st->getSrc(0)->reg.data.offset;2841int sizeRc = rec->size;2842int sizeSt = typeSizeof(st->dType);2843int s = sizeSt / 4;2844int size = sizeRc + sizeSt;2845int j, k;2846Value *src[4]; // no modifiers in ValueRef allowed for st2847Value *extra[3];28482849if (!prog->getTarget()->2850isAccessSupported(st->getSrc(0)->reg.file, typeOfSize(size)))2851return false;2852// no unaligned stores2853if (size == 8 && MIN2(offRc, offSt) & 0x7)2854return false;2855// for compute indirect stores are not guaranteed to be aligned2856if (prog->getType() == Program::TYPE_COMPUTE && rec->rel[0])2857return false;28582859// There's really no great place to put this in a generic manner. Seemingly2860// wide stores at 0x60 don't work in GS shaders on SM50+. Don't combine2861// those.2862if (prog->getTarget()->getChipset() >= NVISA_GM107_CHIPSET &&2863prog->getType() == Program::TYPE_GEOMETRY &&2864st->getSrc(0)->reg.file == FILE_SHADER_OUTPUT &&2865rec->rel[0] == NULL &&2866MIN2(offRc, offSt) == 0x60)2867return false;28682869// remove any existing load/store records for the store being merged into2870// the existing record.2871purgeRecords(st, DATA_FILE_COUNT);28722873st->takeExtraSources(0, extra); // save predicate and indirect address28742875if (offRc < offSt) {2876// save values from @st2877for (s = 0; sizeSt; ++s) {2878sizeSt -= st->getSrc(s + 1)->reg.size;2879src[s] = st->getSrc(s + 1);2880}2881// set record's values as low sources of @st2882for (j = 1; sizeRc; ++j) {2883sizeRc -= rec->insn->getSrc(j)->reg.size;2884st->setSrc(j, rec->insn->getSrc(j));2885}2886// set saved values as high sources of @st2887for (k = j, j = 0; j < s; ++j)2888st->setSrc(k++, src[j]);28892890updateLdStOffset(st, offRc, func);2891} else {2892for (j = 1; sizeSt; ++j)2893sizeSt -= st->getSrc(j)->reg.size;2894for (s = 1; sizeRc; ++j, ++s) {2895sizeRc -= rec->insn->getSrc(s)->reg.size;2896st->setSrc(j, rec->insn->getSrc(s));2897}2898rec->offset = offSt;2899}2900st->putExtraSources(0, extra); // restore pointer and predicate29012902delete_Instruction(prog, rec->insn);2903rec->insn = st;2904rec->size = size;2905rec->insn->getSrc(0)->reg.size = size;2906rec->insn->setType(typeOfSize(size));2907return true;2908}29092910void2911MemoryOpt::Record::set(const Instruction *ldst)2912{2913const Symbol *mem = ldst->getSrc(0)->asSym();2914fileIndex = mem->reg.fileIndex;2915rel[0] = ldst->getIndirect(0, 0);2916rel[1] = ldst->getIndirect(0, 1);2917offset = mem->reg.data.offset;2918base = mem->getBase();2919size = typeSizeof(ldst->sType);2920}29212922void2923MemoryOpt::Record::link(Record **list)2924{2925next = *list;2926if (next)2927next->prev = this;2928prev = NULL;2929*list = this;2930}29312932void2933MemoryOpt::Record::unlink(Record **list)2934{2935if (next)2936next->prev = prev;2937if (prev)2938prev->next = next;2939else2940*list = next;2941}29422943MemoryOpt::Record **2944MemoryOpt::getList(const Instruction *insn)2945{2946if (insn->op == OP_LOAD || insn->op == OP_VFETCH)2947return &loads[insn->src(0).getFile()];2948return &stores[insn->src(0).getFile()];2949}29502951void2952MemoryOpt::addRecord(Instruction *i)2953{2954Record **list = getList(i);2955Record *it = reinterpret_cast<Record *>(recordPool.allocate());29562957it->link(list);2958it->set(i);2959it->insn = i;2960it->locked = false;2961}29622963MemoryOpt::Record *2964MemoryOpt::findRecord(const Instruction *insn, bool load, bool& isAdj) const2965{2966const Symbol *sym = insn->getSrc(0)->asSym();2967const int size = typeSizeof(insn->sType);2968Record *rec = NULL;2969Record *it = load ? loads[sym->reg.file] : stores[sym->reg.file];29702971for (; it; it = it->next) {2972if (it->locked && insn->op != OP_LOAD && insn->op != OP_VFETCH)2973continue;2974if ((it->offset >> 4) != (sym->reg.data.offset >> 4) ||2975it->rel[0] != insn->getIndirect(0, 0) ||2976it->fileIndex != sym->reg.fileIndex ||2977it->rel[1] != insn->getIndirect(0, 1))2978continue;29792980if (it->offset < sym->reg.data.offset) {2981if (it->offset + it->size >= sym->reg.data.offset) {2982isAdj = (it->offset + it->size == sym->reg.data.offset);2983if (!isAdj)2984return it;2985if (!(it->offset & 0x7))2986rec = it;2987}2988} else {2989isAdj = it->offset != sym->reg.data.offset;2990if (size <= it->size && !isAdj)2991return it;2992else2993if (!(sym->reg.data.offset & 0x7))2994if (it->offset - size <= sym->reg.data.offset)2995rec = it;2996}2997}2998return rec;2999}30003001bool3002MemoryOpt::replaceLdFromSt(Instruction *ld, Record *rec)3003{3004Instruction *st = rec->insn;3005int32_t offSt = rec->offset;3006int32_t offLd = ld->getSrc(0)->reg.data.offset;3007int d, s;30083009for (s = 1; offSt != offLd && st->srcExists(s); ++s)3010offSt += st->getSrc(s)->reg.size;3011if (offSt != offLd)3012return false;30133014for (d = 0; ld->defExists(d) && st->srcExists(s); ++d, ++s) {3015if (ld->getDef(d)->reg.size != st->getSrc(s)->reg.size)3016return false;3017if (st->getSrc(s)->reg.file != FILE_GPR)3018return false;3019ld->def(d).replace(st->src(s), false);3020}3021ld->bb->remove(ld);3022return true;3023}30243025bool3026MemoryOpt::replaceLdFromLd(Instruction *ldE, Record *rec)3027{3028Instruction *ldR = rec->insn;3029int32_t offR = rec->offset;3030int32_t offE = ldE->getSrc(0)->reg.data.offset;3031int dR, dE;30323033assert(offR <= offE);3034for (dR = 0; offR < offE && ldR->defExists(dR); ++dR)3035offR += ldR->getDef(dR)->reg.size;3036if (offR != offE)3037return false;30383039for (dE = 0; ldE->defExists(dE) && ldR->defExists(dR); ++dE, ++dR) {3040if (ldE->getDef(dE)->reg.size != ldR->getDef(dR)->reg.size)3041return false;3042ldE->def(dE).replace(ldR->getDef(dR), false);3043}30443045delete_Instruction(prog, ldE);3046return true;3047}30483049bool3050MemoryOpt::replaceStFromSt(Instruction *restrict st, Record *rec)3051{3052const Instruction *const ri = rec->insn;3053Value *extra[3];30543055int32_t offS = st->getSrc(0)->reg.data.offset;3056int32_t offR = rec->offset;3057int32_t endS = offS + typeSizeof(st->dType);3058int32_t endR = offR + typeSizeof(ri->dType);30593060rec->size = MAX2(endS, endR) - MIN2(offS, offR);30613062st->takeExtraSources(0, extra);30633064if (offR < offS) {3065Value *vals[10];3066int s, n;3067int k = 0;3068// get non-replaced sources of ri3069for (s = 1; offR < offS; offR += ri->getSrc(s)->reg.size, ++s)3070vals[k++] = ri->getSrc(s);3071n = s;3072// get replaced sources of st3073for (s = 1; st->srcExists(s); offS += st->getSrc(s)->reg.size, ++s)3074vals[k++] = st->getSrc(s);3075// skip replaced sources of ri3076for (s = n; offR < endS; offR += ri->getSrc(s)->reg.size, ++s);3077// get non-replaced sources after values covered by st3078for (; offR < endR; offR += ri->getSrc(s)->reg.size, ++s)3079vals[k++] = ri->getSrc(s);3080assert((unsigned int)k <= ARRAY_SIZE(vals));3081for (s = 0; s < k; ++s)3082st->setSrc(s + 1, vals[s]);3083st->setSrc(0, ri->getSrc(0));3084} else3085if (endR > endS) {3086int j, s;3087for (j = 1; offR < endS; offR += ri->getSrc(j++)->reg.size);3088for (s = 1; offS < endS; offS += st->getSrc(s++)->reg.size);3089for (; offR < endR; offR += ri->getSrc(j++)->reg.size)3090st->setSrc(s++, ri->getSrc(j));3091}3092st->putExtraSources(0, extra);30933094delete_Instruction(prog, rec->insn);30953096rec->insn = st;3097rec->offset = st->getSrc(0)->reg.data.offset;30983099st->setType(typeOfSize(rec->size));31003101return true;3102}31033104bool3105MemoryOpt::Record::overlaps(const Instruction *ldst) const3106{3107Record that;3108that.set(ldst);31093110// This assumes that images/buffers can't overlap. They can.3111// TODO: Plumb the restrict logic through, and only skip when it's a3112// restrict situation, or there can implicitly be no writes.3113if (this->fileIndex != that.fileIndex && this->rel[1] == that.rel[1])3114return false;31153116if (this->rel[0] || that.rel[0])3117return this->base == that.base;31183119return3120(this->offset < that.offset + that.size) &&3121(this->offset + this->size > that.offset);3122}31233124// We must not eliminate stores that affect the result of @ld if3125// we find later stores to the same location, and we may no longer3126// merge them with later stores.3127// The stored value can, however, still be used to determine the value3128// returned by future loads.3129void3130MemoryOpt::lockStores(Instruction *const ld)3131{3132for (Record *r = stores[ld->src(0).getFile()]; r; r = r->next)3133if (!r->locked && r->overlaps(ld))3134r->locked = true;3135}31363137// Prior loads from the location of @st are no longer valid.3138// Stores to the location of @st may no longer be used to derive3139// the value at it nor be coalesced into later stores.3140void3141MemoryOpt::purgeRecords(Instruction *const st, DataFile f)3142{3143if (st)3144f = st->src(0).getFile();31453146for (Record *r = loads[f]; r; r = r->next)3147if (!st || r->overlaps(st))3148r->unlink(&loads[f]);31493150for (Record *r = stores[f]; r; r = r->next)3151if (!st || r->overlaps(st))3152r->unlink(&stores[f]);3153}31543155bool3156MemoryOpt::visit(BasicBlock *bb)3157{3158bool ret = runOpt(bb);3159// Run again, one pass won't combine 4 32 bit ld/st to a single 128 bit ld/st3160// where 96 bit memory operations are forbidden.3161if (ret)3162ret = runOpt(bb);3163return ret;3164}31653166bool3167MemoryOpt::runOpt(BasicBlock *bb)3168{3169Instruction *ldst, *next;3170Record *rec;3171bool isAdjacent = true;31723173for (ldst = bb->getEntry(); ldst; ldst = next) {3174bool keep = true;3175bool isLoad = true;3176next = ldst->next;31773178if (ldst->op == OP_LOAD || ldst->op == OP_VFETCH) {3179if (ldst->subOp == NV50_IR_SUBOP_LOAD_LOCKED) {3180purgeRecords(ldst, ldst->src(0).getFile());3181continue;3182}3183if (ldst->isDead()) {3184// might have been produced by earlier optimization3185delete_Instruction(prog, ldst);3186continue;3187}3188} else3189if (ldst->op == OP_STORE || ldst->op == OP_EXPORT) {3190if (ldst->subOp == NV50_IR_SUBOP_STORE_UNLOCKED) {3191purgeRecords(ldst, ldst->src(0).getFile());3192continue;3193}3194if (typeSizeof(ldst->dType) == 4 &&3195ldst->src(1).getFile() == FILE_GPR &&3196ldst->getSrc(1)->getInsn()->op == OP_NOP) {3197delete_Instruction(prog, ldst);3198continue;3199}3200isLoad = false;3201} else {3202// TODO: maybe have all fixed ops act as barrier ?3203if (ldst->op == OP_CALL ||3204ldst->op == OP_BAR ||3205ldst->op == OP_MEMBAR) {3206purgeRecords(NULL, FILE_MEMORY_LOCAL);3207purgeRecords(NULL, FILE_MEMORY_GLOBAL);3208purgeRecords(NULL, FILE_MEMORY_SHARED);3209purgeRecords(NULL, FILE_SHADER_OUTPUT);3210} else3211if (ldst->op == OP_ATOM || ldst->op == OP_CCTL) {3212if (ldst->src(0).getFile() == FILE_MEMORY_GLOBAL) {3213purgeRecords(NULL, FILE_MEMORY_LOCAL);3214purgeRecords(NULL, FILE_MEMORY_GLOBAL);3215purgeRecords(NULL, FILE_MEMORY_SHARED);3216} else {3217purgeRecords(NULL, ldst->src(0).getFile());3218}3219} else3220if (ldst->op == OP_EMIT || ldst->op == OP_RESTART) {3221purgeRecords(NULL, FILE_SHADER_OUTPUT);3222}3223continue;3224}3225if (ldst->getPredicate()) // TODO: handle predicated ld/st3226continue;3227if (ldst->perPatch) // TODO: create separate per-patch lists3228continue;32293230if (isLoad) {3231DataFile file = ldst->src(0).getFile();32323233// if ld l[]/g[] look for previous store to eliminate the reload3234if (file == FILE_MEMORY_GLOBAL || file == FILE_MEMORY_LOCAL) {3235// TODO: shared memory ?3236rec = findRecord(ldst, false, isAdjacent);3237if (rec && !isAdjacent)3238keep = !replaceLdFromSt(ldst, rec);3239}32403241// or look for ld from the same location and replace this one3242rec = keep ? findRecord(ldst, true, isAdjacent) : NULL;3243if (rec) {3244if (!isAdjacent)3245keep = !replaceLdFromLd(ldst, rec);3246else3247// or combine a previous load with this one3248keep = !combineLd(rec, ldst);3249}3250if (keep)3251lockStores(ldst);3252} else {3253rec = findRecord(ldst, false, isAdjacent);3254if (rec) {3255if (!isAdjacent)3256keep = !replaceStFromSt(ldst, rec);3257else3258keep = !combineSt(rec, ldst);3259}3260if (keep)3261purgeRecords(ldst, DATA_FILE_COUNT);3262}3263if (keep)3264addRecord(ldst);3265}3266reset();32673268return true;3269}32703271// =============================================================================32723273// Turn control flow into predicated instructions (after register allocation !).3274// TODO:3275// Could move this to before register allocation on NVC0 and also handle nested3276// constructs.3277class FlatteningPass : public Pass3278{3279private:3280virtual bool visit(Function *);3281virtual bool visit(BasicBlock *);32823283bool tryPredicateConditional(BasicBlock *);3284void predicateInstructions(BasicBlock *, Value *pred, CondCode cc);3285void tryPropagateBranch(BasicBlock *);3286inline bool isConstantCondition(Value *pred);3287inline bool mayPredicate(const Instruction *, const Value *pred) const;3288inline void removeFlow(Instruction *);32893290uint8_t gpr_unit;3291};32923293bool3294FlatteningPass::isConstantCondition(Value *pred)3295{3296Instruction *insn = pred->getUniqueInsn();3297assert(insn);3298if (insn->op != OP_SET || insn->srcExists(2))3299return false;33003301for (int s = 0; s < 2 && insn->srcExists(s); ++s) {3302Instruction *ld = insn->getSrc(s)->getUniqueInsn();3303DataFile file;3304if (ld) {3305if (ld->op != OP_MOV && ld->op != OP_LOAD)3306return false;3307if (ld->src(0).isIndirect(0))3308return false;3309file = ld->src(0).getFile();3310} else {3311file = insn->src(s).getFile();3312// catch $r63 on NVC0 and $r63/$r127 on NV50. Unfortunately maxGPR is3313// in register "units", which can vary between targets.3314if (file == FILE_GPR) {3315Value *v = insn->getSrc(s);3316int bytes = v->reg.data.id * MIN2(v->reg.size, 4);3317int units = bytes >> gpr_unit;3318if (units > prog->maxGPR)3319file = FILE_IMMEDIATE;3320}3321}3322if (file != FILE_IMMEDIATE && file != FILE_MEMORY_CONST)3323return false;3324}3325return true;3326}33273328void3329FlatteningPass::removeFlow(Instruction *insn)3330{3331FlowInstruction *term = insn ? insn->asFlow() : NULL;3332if (!term)3333return;3334Graph::Edge::Type ty = term->bb->cfg.outgoing().getType();33353336if (term->op == OP_BRA) {3337// TODO: this might get more difficult when we get arbitrary BRAs3338if (ty == Graph::Edge::CROSS || ty == Graph::Edge::BACK)3339return;3340} else3341if (term->op != OP_JOIN)3342return;33433344Value *pred = term->getPredicate();33453346delete_Instruction(prog, term);33473348if (pred && pred->refCount() == 0) {3349Instruction *pSet = pred->getUniqueInsn();3350pred->join->reg.data.id = -1; // deallocate3351if (pSet->isDead())3352delete_Instruction(prog, pSet);3353}3354}33553356void3357FlatteningPass::predicateInstructions(BasicBlock *bb, Value *pred, CondCode cc)3358{3359for (Instruction *i = bb->getEntry(); i; i = i->next) {3360if (i->isNop())3361continue;3362assert(!i->getPredicate());3363i->setPredicate(cc, pred);3364}3365removeFlow(bb->getExit());3366}33673368bool3369FlatteningPass::mayPredicate(const Instruction *insn, const Value *pred) const3370{3371if (insn->isPseudo())3372return true;3373// TODO: calls where we don't know which registers are modified33743375if (!prog->getTarget()->mayPredicate(insn, pred))3376return false;3377for (int d = 0; insn->defExists(d); ++d)3378if (insn->getDef(d)->equals(pred))3379return false;3380return true;3381}33823383// If we jump to BRA/RET/EXIT, replace the jump with it.3384// NOTE: We do not update the CFG anymore here !3385//3386// TODO: Handle cases where we skip over a branch (maybe do that elsewhere ?):3387// BB:03388// @p0 bra BB:2 -> @!p0 bra BB:3 iff (!) BB:2 immediately adjoins BB:13389// BB1:3390// bra BB:33391// BB2:3392// ...3393// BB3:3394// ...3395void3396FlatteningPass::tryPropagateBranch(BasicBlock *bb)3397{3398for (Instruction *i = bb->getExit(); i && i->op == OP_BRA; i = i->prev) {3399BasicBlock *bf = i->asFlow()->target.bb;34003401if (bf->getInsnCount() != 1)3402continue;34033404FlowInstruction *bra = i->asFlow();3405FlowInstruction *rep = bf->getExit()->asFlow();34063407if (!rep || rep->getPredicate())3408continue;3409if (rep->op != OP_BRA &&3410rep->op != OP_JOIN &&3411rep->op != OP_EXIT)3412continue;34133414// TODO: If there are multiple branches to @rep, only the first would3415// be replaced, so only remove them after this pass is done ?3416// Also, need to check all incident blocks for fall-through exits and3417// add the branch there.3418bra->op = rep->op;3419bra->target.bb = rep->target.bb;3420if (bf->cfg.incidentCount() == 1)3421bf->remove(rep);3422}3423}34243425bool3426FlatteningPass::visit(Function *fn)3427{3428gpr_unit = prog->getTarget()->getFileUnit(FILE_GPR);34293430return true;3431}34323433bool3434FlatteningPass::visit(BasicBlock *bb)3435{3436if (tryPredicateConditional(bb))3437return true;34383439// try to attach join to previous instruction3440if (prog->getTarget()->hasJoin) {3441Instruction *insn = bb->getExit();3442if (insn && insn->op == OP_JOIN && !insn->getPredicate()) {3443insn = insn->prev;3444if (insn && !insn->getPredicate() &&3445!insn->asFlow() &&3446insn->op != OP_DISCARD &&3447insn->op != OP_TEXBAR &&3448!isTextureOp(insn->op) && // probably just nve43449!isSurfaceOp(insn->op) && // not confirmed3450insn->op != OP_LINTERP && // probably just nve43451insn->op != OP_PINTERP && // probably just nve43452((insn->op != OP_LOAD && insn->op != OP_STORE && insn->op != OP_ATOM) ||3453(typeSizeof(insn->dType) <= 4 && !insn->src(0).isIndirect(0))) &&3454!insn->isNop()) {3455insn->join = 1;3456bb->remove(bb->getExit());3457return true;3458}3459}3460}34613462tryPropagateBranch(bb);34633464return true;3465}34663467bool3468FlatteningPass::tryPredicateConditional(BasicBlock *bb)3469{3470BasicBlock *bL = NULL, *bR = NULL;3471unsigned int nL = 0, nR = 0, limit = 12;3472Instruction *insn;3473unsigned int mask;34743475mask = bb->initiatesSimpleConditional();3476if (!mask)3477return false;34783479assert(bb->getExit());3480Value *pred = bb->getExit()->getPredicate();3481assert(pred);34823483if (isConstantCondition(pred))3484limit = 4;34853486Graph::EdgeIterator ei = bb->cfg.outgoing();34873488if (mask & 1) {3489bL = BasicBlock::get(ei.getNode());3490for (insn = bL->getEntry(); insn; insn = insn->next, ++nL)3491if (!mayPredicate(insn, pred))3492return false;3493if (nL > limit)3494return false; // too long, do a real branch3495}3496ei.next();34973498if (mask & 2) {3499bR = BasicBlock::get(ei.getNode());3500for (insn = bR->getEntry(); insn; insn = insn->next, ++nR)3501if (!mayPredicate(insn, pred))3502return false;3503if (nR > limit)3504return false; // too long, do a real branch3505}35063507if (bL)3508predicateInstructions(bL, pred, bb->getExit()->cc);3509if (bR)3510predicateInstructions(bR, pred, inverseCondCode(bb->getExit()->cc));35113512if (bb->joinAt) {3513bb->remove(bb->joinAt);3514bb->joinAt = NULL;3515}3516removeFlow(bb->getExit()); // delete the branch/join at the fork point35173518// remove potential join operations at the end of the conditional3519if (prog->getTarget()->joinAnterior) {3520bb = BasicBlock::get((bL ? bL : bR)->cfg.outgoing().getNode());3521if (bb->getEntry() && bb->getEntry()->op == OP_JOIN)3522removeFlow(bb->getEntry());3523}35243525return true;3526}35273528// =============================================================================35293530// Fold Immediate into MAD; must be done after register allocation due to3531// constraint SDST == SSRC23532// TODO:3533// Does NVC0+ have other situations where this pass makes sense?3534class PostRaLoadPropagation : public Pass3535{3536private:3537virtual bool visit(Instruction *);35383539void handleMADforNV50(Instruction *);3540void handleMADforNVC0(Instruction *);3541};35423543static bool3544post_ra_dead(Instruction *i)3545{3546for (int d = 0; i->defExists(d); ++d)3547if (i->getDef(d)->refCount())3548return false;3549return true;3550}35513552// Fold Immediate into MAD; must be done after register allocation due to3553// constraint SDST == SSRC23554void3555PostRaLoadPropagation::handleMADforNV50(Instruction *i)3556{3557if (i->def(0).getFile() != FILE_GPR ||3558i->src(0).getFile() != FILE_GPR ||3559i->src(1).getFile() != FILE_GPR ||3560i->src(2).getFile() != FILE_GPR ||3561i->getDef(0)->reg.data.id != i->getSrc(2)->reg.data.id)3562return;35633564if (i->getDef(0)->reg.data.id >= 64 ||3565i->getSrc(0)->reg.data.id >= 64)3566return;35673568if (i->flagsSrc >= 0 && i->getSrc(i->flagsSrc)->reg.data.id != 0)3569return;35703571if (i->getPredicate())3572return;35733574Value *vtmp;3575Instruction *def = i->getSrc(1)->getInsn();35763577if (def && def->op == OP_SPLIT && typeSizeof(def->sType) == 4)3578def = def->getSrc(0)->getInsn();3579if (def && def->op == OP_MOV && def->src(0).getFile() == FILE_IMMEDIATE) {3580vtmp = i->getSrc(1);3581if (isFloatType(i->sType)) {3582i->setSrc(1, def->getSrc(0));3583} else {3584ImmediateValue val;3585// getImmediate() has side-effects on the argument so this *shouldn't*3586// be folded into the assert()3587ASSERTED bool ret = def->src(0).getImmediate(val);3588assert(ret);3589if (i->getSrc(1)->reg.data.id & 1)3590val.reg.data.u32 >>= 16;3591val.reg.data.u32 &= 0xffff;3592i->setSrc(1, new_ImmediateValue(prog, val.reg.data.u32));3593}35943595/* There's no post-RA dead code elimination, so do it here3596* XXX: if we add more code-removing post-RA passes, we might3597* want to create a post-RA dead-code elim pass */3598if (post_ra_dead(vtmp->getInsn())) {3599Value *src = vtmp->getInsn()->getSrc(0);3600// Careful -- splits will have already been removed from the3601// functions. Don't double-delete.3602if (vtmp->getInsn()->bb)3603delete_Instruction(prog, vtmp->getInsn());3604if (src->getInsn() && post_ra_dead(src->getInsn()))3605delete_Instruction(prog, src->getInsn());3606}3607}3608}36093610void3611PostRaLoadPropagation::handleMADforNVC0(Instruction *i)3612{3613if (i->def(0).getFile() != FILE_GPR ||3614i->src(0).getFile() != FILE_GPR ||3615i->src(1).getFile() != FILE_GPR ||3616i->src(2).getFile() != FILE_GPR ||3617i->getDef(0)->reg.data.id != i->getSrc(2)->reg.data.id)3618return;36193620// TODO: gm107 can also do this for S32, maybe other chipsets as well3621if (i->dType != TYPE_F32)3622return;36233624if ((i->src(2).mod | Modifier(NV50_IR_MOD_NEG)) != Modifier(NV50_IR_MOD_NEG))3625return;36263627ImmediateValue val;3628int s;36293630if (i->src(0).getImmediate(val))3631s = 1;3632else if (i->src(1).getImmediate(val))3633s = 0;3634else3635return;36363637if ((i->src(s).mod | Modifier(NV50_IR_MOD_NEG)) != Modifier(NV50_IR_MOD_NEG))3638return;36393640if (s == 1)3641i->swapSources(0, 1);36423643Instruction *imm = i->getSrc(1)->getInsn();3644i->setSrc(1, imm->getSrc(0));3645if (post_ra_dead(imm))3646delete_Instruction(prog, imm);3647}36483649bool3650PostRaLoadPropagation::visit(Instruction *i)3651{3652switch (i->op) {3653case OP_FMA:3654case OP_MAD:3655if (prog->getTarget()->getChipset() < 0xc0)3656handleMADforNV50(i);3657else3658handleMADforNVC0(i);3659break;3660default:3661break;3662}36633664return true;3665}36663667// =============================================================================36683669// Common subexpression elimination. Stupid O^2 implementation.3670class LocalCSE : public Pass3671{3672private:3673virtual bool visit(BasicBlock *);36743675inline bool tryReplace(Instruction **, Instruction *);36763677DLList ops[OP_LAST + 1];3678};36793680class GlobalCSE : public Pass3681{3682private:3683virtual bool visit(BasicBlock *);3684};36853686bool3687Instruction::isActionEqual(const Instruction *that) const3688{3689if (this->op != that->op ||3690this->dType != that->dType ||3691this->sType != that->sType)3692return false;3693if (this->cc != that->cc)3694return false;36953696if (this->asTex()) {3697if (memcmp(&this->asTex()->tex,3698&that->asTex()->tex,3699sizeof(this->asTex()->tex)))3700return false;3701} else3702if (this->asCmp()) {3703if (this->asCmp()->setCond != that->asCmp()->setCond)3704return false;3705} else3706if (this->asFlow()) {3707return false;3708} else3709if (this->op == OP_PHI && this->bb != that->bb) {3710/* TODO: we could probably be a bit smarter here by following the3711* control flow, but honestly, it is quite painful to check */3712return false;3713} else {3714if (this->ipa != that->ipa ||3715this->lanes != that->lanes ||3716this->perPatch != that->perPatch)3717return false;3718if (this->postFactor != that->postFactor)3719return false;3720}37213722if (this->subOp != that->subOp ||3723this->saturate != that->saturate ||3724this->rnd != that->rnd ||3725this->ftz != that->ftz ||3726this->dnz != that->dnz ||3727this->cache != that->cache ||3728this->mask != that->mask)3729return false;37303731return true;3732}37333734bool3735Instruction::isResultEqual(const Instruction *that) const3736{3737unsigned int d, s;37383739// NOTE: location of discard only affects tex with liveOnly and quadops3740if (!this->defExists(0) && this->op != OP_DISCARD)3741return false;37423743if (!isActionEqual(that))3744return false;37453746if (this->predSrc != that->predSrc)3747return false;37483749for (d = 0; this->defExists(d); ++d) {3750if (!that->defExists(d) ||3751!this->getDef(d)->equals(that->getDef(d), false))3752return false;3753}3754if (that->defExists(d))3755return false;37563757for (s = 0; this->srcExists(s); ++s) {3758if (!that->srcExists(s))3759return false;3760if (this->src(s).mod != that->src(s).mod)3761return false;3762if (!this->getSrc(s)->equals(that->getSrc(s), true))3763return false;3764}3765if (that->srcExists(s))3766return false;37673768if (op == OP_LOAD || op == OP_VFETCH || op == OP_ATOM) {3769switch (src(0).getFile()) {3770case FILE_MEMORY_CONST:3771case FILE_SHADER_INPUT:3772return true;3773case FILE_SHADER_OUTPUT:3774return bb->getProgram()->getType() == Program::TYPE_TESSELLATION_EVAL;3775default:3776return false;3777}3778}37793780return true;3781}37823783// pull through common expressions from different in-blocks3784bool3785GlobalCSE::visit(BasicBlock *bb)3786{3787Instruction *phi, *next, *ik;3788int s;37893790// TODO: maybe do this with OP_UNION, too37913792for (phi = bb->getPhi(); phi && phi->op == OP_PHI; phi = next) {3793next = phi->next;3794if (phi->getSrc(0)->refCount() > 1)3795continue;3796ik = phi->getSrc(0)->getInsn();3797if (!ik)3798continue; // probably a function input3799if (ik->defCount(0xff) > 1)3800continue; // too painful to check if we can really push this forward3801for (s = 1; phi->srcExists(s); ++s) {3802if (phi->getSrc(s)->refCount() > 1)3803break;3804if (!phi->getSrc(s)->getInsn() ||3805!phi->getSrc(s)->getInsn()->isResultEqual(ik))3806break;3807}3808if (!phi->srcExists(s)) {3809assert(ik->op != OP_PHI);3810Instruction *entry = bb->getEntry();3811ik->bb->remove(ik);3812if (!entry || entry->op != OP_JOIN)3813bb->insertHead(ik);3814else3815bb->insertAfter(entry, ik);3816ik->setDef(0, phi->getDef(0));3817delete_Instruction(prog, phi);3818}3819}38203821return true;3822}38233824bool3825LocalCSE::tryReplace(Instruction **ptr, Instruction *i)3826{3827Instruction *old = *ptr;38283829// TODO: maybe relax this later (causes trouble with OP_UNION)3830if (i->isPredicated())3831return false;38323833if (!old->isResultEqual(i))3834return false;38353836for (int d = 0; old->defExists(d); ++d)3837old->def(d).replace(i->getDef(d), false);3838delete_Instruction(prog, old);3839*ptr = NULL;3840return true;3841}38423843bool3844LocalCSE::visit(BasicBlock *bb)3845{3846unsigned int replaced;38473848do {3849Instruction *ir, *next;38503851replaced = 0;38523853// will need to know the order of instructions3854int serial = 0;3855for (ir = bb->getFirst(); ir; ir = ir->next)3856ir->serial = serial++;38573858for (ir = bb->getFirst(); ir; ir = next) {3859int s;3860Value *src = NULL;38613862next = ir->next;38633864if (ir->fixed) {3865ops[ir->op].insert(ir);3866continue;3867}38683869for (s = 0; ir->srcExists(s); ++s)3870if (ir->getSrc(s)->asLValue())3871if (!src || ir->getSrc(s)->refCount() < src->refCount())3872src = ir->getSrc(s);38733874if (src) {3875for (Value::UseIterator it = src->uses.begin();3876it != src->uses.end(); ++it) {3877Instruction *ik = (*it)->getInsn();3878if (ik && ik->bb == ir->bb && ik->serial < ir->serial)3879if (tryReplace(&ir, ik))3880break;3881}3882} else {3883DLLIST_FOR_EACH(&ops[ir->op], iter)3884{3885Instruction *ik = reinterpret_cast<Instruction *>(iter.get());3886if (tryReplace(&ir, ik))3887break;3888}3889}38903891if (ir)3892ops[ir->op].insert(ir);3893else3894++replaced;3895}3896for (unsigned int i = 0; i <= OP_LAST; ++i)3897ops[i].clear();38983899} while (replaced);39003901return true;3902}39033904// =============================================================================39053906// Remove computations of unused values.3907class DeadCodeElim : public Pass3908{3909public:3910bool buryAll(Program *);39113912private:3913virtual bool visit(BasicBlock *);39143915void checkSplitLoad(Instruction *ld); // for partially dead loads39163917unsigned int deadCount;3918};39193920bool3921DeadCodeElim::buryAll(Program *prog)3922{3923do {3924deadCount = 0;3925if (!this->run(prog, false, false))3926return false;3927} while (deadCount);39283929return true;3930}39313932bool3933DeadCodeElim::visit(BasicBlock *bb)3934{3935Instruction *prev;39363937for (Instruction *i = bb->getExit(); i; i = prev) {3938prev = i->prev;3939if (i->isDead()) {3940++deadCount;3941delete_Instruction(prog, i);3942} else3943if (i->defExists(1) &&3944i->subOp == 0 &&3945(i->op == OP_VFETCH || i->op == OP_LOAD)) {3946checkSplitLoad(i);3947} else3948if (i->defExists(0) && !i->getDef(0)->refCount()) {3949if (i->op == OP_ATOM ||3950i->op == OP_SUREDP ||3951i->op == OP_SUREDB) {3952const Target *targ = prog->getTarget();3953if (targ->getChipset() >= NVISA_GF100_CHIPSET ||3954i->subOp != NV50_IR_SUBOP_ATOM_CAS)3955i->setDef(0, NULL);3956if (i->op == OP_ATOM && i->subOp == NV50_IR_SUBOP_ATOM_EXCH) {3957i->cache = CACHE_CV;3958i->op = OP_STORE;3959i->subOp = 0;3960}3961} else if (i->op == OP_LOAD && i->subOp == NV50_IR_SUBOP_LOAD_LOCKED) {3962i->setDef(0, i->getDef(1));3963i->setDef(1, NULL);3964}3965}3966}3967return true;3968}39693970// Each load can go into up to 4 destinations, any of which might potentially3971// be dead (i.e. a hole). These can always be split into 2 loads, independent3972// of where the holes are. We find the first contiguous region, put it into3973// the first load, and then put the second contiguous region into the second3974// load. There can be at most 2 contiguous regions.3975//3976// Note that there are some restrictions, for example it's not possible to do3977// a 64-bit load that's not 64-bit aligned, so such a load has to be split3978// up. Also hardware doesn't support 96-bit loads, so those also have to be3979// split into a 64-bit and 32-bit load.3980void3981DeadCodeElim::checkSplitLoad(Instruction *ld1)3982{3983Instruction *ld2 = NULL; // can get at most 2 loads3984Value *def1[4];3985Value *def2[4];3986int32_t addr1, addr2;3987int32_t size1, size2;3988int d, n1, n2;3989uint32_t mask = 0xffffffff;39903991for (d = 0; ld1->defExists(d); ++d)3992if (!ld1->getDef(d)->refCount() && ld1->getDef(d)->reg.data.id < 0)3993mask &= ~(1 << d);3994if (mask == 0xffffffff)3995return;39963997addr1 = ld1->getSrc(0)->reg.data.offset;3998n1 = n2 = 0;3999size1 = size2 = 0;40004001// Compute address/width for first load4002for (d = 0; ld1->defExists(d); ++d) {4003if (mask & (1 << d)) {4004if (size1 && (addr1 & 0x7))4005break;4006def1[n1] = ld1->getDef(d);4007size1 += def1[n1++]->reg.size;4008} else4009if (!n1) {4010addr1 += ld1->getDef(d)->reg.size;4011} else {4012break;4013}4014}40154016// Scale back the size of the first load until it can be loaded. This4017// typically happens for TYPE_B96 loads.4018while (n1 &&4019!prog->getTarget()->isAccessSupported(ld1->getSrc(0)->reg.file,4020typeOfSize(size1))) {4021size1 -= def1[--n1]->reg.size;4022d--;4023}40244025// Compute address/width for second load4026for (addr2 = addr1 + size1; ld1->defExists(d); ++d) {4027if (mask & (1 << d)) {4028assert(!size2 || !(addr2 & 0x7));4029def2[n2] = ld1->getDef(d);4030size2 += def2[n2++]->reg.size;4031} else if (!n2) {4032assert(!n2);4033addr2 += ld1->getDef(d)->reg.size;4034} else {4035break;4036}4037}40384039// Make sure that we've processed all the values4040for (; ld1->defExists(d); ++d)4041assert(!(mask & (1 << d)));40424043updateLdStOffset(ld1, addr1, func);4044ld1->setType(typeOfSize(size1));4045for (d = 0; d < 4; ++d)4046ld1->setDef(d, (d < n1) ? def1[d] : NULL);40474048if (!n2)4049return;40504051ld2 = cloneShallow(func, ld1);4052updateLdStOffset(ld2, addr2, func);4053ld2->setType(typeOfSize(size2));4054for (d = 0; d < 4; ++d)4055ld2->setDef(d, (d < n2) ? def2[d] : NULL);40564057ld1->bb->insertAfter(ld1, ld2);4058}40594060// =============================================================================40614062#define RUN_PASS(l, n, f) \4063if (level >= (l)) { \4064if (dbgFlags & NV50_IR_DEBUG_VERBOSE) \4065INFO("PEEPHOLE: %s\n", #n); \4066n pass; \4067if (!pass.f(this)) \4068return false; \4069}40704071bool4072Program::optimizeSSA(int level)4073{4074RUN_PASS(1, DeadCodeElim, buryAll);4075RUN_PASS(1, CopyPropagation, run);4076RUN_PASS(1, MergeSplits, run);4077RUN_PASS(2, GlobalCSE, run);4078RUN_PASS(1, LocalCSE, run);4079RUN_PASS(2, AlgebraicOpt, run);4080RUN_PASS(2, ModifierFolding, run); // before load propagation -> less checks4081RUN_PASS(1, ConstantFolding, foldAll);4082RUN_PASS(0, Split64BitOpPreRA, run);4083RUN_PASS(2, LateAlgebraicOpt, run);4084RUN_PASS(1, LoadPropagation, run);4085RUN_PASS(1, IndirectPropagation, run);4086RUN_PASS(2, MemoryOpt, run);4087RUN_PASS(2, LocalCSE, run);4088RUN_PASS(0, DeadCodeElim, buryAll);40894090return true;4091}40924093bool4094Program::optimizePostRA(int level)4095{4096RUN_PASS(2, FlatteningPass, run);4097RUN_PASS(2, PostRaLoadPropagation, run);40984099return true;4100}41014102}410341044105