2 * Copyright 2011 Christoph Bumiller
4 * Permission is hereby granted, free of charge, to any person obtaining a
5 * copy of this software and associated documentation files (the "Software"),
6 * to deal in the Software without restriction, including without limitation
7 * the rights to use, copy, modify, merge, publish, distribute, sublicense,
8 * and/or sell copies of the Software, and to permit persons to whom the
9 * Software is furnished to do so, subject to the following conditions:
11 * The above copyright notice and this permission notice shall be included in
12 * all copies or substantial portions of the Software.
14 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
15 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
16 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
17 * THE AUTHORS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
18 * WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF
19 * OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
33 #include "nv50_ir_util.h"
34 #include "nv50_ir_graph.h"
36 #include "nv50_ir_driver.h"
44 OP_UNION
, // unify a new definition and several source values
45 OP_SPLIT
, // $r0d -> { $r0, $r1 } ($r0d and $r0/$r1 will be coalesced)
46 OP_MERGE
, // opposite of split, e.g. combine 2 32 bit into a 64 bit value
47 OP_CONSTRAINT
, // copy values into consecutive registers
48 OP_MOV
, // simple copy, no modifiers allowed
58 OP_SAD
, // abs(src0 - src1) + src2
69 OP_SAT
, // CLAMP(f32, 0.0, 1.0)
74 OP_SET_AND
, // dst = (src0 CMP src1) & src2
78 OP_SELP
, // dst = src2 ? src0 : src1
79 OP_SLCT
, // dst = (src2 CMP 0) ? src0 : src1
86 OP_EXP
, // exponential (base M_E)
87 OP_LOG
, // natural logarithm
100 OP_BRKPT
, // breakpoint (not related to loops)
101 OP_JOINAT
, // push control flow convergence point
106 OP_VFETCH
, // indirection 0 in attribute space, indirection 1 is vertex base
107 OP_PFETCH
, // fetch base address of vertex src0 (immediate) [+ src1]
111 OP_EMIT
, // emit vertex
112 OP_RESTART
, // restart primitive
114 OP_TXB
, // texture bias
115 OP_TXL
, // texure lod
116 OP_TXF
, // texel fetch
117 OP_TXQ
, // texture size query
118 OP_TXD
, // texture derivatives
119 OP_TXG
, // texture gather
121 OP_SULD
, // surface load
122 OP_SUST
, // surface store
125 OP_RDSV
, // read system value
126 OP_WRSV
, // write system value
131 OP_POPCNT
, // bitcount(src0 & src1)
132 OP_INSBF
, // insert first src1[8:15] bits of src0 into src2 at src1[0:7]
137 #define NV50_IR_SUBOP_MUL_HIGH 1
138 #define NV50_IR_SUBOP_EMIT_RESTART 1
139 #define NV50_IR_SUBOP_LDC_IL 1
140 #define NV50_IR_SUBOP_LDC_IS 2
141 #define NV50_IR_SUBOP_LDC_ISL 3
142 #define NV50_IR_SUBOP_SHIFT_WRAP 1
153 TYPE_U64
, // 64 bit operations are only lowered after register allocation
165 CC_NEVER
= CC_FL
, // when used with FILE_FLAGS
168 CC_NOT_P
= CC_EQ
, // when used with FILE_PREDICATE
196 ROUND_M
, // towards -inf
197 ROUND_Z
, // towards 0
198 ROUND_P
, // towards +inf
199 ROUND_NI
, // nearest integer
200 ROUND_MI
, // to integer towards -inf
201 ROUND_ZI
, // to integer towards 0
202 ROUND_PI
, // to integer towards +inf
207 CACHE_CA
, // cache at all levels
208 CACHE_WB
= CACHE_CA
, // cache write back
209 CACHE_CG
, // cache at global level
210 CACHE_CS
, // cache streaming
211 CACHE_CV
, // cache as volatile
212 CACHE_WT
= CACHE_CV
// cache write-through
219 FILE_PREDICATE
, // boolean predicate
220 FILE_FLAGS
, // zero/sign/carry/overflow bits
240 TEX_TARGET_1D_SHADOW
,
241 TEX_TARGET_2D_SHADOW
,
242 TEX_TARGET_CUBE_SHADOW
,
245 TEX_TARGET_2D_MS_ARRAY
,
246 TEX_TARGET_CUBE_ARRAY
,
247 TEX_TARGET_1D_ARRAY_SHADOW
,
248 TEX_TARGET_2D_ARRAY_SHADOW
,
250 TEX_TARGET_RECT_SHADOW
,
251 TEX_TARGET_CUBE_ARRAY_SHADOW
,
263 SV_VERTEX_COUNT
, // gl_PatchVerticesIn
296 class CmpInstruction
;
297 class TexInstruction
;
298 class FlowInstruction
;
303 class ImmediateValue
;
308 int8_t fileIndex
; // signed, may be indirect for CONST[]
309 uint8_t size
; // this should match the Instruction type's size
310 DataType type
; // mainly for pretty printing
312 uint64_t u64
; // immediate values
322 int32_t offset
; // offset from 0 (base of address space)
323 int32_t id
; // register id (< 0 if virtual/unassigned)
331 // precedence: NOT after SAT after NEG after ABS
332 #define NV50_IR_MOD_ABS (1 << 0)
333 #define NV50_IR_MOD_NEG (1 << 1)
334 #define NV50_IR_MOD_SAT (1 << 2)
335 #define NV50_IR_MOD_NOT (1 << 3)
336 #define NV50_IR_MOD_NEG_ABS (NV50_IR_MOD_NEG | NV50_IR_MOD_ABS)
338 #define NV50_IR_INTERP_MODE_MASK 0x3
339 #define NV50_IR_INTERP_LINEAR (0 << 0)
340 #define NV50_IR_INTERP_PERSPECTIVE (1 << 0)
341 #define NV50_IR_INTERP_FLAT (2 << 0)
342 #define NV50_IR_INTERP_SC (3 << 0) // what exactly is that ?
343 #define NV50_IR_INTERP_SAMPLE_MASK 0xc
344 #define NV50_IR_INTERP_DEFAULT (0 << 2)
345 #define NV50_IR_INTERP_CENTROID (1 << 2)
346 #define NV50_IR_INTERP_OFFSET (2 << 2)
347 #define NV50_IR_INTERP_SAMPLEID (3 << 2)
349 // do we really want this to be a class ?
353 Modifier() : bits(0) { }
354 Modifier(unsigned int m
) : bits(m
) { }
355 Modifier(operation op
);
357 // @return new Modifier applying a after b (asserts if unrepresentable)
358 Modifier
operator*(const Modifier
) const;
359 Modifier
operator*=(const Modifier m
) { *this = *this * m
; return *this; }
360 Modifier
operator==(const Modifier m
) const { return m
.bits
== bits
; }
361 Modifier
operator!=(const Modifier m
) const { return m
.bits
!= bits
; }
363 inline Modifier
operator&(const Modifier m
) const { return bits
& m
.bits
; }
364 inline Modifier
operator|(const Modifier m
) const { return bits
| m
.bits
; }
365 inline Modifier
operator^(const Modifier m
) const { return bits
^ m
.bits
; }
367 operation
getOp() const;
369 inline int neg() const { return (bits
& NV50_IR_MOD_NEG
) ? 1 : 0; }
370 inline int abs() const { return (bits
& NV50_IR_MOD_ABS
) ? 1 : 0; }
372 inline operator bool() const { return bits
? true : false; }
374 void applyTo(ImmediateValue
&imm
) const;
376 int print(char *buf
, size_t size
) const;
385 ValueRef(Value
* = NULL
);
386 ValueRef(const ValueRef
&);
389 inline bool exists() const { return value
!= NULL
; }
392 void set(const ValueRef
&);
393 inline Value
*get() const { return value
; }
394 inline Value
*rep() const;
396 inline Instruction
*getInsn() const { return insn
; }
397 inline void setInsn(Instruction
*inst
) { insn
= inst
; }
399 inline bool isIndirect(int dim
) const { return indirect
[dim
] >= 0; }
400 inline const ValueRef
*getIndirect(int dim
) const;
402 inline DataFile
getFile() const;
403 inline unsigned getSize() const;
405 // SSA: return eventual (traverse MOVs) literal value, if it exists
406 bool getImmediate(ImmediateValue
&) const;
410 int8_t indirect
[2]; // >= 0 if relative to lvalue in insn->src(indirect[i])
413 bool usedAsPtr
; // for printing
423 ValueDef(Value
* = NULL
);
424 ValueDef(const ValueDef
&);
427 inline bool exists() const { return value
!= NULL
; }
429 inline Value
*get() const { return value
; }
430 inline Value
*rep() const;
432 bool mayReplace(const ValueRef
&);
433 void replace(const ValueRef
&, bool doSet
); // replace all uses of the old value
435 inline Instruction
*getInsn() const { return insn
; }
436 inline void setInsn(Instruction
*inst
) { insn
= inst
; }
438 inline DataFile
getFile() const;
439 inline unsigned getSize() const;
441 inline void setSSA(LValue
*);
442 inline const LValue
*preSSA() const;
445 Value
*value
; // should make this LValue * ...
446 LValue
*origin
; // pre SSA value
456 virtual Value
*clone(ClonePolicy
<Function
>&) const = 0;
458 virtual int print(char *, size_t, DataType ty
= TYPE_NONE
) const = 0;
460 virtual bool equals(const Value
*, bool strict
= false) const;
461 virtual bool interfers(const Value
*) const;
463 inline Value
*rep() const { return join
; }
465 inline Instruction
*getUniqueInsn() const;
466 inline Instruction
*getInsn() const; // use when uniqueness is certain
468 inline int refCount() { return uses
.size(); }
470 inline LValue
*asLValue();
471 inline Symbol
*asSym();
472 inline ImmediateValue
*asImm();
473 inline const Symbol
*asSym() const;
474 inline const ImmediateValue
*asImm() const;
476 bool coalesce(Value
*, bool force
= false);
478 inline bool inFile(DataFile f
) { return reg
.file
== f
; }
480 static inline Value
*get(Iterator
&);
482 std::list
<ValueRef
*> uses
;
483 std::list
<ValueDef
*> defs
;
484 typedef std::list
<ValueRef
*>::iterator UseIterator
;
485 typedef std::list
<ValueRef
*>::const_iterator UseCIterator
;
486 typedef std::list
<ValueDef
*>::iterator DefIterator
;
487 typedef std::list
<ValueDef
*>::const_iterator DefCIterator
;
492 // TODO: these should be in LValue:
497 class LValue
: public Value
500 LValue(Function
*, DataFile file
);
501 LValue(Function
*, LValue
*);
504 virtual LValue
*clone(ClonePolicy
<Function
>&) const;
506 virtual int print(char *, size_t, DataType ty
= TYPE_NONE
) const;
514 class Symbol
: public Value
517 Symbol(Program
*, DataFile file
= FILE_MEMORY_CONST
, ubyte fileIdx
= 0);
520 virtual Symbol
*clone(ClonePolicy
<Function
>&) const;
522 virtual bool equals(const Value
*that
, bool strict
) const;
524 virtual int print(char *, size_t, DataType ty
= TYPE_NONE
) const;
526 // print with indirect values
527 int print(char *, size_t, Value
*, Value
*, DataType ty
= TYPE_NONE
) const;
529 inline void setFile(DataFile file
, ubyte fileIndex
= 0)
532 reg
.fileIndex
= fileIndex
;
535 inline void setOffset(int32_t offset
);
536 inline void setAddress(Symbol
*base
, int32_t offset
);
537 inline void setSV(SVSemantic sv
, uint32_t idx
= 0);
539 inline const Symbol
*getBase() const { return baseSym
; }
542 Symbol
*baseSym
; // array base for Symbols representing array elements
545 class ImmediateValue
: public Value
549 ImmediateValue(Program
*, uint32_t);
550 ImmediateValue(Program
*, float);
551 ImmediateValue(Program
*, double);
552 // NOTE: not added to program with
553 ImmediateValue(const ImmediateValue
*, DataType ty
);
554 ~ImmediateValue() { };
556 virtual ImmediateValue
*clone(ClonePolicy
<Function
>&) const;
558 virtual bool equals(const Value
*that
, bool strict
) const;
560 // these only work if 'type' is valid (we mostly use untyped literals):
561 bool isInteger(const int ival
) const; // ival is cast to this' type
562 bool isNegative() const;
567 // for constant folding:
568 ImmediateValue
operator+(const ImmediateValue
&) const;
569 ImmediateValue
operator-(const ImmediateValue
&) const;
570 ImmediateValue
operator*(const ImmediateValue
&) const;
571 ImmediateValue
operator/(const ImmediateValue
&) const;
573 ImmediateValue
& operator=(const ImmediateValue
&); // only sets value !
575 bool compare(CondCode cc
, float fval
) const;
577 virtual int print(char *, size_t, DataType ty
= TYPE_NONE
) const;
584 Instruction(Function
*, operation
, DataType
);
585 virtual ~Instruction();
587 virtual Instruction
*clone(ClonePolicy
<Function
>&,
588 Instruction
* = NULL
) const;
590 void setDef(int i
, Value
*);
591 void setSrc(int s
, Value
*);
592 void setSrc(int s
, const ValueRef
&);
593 void swapSources(int a
, int b
);
594 bool setIndirect(int s
, int dim
, Value
*);
596 inline ValueRef
& src(int s
) { return srcs
[s
]; }
597 inline ValueDef
& def(int s
) { return defs
[s
]; }
598 inline const ValueRef
& src(int s
) const { return srcs
[s
]; }
599 inline const ValueDef
& def(int s
) const { return defs
[s
]; }
601 inline Value
*getDef(int d
) const { return defs
[d
].get(); }
602 inline Value
*getSrc(int s
) const { return srcs
[s
].get(); }
603 inline Value
*getIndirect(int s
, int dim
) const;
605 inline bool defExists(unsigned d
) const
607 return d
< defs
.size() && defs
[d
].exists();
609 inline bool srcExists(unsigned s
) const
611 return s
< srcs
.size() && srcs
[s
].exists();
614 inline bool constrainedDefs() const { return defExists(1); }
616 bool setPredicate(CondCode ccode
, Value
*);
617 inline Value
*getPredicate() const;
618 bool writesPredicate() const;
620 inline void setFlagsSrc(int s
, Value
*);
621 inline void setFlagsDef(int d
, Value
*);
623 unsigned int defCount() const { return defs
.size(); };
624 unsigned int defCount(unsigned int mask
) const;
625 unsigned int srcCount() const { return srcs
.size(); };
626 unsigned int srcCount(unsigned int mask
) const;
628 // save & remove / set indirect[0,1] and predicate source
629 void takeExtraSources(int s
, Value
*[3]);
630 void putExtraSources(int s
, Value
*[3]);
632 inline void setType(DataType type
) { dType
= sType
= type
; }
634 inline void setType(DataType dtype
, DataType stype
)
640 inline bool isPseudo() const { return op
< OP_MOV
; }
643 bool isCommutationLegal(const Instruction
*) const; // must be adjacent !
644 bool isActionEqual(const Instruction
*) const;
645 bool isResultEqual(const Instruction
*) const;
649 inline CmpInstruction
*asCmp();
650 inline TexInstruction
*asTex();
651 inline FlowInstruction
*asFlow();
652 inline const TexInstruction
*asTex() const;
653 inline const CmpInstruction
*asCmp() const;
654 inline const FlowInstruction
*asFlow() const;
660 int serial
; // CFG order
663 DataType dType
; // destination or defining type
664 DataType sType
; // source or secondary type
669 uint8_t subOp
; // quadop, 1 for mul-high, etc.
671 unsigned encSize
: 4; // encoding size in bytes
672 unsigned saturate
: 1; // to [0.0f, 1.0f]
673 unsigned join
: 1; // converge control flow (use OP_JOIN until end)
674 unsigned fixed
: 1; // prevent dead code elimination
675 unsigned terminator
: 1; // end of basic block
677 unsigned ftz
: 1; // flush denormal to zero
678 unsigned dnz
: 1; // denormals, NaN are zero
679 unsigned ipa
: 4; // interpolation mode
681 unsigned perPatch
: 1;
682 unsigned exit
: 1; // terminate program after insn
684 int8_t postFactor
; // MUL/DIV(if < 0) by 1 << postFactor
693 std::deque
<ValueDef
> defs
; // no gaps !
694 std::deque
<ValueRef
> srcs
; // no gaps !
696 // instruction specific methods:
697 // (don't want to subclass, would need more constructors and memory pools)
699 inline void setInterpolate(unsigned int mode
) { ipa
= mode
; }
701 unsigned int getInterpMode() const { return ipa
& 0x3; }
702 unsigned int getSampleMode() const { return ipa
& 0xc; }
719 class TexInstruction
: public Instruction
725 Target(TexTarget targ
= TEX_TARGET_2D
) : target(targ
) { }
727 const char *getName() const { return descTable
[target
].name
; }
728 unsigned int getArgCount() const { return descTable
[target
].argc
; }
729 unsigned int getDim() const { return descTable
[target
].dim
; }
730 int isArray() const { return descTable
[target
].array
? 1 : 0; }
731 int isCube() const { return descTable
[target
].cube
? 1 : 0; }
732 int isShadow() const { return descTable
[target
].shadow
? 1 : 0; }
734 Target
& operator=(TexTarget targ
)
736 assert(targ
< TEX_TARGET_COUNT
);
740 inline bool operator==(TexTarget targ
) const { return target
== targ
; }
753 static const struct Desc descTable
[TEX_TARGET_COUNT
];
756 enum TexTarget target
;
760 TexInstruction(Function
*, operation
);
761 virtual ~TexInstruction();
763 virtual TexInstruction
*clone(ClonePolicy
<Function
>&,
764 Instruction
* = NULL
) const;
766 inline void setTexture(Target targ
, uint8_t r
, uint8_t s
)
773 inline Value
*getIndirectR() const;
774 inline Value
*getIndirectS() const;
788 bool liveOnly
; // only execute on live pixels of a quad (optimization)
792 int8_t useOffsets
; // 0, 1, or 4 for textureGatherOffsets
802 class CmpInstruction
: public Instruction
805 CmpInstruction(Function
*, operation
);
807 virtual CmpInstruction
*clone(ClonePolicy
<Function
>&,
808 Instruction
* = NULL
) const;
810 void setCondition(CondCode cond
) { setCond
= cond
; }
811 CondCode
getCondition() const { return setCond
; }
817 class FlowInstruction
: public Instruction
820 FlowInstruction(Function
*, operation
, BasicBlock
*target
);
822 virtual FlowInstruction
*clone(ClonePolicy
<Function
>&,
823 Instruction
* = NULL
) const;
826 unsigned allWarp
: 1;
827 unsigned absolute
: 1;
829 unsigned builtin
: 1; // true for calls to emulation code
841 BasicBlock(Function
*);
844 BasicBlock
*clone(ClonePolicy
<Function
>&) const;
846 inline int getId() const { return id
; }
847 inline unsigned int getInsnCount() const { return numInsns
; }
848 inline bool isTerminated() const { return exit
&& exit
->terminator
; }
850 bool dominatedBy(BasicBlock
*bb
);
851 inline bool reachableBy(BasicBlock
*by
, BasicBlock
*term
);
853 // returns mask of conditional out blocks
854 // e.g. 3 for IF { .. } ELSE { .. } ENDIF, 1 for IF { .. } ENDIF
855 unsigned int initiatesSimpleConditional() const;
858 Function
*getFunction() const { return func
; }
859 Program
*getProgram() const { return program
; }
861 Instruction
*getEntry() const { return entry
; } // first non-phi instruction
862 Instruction
*getPhi() const { return phi
; }
863 Instruction
*getFirst() const { return phi
? phi
: entry
; }
864 Instruction
*getExit() const { return exit
; }
866 void insertHead(Instruction
*);
867 void insertTail(Instruction
*);
868 void insertBefore(Instruction
*, Instruction
*);
869 void insertAfter(Instruction
*, Instruction
*);
870 void remove(Instruction
*);
871 void permuteAdjacent(Instruction
*, Instruction
*);
873 BasicBlock
*idom() const;
875 // NOTE: currently does not rebuild the dominator tree
876 BasicBlock
*splitBefore(Instruction
*, bool attach
= true);
877 BasicBlock
*splitAfter(Instruction
*, bool attach
= true);
879 DLList
& getDF() { return df
; }
880 DLList::Iterator
iterDF() { return df
.iterator(); }
882 static inline BasicBlock
*get(Iterator
&);
883 static inline BasicBlock
*get(Graph::Node
*);
886 Graph::Node cfg
; // first edge is branch *taken* (the ELSE branch)
895 Instruction
*joinAt
; // for quick reference
897 bool explicitCont
; // loop headers: true if loop contains continue stmts
907 unsigned int numInsns
;
913 void splitCommon(Instruction
*, BasicBlock
*, bool attach
);
919 Function(Program
*, const char *name
);
922 inline Program
*getProgram() const { return prog
; }
923 inline const char *getName() const { return name
; }
924 inline int getId() const { return id
; }
927 void printLiveIntervals() const;
928 void printCFGraph(const char *filePath
);
930 bool setEntry(BasicBlock
*);
931 bool setExit(BasicBlock
*);
933 unsigned int orderInstructions(ArrayList
&);
935 inline void add(BasicBlock
*bb
, int& id
) { allBBlocks
.insert(bb
, id
); }
936 inline void add(Instruction
*insn
, int& id
) { allInsns
.insert(insn
, id
); }
937 inline void add(LValue
*lval
, int& id
) { allLValues
.insert(lval
, id
); }
939 inline LValue
*getLValue(int id
);
946 Graph::Node
*cfgExit
;
948 Graph::Node call
; // node in the call graph
950 BasicBlock
**bbArray
; // BBs in emission order
953 unsigned int loopNestingBound
;
959 ArrayList allBBlocks
;
961 ArrayList allLValues
;
964 void buildLiveSetsPreSSA(BasicBlock
*, const int sequence
);
965 void buildDefSetsPreSSA(BasicBlock
*bb
, const int seq
);
969 const char *const name
;
976 CG_STAGE_SSA
, // expected directly before register allocation
986 TYPE_TESSELLATION_CONTROL
,
987 TYPE_TESSELLATION_EVAL
,
993 Program(Type type
, Target
*targ
);
998 Type
getType() const { return progType
; }
1000 inline void add(Function
*fn
, int& id
) { allFuncs
.insert(fn
, id
); }
1001 inline void add(Value
*rval
, int& id
) { allRValues
.insert(rval
, id
); }
1003 bool makeFromTGSI(struct nv50_ir_prog_info
*);
1004 bool makeFromSM4(struct nv50_ir_prog_info
*);
1005 bool convertToSSA();
1006 bool optimizeSSA(int level
);
1007 bool optimizePostRA(int level
);
1008 bool registerAllocation();
1009 bool emitBinary(struct nv50_ir_prog_info
*);
1011 const Target
*getTarget() const { return target
; }
1022 ArrayList allRValues
;
1029 MemoryPool mem_Instruction
;
1030 MemoryPool mem_CmpInstruction
;
1031 MemoryPool mem_TexInstruction
;
1032 MemoryPool mem_FlowInstruction
;
1033 MemoryPool mem_LValue
;
1034 MemoryPool mem_Symbol
;
1035 MemoryPool mem_ImmediateValue
;
1039 void releaseInstruction(Instruction
*);
1040 void releaseValue(Value
*);
1043 // TODO: add const version
1047 bool run(Program
*, bool ordered
= false, bool skipPhi
= false);
1048 bool run(Function
*, bool ordered
= false, bool skipPhi
= false);
1051 // return false to continue with next entity on next higher level
1052 virtual bool visit(Function
*) { return true; }
1053 virtual bool visit(BasicBlock
*) { return true; }
1054 virtual bool visit(Instruction
*) { return false; }
1056 bool doRun(Program
*, bool ordered
, bool skipPhi
);
1057 bool doRun(Function
*, bool ordered
, bool skipPhi
);
1065 // =============================================================================
1067 #include "nv50_ir_inlines.h"
1069 } // namespace nv50_ir
1071 #endif // __NV50_IR_H__