repo_name
stringlengths 5
122
| path
stringlengths 3
232
| text
stringlengths 6
1.05M
|
|---|---|---|
DerSchmale/spirv4web
|
src/utils/defaultCopy.ts
|
<reponame>DerSchmale/spirv4web
// a shallow copy function
import { DefaultConstructor } from "../common/ConstructorTypes";
export function defaultCopy<T>(src: T, dst: T)
{
for (let key in src) {
if (src.hasOwnProperty(key))
dst[key] = _clone(src[key]);
}
}
export function defaultClone<T>(classRef: DefaultConstructor<T>, src: T): T
{
const c = new classRef();
defaultCopy(src, c);
return c;
}
function _clone(src: any): any
{
if (src === undefined || src === null)
return src;
if (Array.isArray(src)) {
return src.map(elm => _clone(elm));
}
else if (src instanceof Set) {
const set = new Set();
src.forEach(elm => {
set.add(_clone(elm));
});
return set;
}
else {
const type = typeof src;
if (type === "object") {
// the object knows how to clone itself
if (typeof src.clone === "function")
return src.clone();
else if (src instanceof Set) {
const dst = new Set();
src.forEach((value => dst.add(value)));
return dst;
}
else if (
src instanceof Uint8Array|| src instanceof Uint8ClampedArray || src instanceof Uint16Array || src instanceof Uint32Array ||
src instanceof Int8Array || src instanceof Int16Array || src instanceof Int32Array ||
src instanceof BigInt64Array || src instanceof BigUint64Array ||
src instanceof Float32Array || src instanceof Float64Array
) {
return src.slice();
}
else {
throw new Error(`The object ${src} does not have a clone function.`);
}
}
else if (type !== "function") {
// it's a primitive, it can just be passed back
return src;
}
}
}
|
DerSchmale/spirv4web
|
build/types/common/SPIRConstant.d.ts
|
import { IVariant } from "./IVariant";
import { Types } from "./Types";
import { SPIRType } from "./SPIRType";
export declare class SPIRConstantConstant {
value: ArrayBuffer;
private _dataView;
get u32(): number;
set u32(value: number);
get i32(): number;
set i32(value: number);
get f32(): number;
set f32(value: number);
get u64(): bigint;
set u64(value: bigint);
get i64(): bigint;
set i64(value: bigint);
get f64(): number;
set f64(value: number);
clone(): SPIRConstantConstant;
}
export declare class SPIRConstantConstantVector {
r: SPIRConstantConstant[];
id: ID[];
vecsize: number;
constructor();
clone(): SPIRConstantConstantVector;
}
export declare class SPIRConstantConstantMatrix {
c: SPIRConstantConstantVector[];
id: ID[];
columns: number;
constructor();
clone(): SPIRConstantConstantMatrix;
}
export declare class SPIRConstant extends IVariant {
static type: Types;
constant_type: TypeID;
m: SPIRConstantConstantMatrix;
specialization: boolean;
is_used_as_array_length: boolean;
is_used_as_lut: boolean;
subconstants: Uint32Array;
specialization_constant_macro_name: string;
f16_to_f32(u16_value: number): number;
specialization_constant_id(col: number, row?: number): number;
scalar(col?: number, row?: number): number;
scalar_i16(col?: number, row?: number): number;
scalar_u16(col?: number, row?: number): number;
scalar_i8(col?: number, row?: number): number;
scalar_u8(col?: number, row?: number): number;
scalar_f16(col?: number, row?: number): number;
scalar_f32(col?: number, row?: number): number;
scalar_i32(col?: number, row?: number): number;
scalar_f64(col?: number, row?: number): number;
scalar_i64(col?: number, row?: number): bigint;
scalar_u64(col?: number, row?: number): bigint;
vector(): SPIRConstantConstantVector;
vector_size(): number;
columns(): number;
make_null(constant_type: SPIRType): void;
constant_is_null(): boolean;
constructor();
constructor(other: SPIRConstant);
constructor(constant_type: TypeID);
constructor(constant_type: TypeID, elements: number[], num_elements: number, specialized: boolean);
constructor(constant_type: TypeID, v0: number, specialized: boolean);
constructor(constant_type: TypeID, v0: bigint, specialized: boolean);
constructor(constant_type: TypeID, vector_elements: SPIRConstant[], num_elements: number, specialized: boolean);
_construct(constant_type: TypeID): void;
_constructArray(constant_type: TypeID, elements: Uint32Array, num_elements: number, specialized: boolean): void;
_constructScalar32(constant_type: TypeID, v0: number, specialized: boolean): void;
_constructScalar64(constant_type: TypeID, v0: bigint, specialized: boolean): void;
_constructVecMat(constant_type: TypeID, vector_elements: SPIRConstant[], num_elements: number, specialized: boolean): void;
}
|
DerSchmale/spirv4web
|
build/types/compiler/DebugHandler.d.ts
|
<reponame>DerSchmale/spirv4web
import { OpcodeHandler } from "./OpcodeHandler";
import { Op } from "../spirv/Op";
export declare class DebugHandler extends OpcodeHandler {
private compiler;
constructor(compiler: any);
handle(opcode: Op, args: Uint32Array, length: number): boolean;
get_name(id: number): string | number;
}
|
DerSchmale/spirv4web
|
src/spirv/Op.ts
|
<gh_stars>0
export enum Op
{
Nop = 0,
Undef = 1,
SourceContinued = 2,
Source = 3,
SourceExtension = 4,
Name = 5,
MemberName = 6,
String = 7,
Line = 8,
Extension = 10,
ExtInstImport = 11,
ExtInst = 12,
MemoryModel = 14,
EntryPoint = 15,
ExecutionMode = 16,
Capability = 17,
TypeVoid = 19,
TypeBool = 20,
TypeInt = 21,
TypeFloat = 22,
TypeVector = 23,
TypeMatrix = 24,
TypeImage = 25,
TypeSampler = 26,
TypeSampledImage = 27,
TypeArray = 28,
TypeRuntimeArray = 29,
TypeStruct = 30,
TypeOpaque = 31,
TypePointer = 32,
TypeFunction = 33,
TypeEvent = 34,
TypeDeviceEvent = 35,
TypeReserveId = 36,
TypeQueue = 37,
TypePipe = 38,
TypeForwardPointer = 39,
ConstantTrue = 41,
ConstantFalse = 42,
Constant = 43,
ConstantComposite = 44,
ConstantSampler = 45,
ConstantNull = 46,
SpecConstantTrue = 48,
SpecConstantFalse = 49,
SpecConstant = 50,
SpecConstantComposite = 51,
SpecConstantOp = 52,
Function = 54,
FunctionParameter = 55,
FunctionEnd = 56,
FunctionCall = 57,
Variable = 59,
ImageTexelPointer = 60,
Load = 61,
Store = 62,
CopyMemory = 63,
CopyMemorySized = 64,
AccessChain = 65,
InBoundsAccessChain = 66,
PtrAccessChain = 67,
ArrayLength = 68,
GenericPtrMemSemantics = 69,
InBoundsPtrAccessChain = 70,
Decorate = 71,
MemberDecorate = 72,
DecorationGroup = 73,
GroupDecorate = 74,
GroupMemberDecorate = 75,
VectorExtractDynamic = 77,
VectorInsertDynamic = 78,
VectorShuffle = 79,
CompositeConstruct = 80,
CompositeExtract = 81,
CompositeInsert = 82,
CopyObject = 83,
Transpose = 84,
SampledImage = 86,
ImageSampleImplicitLod = 87,
ImageSampleExplicitLod = 88,
ImageSampleDrefImplicitLod = 89,
ImageSampleDrefExplicitLod = 90,
ImageSampleProjImplicitLod = 91,
ImageSampleProjExplicitLod = 92,
ImageSampleProjDrefImplicitLod = 93,
ImageSampleProjDrefExplicitLod = 94,
ImageFetch = 95,
ImageGather = 96,
ImageDrefGather = 97,
ImageRead = 98,
ImageWrite = 99,
Image = 100,
ImageQueryFormat = 101,
ImageQueryOrder = 102,
ImageQuerySizeLod = 103,
ImageQuerySize = 104,
ImageQueryLod = 105,
ImageQueryLevels = 106,
ImageQuerySamples = 107,
ConvertFToU = 109,
ConvertFToS = 110,
ConvertSToF = 111,
ConvertUToF = 112,
UConvert = 113,
SConvert = 114,
FConvert = 115,
QuantizeToF16 = 116,
ConvertPtrToU = 117,
SatConvertSToU = 118,
SatConvertUToS = 119,
ConvertUToPtr = 120,
PtrCastToGeneric = 121,
GenericCastToPtr = 122,
GenericCastToPtrExplicit = 123,
Bitcast = 124,
SNegate = 126,
FNegate = 127,
IAdd = 128,
FAdd = 129,
ISub = 130,
FSub = 131,
IMul = 132,
FMul = 133,
UDiv = 134,
SDiv = 135,
FDiv = 136,
UMod = 137,
SRem = 138,
SMod = 139,
FRem = 140,
FMod = 141,
VectorTimesScalar = 142,
MatrixTimesScalar = 143,
VectorTimesMatrix = 144,
MatrixTimesVector = 145,
MatrixTimesMatrix = 146,
OuterProduct = 147,
Dot = 148,
IAddCarry = 149,
ISubBorrow = 150,
UMulExtended = 151,
SMulExtended = 152,
Any = 154,
All = 155,
IsNan = 156,
IsInf = 157,
IsFinite = 158,
IsNormal = 159,
SignBitSet = 160,
LessOrGreater = 161,
Ordered = 162,
Unordered = 163,
LogicalEqual = 164,
LogicalNotEqual = 165,
LogicalOr = 166,
LogicalAnd = 167,
LogicalNot = 168,
Select = 169,
IEqual = 170,
INotEqual = 171,
UGreaterThan = 172,
SGreaterThan = 173,
UGreaterThanEqual = 174,
SGreaterThanEqual = 175,
ULessThan = 176,
SLessThan = 177,
ULessThanEqual = 178,
SLessThanEqual = 179,
FOrdEqual = 180,
FUnordEqual = 181,
FOrdNotEqual = 182,
FUnordNotEqual = 183,
FOrdLessThan = 184,
FUnordLessThan = 185,
FOrdGreaterThan = 186,
FUnordGreaterThan = 187,
FOrdLessThanEqual = 188,
FUnordLessThanEqual = 189,
FOrdGreaterThanEqual = 190,
FUnordGreaterThanEqual = 191,
ShiftRightLogical = 194,
ShiftRightArithmetic = 195,
ShiftLeftLogical = 196,
BitwiseOr = 197,
BitwiseXor = 198,
BitwiseAnd = 199,
Not = 200,
BitFieldInsert = 201,
BitFieldSExtract = 202,
BitFieldUExtract = 203,
BitReverse = 204,
BitCount = 205,
DPdx = 207,
DPdy = 208,
Fwidth = 209,
DPdxFine = 210,
DPdyFine = 211,
FwidthFine = 212,
DPdxCoarse = 213,
DPdyCoarse = 214,
FwidthCoarse = 215,
EmitVertex = 218,
EndPrimitive = 219,
EmitStreamVertex = 220,
EndStreamPrimitive = 221,
ControlBarrier = 224,
MemoryBarrier = 225,
AtomicLoad = 227,
AtomicStore = 228,
AtomicExchange = 229,
AtomicCompareExchange = 230,
AtomicCompareExchangeWeak = 231,
AtomicIIncrement = 232,
AtomicIDecrement = 233,
AtomicIAdd = 234,
AtomicISub = 235,
AtomicSMin = 236,
AtomicUMin = 237,
AtomicSMax = 238,
AtomicUMax = 239,
AtomicAnd = 240,
AtomicOr = 241,
AtomicXor = 242,
Phi = 245,
LoopMerge = 246,
SelectionMerge = 247,
Label = 248,
Branch = 249,
BranchConditional = 250,
Switch = 251,
Kill = 252,
Return = 253,
ReturnValue = 254,
Unreachable = 255,
LifetimeStart = 256,
LifetimeStop = 257,
GroupAsyncCopy = 259,
GroupWaitEvents = 260,
GroupAll = 261,
GroupAny = 262,
GroupBroadcast = 263,
GroupIAdd = 264,
GroupFAdd = 265,
GroupFMin = 266,
GroupUMin = 267,
GroupSMin = 268,
GroupFMax = 269,
GroupUMax = 270,
GroupSMax = 271,
ReadPipe = 274,
WritePipe = 275,
ReservedReadPipe = 276,
ReservedWritePipe = 277,
ReserveReadPipePackets = 278,
ReserveWritePipePackets = 279,
CommitReadPipe = 280,
CommitWritePipe = 281,
IsValidReserveId = 282,
GetNumPipePackets = 283,
GetMaxPipePackets = 284,
GroupReserveReadPipePackets = 285,
GroupReserveWritePipePackets = 286,
GroupCommitReadPipe = 287,
GroupCommitWritePipe = 288,
EnqueueMarker = 291,
EnqueueKernel = 292,
GetKernelNDrangeSubGroupCount = 293,
GetKernelNDrangeMaxSubGroupSize = 294,
GetKernelWorkGroupSize = 295,
GetKernelPreferredWorkGroupSizeMultiple = 296,
RetainEvent = 297,
ReleaseEvent = 298,
CreateUserEvent = 299,
IsValidEvent = 300,
SetUserEventStatus = 301,
CaptureEventProfilingInfo = 302,
GetDefaultQueue = 303,
BuildNDRange = 304,
ImageSparseSampleImplicitLod = 305,
ImageSparseSampleExplicitLod = 306,
ImageSparseSampleDrefImplicitLod = 307,
ImageSparseSampleDrefExplicitLod = 308,
ImageSparseSampleProjImplicitLod = 309,
ImageSparseSampleProjExplicitLod = 310,
ImageSparseSampleProjDrefImplicitLod = 311,
ImageSparseSampleProjDrefExplicitLod = 312,
ImageSparseFetch = 313,
ImageSparseGather = 314,
ImageSparseDrefGather = 315,
ImageSparseTexelsResident = 316,
NoLine = 317,
AtomicFlagTestAndSet = 318,
AtomicFlagClear = 319,
ImageSparseRead = 320,
SizeOf = 321,
TypePipeStorage = 322,
ConstantPipeStorage = 323,
CreatePipeFromPipeStorage = 324,
GetKernelLocalSizeForSubgroupCount = 325,
GetKernelMaxNumSubgroups = 326,
TypeNamedBarrier = 327,
NamedBarrierInitialize = 328,
MemoryNamedBarrier = 329,
ModuleProcessed = 330,
ExecutionModeId = 331,
DecorateId = 332,
GroupNonUniformElect = 333,
GroupNonUniformAll = 334,
GroupNonUniformAny = 335,
GroupNonUniformAllEqual = 336,
GroupNonUniformBroadcast = 337,
GroupNonUniformBroadcastFirst = 338,
GroupNonUniformBallot = 339,
GroupNonUniformInverseBallot = 340,
GroupNonUniformBallotBitExtract = 341,
GroupNonUniformBallotBitCount = 342,
GroupNonUniformBallotFindLSB = 343,
GroupNonUniformBallotFindMSB = 344,
GroupNonUniformShuffle = 345,
GroupNonUniformShuffleXor = 346,
GroupNonUniformShuffleUp = 347,
GroupNonUniformShuffleDown = 348,
GroupNonUniformIAdd = 349,
GroupNonUniformFAdd = 350,
GroupNonUniformIMul = 351,
GroupNonUniformFMul = 352,
GroupNonUniformSMin = 353,
GroupNonUniformUMin = 354,
GroupNonUniformFMin = 355,
GroupNonUniformSMax = 356,
GroupNonUniformUMax = 357,
GroupNonUniformFMax = 358,
GroupNonUniformBitwiseAnd = 359,
GroupNonUniformBitwiseOr = 360,
GroupNonUniformBitwiseXor = 361,
GroupNonUniformLogicalAnd = 362,
GroupNonUniformLogicalOr = 363,
GroupNonUniformLogicalXor = 364,
GroupNonUniformQuadBroadcast = 365,
GroupNonUniformQuadSwap = 366,
CopyLogical = 400,
PtrEqual = 401,
PtrNotEqual = 402,
PtrDiff = 403,
TerminateInvocation = 4416,
SubgroupBallotKHR = 4421,
SubgroupFirstInvocationKHR = 4422,
SubgroupAllKHR = 4428,
SubgroupAnyKHR = 4429,
SubgroupAllEqualKHR = 4430,
SubgroupReadInvocationKHR = 4432,
TraceRayKHR = 4445,
ExecuteCallableKHR = 4446,
ConvertUToAccelerationStructureKHR = 4447,
IgnoreIntersectionKHR = 4448,
TerminateRayKHR = 4449,
TypeRayQueryKHR = 4472,
RayQueryInitializeKHR = 4473,
RayQueryTerminateKHR = 4474,
RayQueryGenerateIntersectionKHR = 4475,
RayQueryConfirmIntersectionKHR = 4476,
RayQueryProceedKHR = 4477,
RayQueryGetIntersectionTypeKHR = 4479,
GroupIAddNonUniformAMD = 5000,
GroupFAddNonUniformAMD = 5001,
GroupFMinNonUniformAMD = 5002,
GroupUMinNonUniformAMD = 5003,
GroupSMinNonUniformAMD = 5004,
GroupFMaxNonUniformAMD = 5005,
GroupUMaxNonUniformAMD = 5006,
GroupSMaxNonUniformAMD = 5007,
FragmentMaskFetchAMD = 5011,
FragmentFetchAMD = 5012,
ReadClockKHR = 5056,
ImageSampleFootprintNV = 5283,
GroupNonUniformPartitionNV = 5296,
WritePackedPrimitiveIndices4x8NV = 5299,
ReportIntersectionKHR = 5334,
ReportIntersectionNV = 5334,
IgnoreIntersectionNV = 5335,
TerminateRayNV = 5336,
TraceNV = 5337,
TypeAccelerationStructureKHR = 5341,
TypeAccelerationStructureNV = 5341,
ExecuteCallableNV = 5344,
TypeCooperativeMatrixNV = 5358,
CooperativeMatrixLoadNV = 5359,
CooperativeMatrixStoreNV = 5360,
CooperativeMatrixMulAddNV = 5361,
CooperativeMatrixLengthNV = 5362,
BeginInvocationInterlockEXT = 5364,
EndInvocationInterlockEXT = 5365,
DemoteToHelperInvocationEXT = 5380,
IsHelperInvocationEXT = 5381,
SubgroupShuffleINTEL = 5571,
SubgroupShuffleDownINTEL = 5572,
SubgroupShuffleUpINTEL = 5573,
SubgroupShuffleXorINTEL = 5574,
SubgroupBlockReadINTEL = 5575,
SubgroupBlockWriteINTEL = 5576,
SubgroupImageBlockReadINTEL = 5577,
SubgroupImageBlockWriteINTEL = 5578,
SubgroupImageMediaBlockReadINTEL = 5580,
SubgroupImageMediaBlockWriteINTEL = 5581,
UCountLeadingZerosINTEL = 5585,
UCountTrailingZerosINTEL = 5586,
AbsISubINTEL = 5587,
AbsUSubINTEL = 5588,
IAddSatINTEL = 5589,
UAddSatINTEL = 5590,
IAverageINTEL = 5591,
UAverageINTEL = 5592,
IAverageRoundedINTEL = 5593,
UAverageRoundedINTEL = 5594,
ISubSatINTEL = 5595,
USubSatINTEL = 5596,
IMul32x16INTEL = 5597,
UMul32x16INTEL = 5598,
FunctionPointerINTEL = 5600,
FunctionPointerCallINTEL = 5601,
DecorateString = 5632,
DecorateStringGOOGLE = 5632,
MemberDecorateString = 5633,
MemberDecorateStringGOOGLE = 5633,
VmeImageINTEL = 5699,
TypeVmeImageINTEL = 5700,
TypeAvcImePayloadINTEL = 5701,
TypeAvcRefPayloadINTEL = 5702,
TypeAvcSicPayloadINTEL = 5703,
TypeAvcMcePayloadINTEL = 5704,
TypeAvcMceResultINTEL = 5705,
TypeAvcImeResultINTEL = 5706,
TypeAvcImeResultSingleReferenceStreamoutINTEL = 5707,
TypeAvcImeResultDualReferenceStreamoutINTEL = 5708,
TypeAvcImeSingleReferenceStreaminINTEL = 5709,
TypeAvcImeDualReferenceStreaminINTEL = 5710,
TypeAvcRefResultINTEL = 5711,
TypeAvcSicResultINTEL = 5712,
SubgroupAvcMceGetDefaultInterBaseMultiReferencePenaltyINTEL = 5713,
SubgroupAvcMceSetInterBaseMultiReferencePenaltyINTEL = 5714,
SubgroupAvcMceGetDefaultInterShapePenaltyINTEL = 5715,
SubgroupAvcMceSetInterShapePenaltyINTEL = 5716,
SubgroupAvcMceGetDefaultInterDirectionPenaltyINTEL = 5717,
SubgroupAvcMceSetInterDirectionPenaltyINTEL = 5718,
SubgroupAvcMceGetDefaultIntraLumaShapePenaltyINTEL = 5719,
SubgroupAvcMceGetDefaultInterMotionVectorCostTableINTEL = 5720,
SubgroupAvcMceGetDefaultHighPenaltyCostTableINTEL = 5721,
SubgroupAvcMceGetDefaultMediumPenaltyCostTableINTEL = 5722,
SubgroupAvcMceGetDefaultLowPenaltyCostTableINTEL = 5723,
SubgroupAvcMceSetMotionVectorCostFunctionINTEL = 5724,
SubgroupAvcMceGetDefaultIntraLumaModePenaltyINTEL = 5725,
SubgroupAvcMceGetDefaultNonDcLumaIntraPenaltyINTEL = 5726,
SubgroupAvcMceGetDefaultIntraChromaModeBasePenaltyINTEL = 5727,
SubgroupAvcMceSetAcOnlyHaarINTEL = 5728,
SubgroupAvcMceSetSourceInterlacedFieldPolarityINTEL = 5729,
SubgroupAvcMceSetSingleReferenceInterlacedFieldPolarityINTEL = 5730,
SubgroupAvcMceSetDualReferenceInterlacedFieldPolaritiesINTEL = 5731,
SubgroupAvcMceConvertToImePayloadINTEL = 5732,
SubgroupAvcMceConvertToImeResultINTEL = 5733,
SubgroupAvcMceConvertToRefPayloadINTEL = 5734,
SubgroupAvcMceConvertToRefResultINTEL = 5735,
SubgroupAvcMceConvertToSicPayloadINTEL = 5736,
SubgroupAvcMceConvertToSicResultINTEL = 5737,
SubgroupAvcMceGetMotionVectorsINTEL = 5738,
SubgroupAvcMceGetInterDistortionsINTEL = 5739,
SubgroupAvcMceGetBestInterDistortionsINTEL = 5740,
SubgroupAvcMceGetInterMajorShapeINTEL = 5741,
SubgroupAvcMceGetInterMinorShapeINTEL = 5742,
SubgroupAvcMceGetInterDirectionsINTEL = 5743,
SubgroupAvcMceGetInterMotionVectorCountINTEL = 5744,
SubgroupAvcMceGetInterReferenceIdsINTEL = 5745,
SubgroupAvcMceGetInterReferenceInterlacedFieldPolaritiesINTEL = 5746,
SubgroupAvcImeInitializeINTEL = 5747,
SubgroupAvcImeSetSingleReferenceINTEL = 5748,
SubgroupAvcImeSetDualReferenceINTEL = 5749,
SubgroupAvcImeRefWindowSizeINTEL = 5750,
SubgroupAvcImeAdjustRefOffsetINTEL = 5751,
SubgroupAvcImeConvertToMcePayloadINTEL = 5752,
SubgroupAvcImeSetMaxMotionVectorCountINTEL = 5753,
SubgroupAvcImeSetUnidirectionalMixDisableINTEL = 5754,
SubgroupAvcImeSetEarlySearchTerminationThresholdINTEL = 5755,
SubgroupAvcImeSetWeightedSadINTEL = 5756,
SubgroupAvcImeEvaluateWithSingleReferenceINTEL = 5757,
SubgroupAvcImeEvaluateWithDualReferenceINTEL = 5758,
SubgroupAvcImeEvaluateWithSingleReferenceStreaminINTEL = 5759,
SubgroupAvcImeEvaluateWithDualReferenceStreaminINTEL = 5760,
SubgroupAvcImeEvaluateWithSingleReferenceStreamoutINTEL = 5761,
SubgroupAvcImeEvaluateWithDualReferenceStreamoutINTEL = 5762,
SubgroupAvcImeEvaluateWithSingleReferenceStreaminoutINTEL = 5763,
SubgroupAvcImeEvaluateWithDualReferenceStreaminoutINTEL = 5764,
SubgroupAvcImeConvertToMceResultINTEL = 5765,
SubgroupAvcImeGetSingleReferenceStreaminINTEL = 5766,
SubgroupAvcImeGetDualReferenceStreaminINTEL = 5767,
SubgroupAvcImeStripSingleReferenceStreamoutINTEL = 5768,
SubgroupAvcImeStripDualReferenceStreamoutINTEL = 5769,
SubgroupAvcImeGetStreamoutSingleReferenceMajorShapeMotionVectorsINTEL = 5770,
SubgroupAvcImeGetStreamoutSingleReferenceMajorShapeDistortionsINTEL = 5771,
SubgroupAvcImeGetStreamoutSingleReferenceMajorShapeReferenceIdsINTEL = 5772,
SubgroupAvcImeGetStreamoutDualReferenceMajorShapeMotionVectorsINTEL = 5773,
SubgroupAvcImeGetStreamoutDualReferenceMajorShapeDistortionsINTEL = 5774,
SubgroupAvcImeGetStreamoutDualReferenceMajorShapeReferenceIdsINTEL = 5775,
SubgroupAvcImeGetBorderReachedINTEL = 5776,
SubgroupAvcImeGetTruncatedSearchIndicationINTEL = 5777,
SubgroupAvcImeGetUnidirectionalEarlySearchTerminationINTEL = 5778,
SubgroupAvcImeGetWeightingPatternMinimumMotionVectorINTEL = 5779,
SubgroupAvcImeGetWeightingPatternMinimumDistortionINTEL = 5780,
SubgroupAvcFmeInitializeINTEL = 5781,
SubgroupAvcBmeInitializeINTEL = 5782,
SubgroupAvcRefConvertToMcePayloadINTEL = 5783,
SubgroupAvcRefSetBidirectionalMixDisableINTEL = 5784,
SubgroupAvcRefSetBilinearFilterEnableINTEL = 5785,
SubgroupAvcRefEvaluateWithSingleReferenceINTEL = 5786,
SubgroupAvcRefEvaluateWithDualReferenceINTEL = 5787,
SubgroupAvcRefEvaluateWithMultiReferenceINTEL = 5788,
SubgroupAvcRefEvaluateWithMultiReferenceInterlacedINTEL = 5789,
SubgroupAvcRefConvertToMceResultINTEL = 5790,
SubgroupAvcSicInitializeINTEL = 5791,
SubgroupAvcSicConfigureSkcINTEL = 5792,
SubgroupAvcSicConfigureIpeLumaINTEL = 5793,
SubgroupAvcSicConfigureIpeLumaChromaINTEL = 5794,
SubgroupAvcSicGetMotionVectorMaskINTEL = 5795,
SubgroupAvcSicConvertToMcePayloadINTEL = 5796,
SubgroupAvcSicSetIntraLumaShapePenaltyINTEL = 5797,
SubgroupAvcSicSetIntraLumaModeCostFunctionINTEL = 5798,
SubgroupAvcSicSetIntraChromaModeCostFunctionINTEL = 5799,
SubgroupAvcSicSetBilinearFilterEnableINTEL = 5800,
SubgroupAvcSicSetSkcForwardTransformEnableINTEL = 5801,
SubgroupAvcSicSetBlockBasedRawSkipSadINTEL = 5802,
SubgroupAvcSicEvaluateIpeINTEL = 5803,
SubgroupAvcSicEvaluateWithSingleReferenceINTEL = 5804,
SubgroupAvcSicEvaluateWithDualReferenceINTEL = 5805,
SubgroupAvcSicEvaluateWithMultiReferenceINTEL = 5806,
SubgroupAvcSicEvaluateWithMultiReferenceInterlacedINTEL = 5807,
SubgroupAvcSicConvertToMceResultINTEL = 5808,
SubgroupAvcSicGetIpeLumaShapeINTEL = 5809,
SubgroupAvcSicGetBestIpeLumaDistortionINTEL = 5810,
SubgroupAvcSicGetBestIpeChromaDistortionINTEL = 5811,
SubgroupAvcSicGetPackedIpeLumaModesINTEL = 5812,
SubgroupAvcSicGetIpeChromaModeINTEL = 5813,
SubgroupAvcSicGetPackedSkcLumaCountThresholdINTEL = 5814,
SubgroupAvcSicGetPackedSkcLumaSumThresholdINTEL = 5815,
SubgroupAvcSicGetInterRawSadsINTEL = 5816,
LoopControlINTEL = 5887,
ReadPipeBlockingINTEL = 5946,
WritePipeBlockingINTEL = 5947,
FPGARegINTEL = 5949,
RayQueryGetRayTMinKHR = 6016,
RayQueryGetRayFlagsKHR = 6017,
RayQueryGetIntersectionTKHR = 6018,
RayQueryGetIntersectionInstanceCustomIndexKHR = 6019,
RayQueryGetIntersectionInstanceIdKHR = 6020,
RayQueryGetIntersectionInstanceShaderBindingTableRecordOffsetKHR = 6021,
RayQueryGetIntersectionGeometryIndexKHR = 6022,
RayQueryGetIntersectionPrimitiveIndexKHR = 6023,
RayQueryGetIntersectionBarycentricsKHR = 6024,
RayQueryGetIntersectionFrontFaceKHR = 6025,
RayQueryGetIntersectionCandidateAABBOpaqueKHR = 6026,
RayQueryGetIntersectionObjectRayDirectionKHR = 6027,
RayQueryGetIntersectionObjectRayOriginKHR = 6028,
RayQueryGetWorldRayDirectionKHR = 6029,
RayQueryGetWorldRayOriginKHR = 6030,
RayQueryGetIntersectionObjectToWorldKHR = 6031,
RayQueryGetIntersectionWorldToObjectKHR = 6032,
AtomicFAddEXT = 6035,
Max = 0x7fffffff,
}
|
DerSchmale/spirv4web
|
src/cfg/CFG.ts
|
<reponame>DerSchmale/spirv4web
import { Compiler } from "../compiler/Compiler";
import { SPIRFunction } from "../common/SPIRFunction";
import { VisitOrder } from "./VisitOrder";
import { SPIRBlock, SPIRBlockMerge, SPIRBlockTerminator } from "../common/SPIRBlock";
import { DominatorBuilder } from "./DominatorBuilder";
import { maplike_get } from "../utils/maplike_get";
export class CFG
{
private compiler: Compiler;
private func: SPIRFunction;
private preceding_edges: number[][] = []; // std::unordered_map<uint32_t, SmallVector<uint32_t>>
private succeeding_edges: number[][] = []; // std::unordered_map<uint32_t, SmallVector<uint32_t>>
private immediate_dominators: number[] = []; // std::unordered_map<uint32_t, uint32_t>
private visit_order: VisitOrder[] = []; // std::unordered_map<uint32_t, VisitOrder>
private post_order: number[] = []; // SmallVector<uint32_t>
private empty_vector: number[] = []; // SmallVector<uint32_t>
private visit_count: number = 0; // SmallVector<uint32_t>
constructor(compiler?: Compiler, func?: SPIRFunction)
{
this.compiler = compiler;
this.func = func;
this.build_post_order_visit_order();
this.build_immediate_dominators();
}
get_compiler(): Compiler
{
return this.compiler;
}
get_function(): SPIRFunction
{
return this.func;
}
get_immediate_dominator(block: number): number
{
const itr_second = this.immediate_dominators[block];
if (itr_second)
return itr_second;
else
return 0;
}
get_visit_order(block: number): number
{
const itr_second = this.visit_order[block];
console.assert(itr_second);
const v = itr_second.get();
console.assert(v > 0);
return v;
}
find_common_dominator(a: number, b: number): number
{
while (a !== b)
{
if (this.get_visit_order(a) < this.get_visit_order(b))
a = this.get_immediate_dominator(a);
else
b = this.get_immediate_dominator(b);
}
return a;
}
get_preceding_edges(block: number): number[]
{
const itr_second = this.preceding_edges[block];
return itr_second || this.empty_vector;
}
get_succeeding_edges(block: number): number[]
{
const itr_second = this.succeeding_edges[block];
return itr_second || this.empty_vector;
}
walk_from(seen_blocks: Set<number>, block: number, op: (block: number) => boolean)
{
if (seen_blocks.has(block))
return;
seen_blocks.add(block);
if (op(block))
{
for (let b of this.get_succeeding_edges(block))
this.walk_from(seen_blocks, b, op);
}
}
find_loop_dominator(block_id: number): number
{
while (block_id !== SPIRBlock.NoDominator)
{
const itr_second = this.preceding_edges[block_id];
if (!itr_second)
return SPIRBlock.NoDominator;
if (itr_second.length === 0)
return SPIRBlock.NoDominator;
let pred_block_id = SPIRBlock.NoDominator;
let ignore_loop_header = false;
// If we are a merge block, go directly to the header block.
// Only consider a loop dominator if we are branching from inside a block to a loop header.
// NOTE: In the CFG we forced an edge from header to merge block always to support variable scopes properly.
for (let pred of itr_second)
{
let pred_block = this.compiler.get<SPIRBlock>(SPIRBlock, pred);
if (pred_block.merge === SPIRBlockMerge.Loop && pred_block.merge_block === <ID>(block_id))
{
pred_block_id = pred;
ignore_loop_header = true;
break;
}
else if (pred_block.merge === SPIRBlockMerge.Selection && pred_block.next_block === <ID>(block_id))
{
pred_block_id = pred;
break;
}
}
// No merge block means we can just pick any edge. Loop headers dominate the inner loop, so any path we
// take will lead there.
if (pred_block_id === SPIRBlock.NoDominator)
pred_block_id = itr_second[0];
block_id = pred_block_id;
if (!ignore_loop_header && block_id)
{
const block = this.compiler.get<SPIRBlock>(SPIRBlock, block_id);
if (block.merge === SPIRBlockMerge.Loop)
return block_id;
}
}
return block_id;
}
node_terminates_control_flow_in_sub_graph(from: BlockID, to: BlockID): boolean
{
// Walk backwards, starting from "to" block.
// Only follow pred edges if they have a 1:1 relationship, or a merge relationship.
// If we cannot find a path to "from", we must assume that to is inside control flow in some way.
const compiler = this.compiler;
const from_block = compiler.get<SPIRBlock>(SPIRBlock, from);
let ignore_block_id: BlockID = 0;
if (from_block.merge === SPIRBlockMerge.Loop)
ignore_block_id = from_block.merge_block;
while (to !== from)
{
const pred_itr_second = this.preceding_edges[to];
if (!pred_itr_second)
return false;
const builder = new DominatorBuilder(this);
for (let edge of pred_itr_second)
builder.add_block(edge);
const dominator = builder.get_dominator();
if (dominator === 0)
return false;
const dom = compiler.get<SPIRBlock>(SPIRBlock, dominator);
let true_path_ignore = false;
let false_path_ignore = false;
if (ignore_block_id && dom.terminator === SPIRBlockTerminator.Select)
{
const true_block = compiler.get<SPIRBlock>(SPIRBlock, dom.true_block);
const false_block = compiler.get<SPIRBlock>(SPIRBlock, dom.false_block);
const ignore_block = compiler.get<SPIRBlock>(SPIRBlock, ignore_block_id);
true_path_ignore = compiler.execution_is_branchless(true_block, ignore_block);
false_path_ignore = compiler.execution_is_branchless(false_block, ignore_block);
}
if ((dom.merge === SPIRBlockMerge.Selection && dom.next_block === to) ||
(dom.merge === SPIRBlockMerge.Loop && dom.merge_block === to) ||
(dom.terminator === SPIRBlockTerminator.Direct && dom.next_block === to) ||
(dom.terminator === SPIRBlockTerminator.Select && dom.true_block === to && false_path_ignore) ||
(dom.terminator === SPIRBlockTerminator.Select && dom.false_block === to && true_path_ignore))
{
// Allow walking selection constructs if the other branch reaches out of a loop construct.
// It cannot be in-scope anymore.
to = dominator;
}
else
return false;
}
return true;
}
private add_branch(from: number, to: number)
{
const add_unique = (l: number[], value: number) => {
const itr = l.indexOf(value);
if (itr < 0)
l.push(value);
};
add_unique(maplike_get<number[]>(Array, this.preceding_edges, to), from);
add_unique(maplike_get<number[]>(Array, this.succeeding_edges, from), to);
}
private build_post_order_visit_order()
{
const block = this.func.entry_block;
this.visit_count = 0;
this.visit_order = [];
this.post_order = [];
this.post_order_visit(block);
}
private build_immediate_dominators()
{
// Traverse the post-order in reverse and build up the immediate dominator tree.
this.immediate_dominators = [];
this.immediate_dominators[this.func.entry_block] = this.func.entry_block;
for (let i = this.post_order.length; i; i--)
{
const block = this.post_order[i - 1];
const pred = maplike_get<number[]>(Array, this.preceding_edges, block);
if (pred.length === 0) // This is for the entry block, but we've already set up the dominators.
continue;
for (let edge of pred)
{
if (maplike_get(0, this.immediate_dominators, block))
{
console.assert(maplike_get(0, this.immediate_dominators, edge));
this.immediate_dominators[block] = this.find_common_dominator(this.immediate_dominators[block], edge);
}
else
this.immediate_dominators[block] = edge;
}
}
}
private post_order_visit(block_id: number)
{
// If we have already branched to this block (back edge), stop recursion.
// If our branches are back-edges, we do not record them.
// We have to record crossing edges however.
if (this.has_visited_forward_edge(block_id))
return true;
else if (this.is_back_edge(block_id))
return false;
// Block back-edges from recursively revisiting ourselves.
maplike_get(VisitOrder, this.visit_order, block_id).set(0);
const block = this.compiler.get<SPIRBlock>(SPIRBlock, block_id);
// If this is a loop header, add an implied branch to the merge target.
// This is needed to avoid annoying cases with do { ... } while(false) loops often generated by inliners.
// To the CFG, this is linear control flow, but we risk picking the do/while scope as our dominating block.
// This makes sure that if we are accessing a variable outside the do/while, we choose the loop header as dominator.
// We could use has_visited_forward_edge, but this break code-gen where the merge block is unreachable in the CFG.
// Make a point out of visiting merge target first. This is to make sure that post visit order outside the loop
// is lower than inside the loop, which is going to be key for some traversal algorithms like post-dominance analysis.
// For selection constructs true/false blocks will end up visiting the merge block directly and it works out fine,
// but for loops, only the header might end up actually branching to merge block.
if (block.merge === SPIRBlockMerge.Loop && this.post_order_visit(block.merge_block))
this.add_branch(block_id, block.merge_block);
// First visit our branch targets.
switch (block.terminator)
{
case SPIRBlockTerminator.Direct:
if (this.post_order_visit(block.next_block))
this.add_branch(block_id, block.next_block);
break;
case SPIRBlockTerminator.Select:
if (this.post_order_visit(block.true_block))
this.add_branch(block_id, block.true_block);
if (this.post_order_visit(block.false_block))
this.add_branch(block_id, block.false_block);
break;
case SPIRBlockTerminator.MultiSelect:
{
const cases = this.compiler.get_case_list(block);
for (let target of cases)
{
if (this.post_order_visit(target.block))
this.add_branch(block_id, target.block);
}
if (block.default_block && this.post_order_visit(block.default_block))
this.add_branch(block_id, block.default_block);
break;
}
default:
break;
}
// If this is a selection merge, add an implied branch to the merge target.
// This is needed to avoid cases where an inner branch dominates the outer branch.
// This can happen if one of the branches exit early, e.g.:
// if (cond) { ...; break; } else { var = 100 } use_var(var);
// We can use the variable without a Phi since there is only one possible parent here.
// However, in this case, we need to hoist out the inner variable to outside the branch.
// Use same strategy as loops.
if (block.merge === SPIRBlockMerge.Selection && this.post_order_visit(block.next_block))
{
// If there is only one preceding edge to the merge block and it's not ourselves, we need a fixup.
// Add a fake branch so any dominator in either the if (), or else () block, or a lone case statement
// will be hoisted out to outside the selection merge.
// If size > 1, the variable will be automatically hoisted, so we should not mess with it.
// The exception here is switch blocks, where we can have multiple edges to merge block,
// all coming from same scope, so be more conservative in this case.
// Adding fake branches unconditionally breaks parameter preservation analysis,
// which looks at how variables are accessed through the CFG.
if (this.preceding_edges.hasOwnProperty(block.next_block))
{
const pred_itr_second = this.preceding_edges[block.next_block];
const pred = pred_itr_second;
let num_succeeding_edges = 0;
if (this.succeeding_edges.hasOwnProperty(block_id))
num_succeeding_edges = this.succeeding_edges[block_id].length;
if (block.terminator === SPIRBlockTerminator.MultiSelect && num_succeeding_edges === 1)
{
// Multiple branches can come from the same scope due to "break;", so we need to assume that all branches
// come from same case scope in worst case, even if there are multiple preceding edges.
// If we have more than one succeeding edge from the block header, it should be impossible
// to have a dominator be inside the block.
// Only case this can go wrong is if we have 2 or more edges from block header and
// 2 or more edges to merge block, and still have dominator be inside a case label.
if (pred.length === 0)
this.add_branch(block_id, block.next_block);
}
else
{
if (pred.length === 1 && pred[0] !== block_id)
this.add_branch(block_id, block.next_block);
}
}
else
{
// If the merge block does not have any preceding edges, i.e. unreachable, hallucinate it.
// We're going to do code-gen for it, and domination analysis requires that we have at least one preceding edge.
this.add_branch(block_id, block.next_block);
}
}
// Then visit ourselves. Start counting at one, to let 0 be a magic value for testing back vs. crossing edges.
maplike_get(VisitOrder, this.visit_order, block_id).set(++this.visit_count);
this.post_order.push(block_id);
return true;
}
private is_back_edge(to: number): boolean
{
// We have a back edge if the visit order is set with the temporary magic value 0.
// Crossing edges will have already been recorded with a visit order.
return this.visit_order.hasOwnProperty(to) && this.visit_order[to].get() === 0;
}
private has_visited_forward_edge(to: number): boolean
{
// If > 0, we have visited the edge already, and this is not a back edge branch.
return this.visit_order.hasOwnProperty(to) && this.visit_order[to].get() > 0;
}
}
|
DerSchmale/spirv4web
|
src/spirv/SelectionControlMask.ts
|
export enum SelectionControlMask {
None = 0,
Flatten = 0x00000001,
DontFlatten = 0x00000002,
}
|
DerSchmale/spirv4web
|
build/types/compiler/BufferPackingStandard.d.ts
|
export declare enum BufferPackingStandard {
Std140 = 0,
Std430 = 1,
Std140EnhancedLayout = 2,
Std430EnhancedLayout = 3,
_HLSLCbuffer = 4,
_HLSLCbufferPackOffset = 5,
PackingScalar = 6,
PackingScalarEnhancedLayout = 7
}
|
DerSchmale/spirv4web
|
src/spirv/RayQueryCandidateIntersectionType.ts
|
<gh_stars>0
export enum RayQueryCandidateIntersectionType {
RayQueryCandidateIntersectionTriangleKHR = 0,
RayQueryCandidateIntersectionAABBKHR = 1,
Max = 0x7fffffff,
}
|
DerSchmale/spirv4web
|
src/spirv/FunctionControlShift.ts
|
export enum FunctionControlShift {
Inline = 0,
DontInline = 1,
Pure = 2,
Const = 3,
Max = 0x7fffffff,
}
|
DerSchmale/spirv4web
|
src/common/Bitset.ts
|
// @ts-ignore
import { compare } from "@derschmale/array-utils"
import { defaultClone } from "../utils/defaultCopy";
import { set_compare } from "../utils/set_compare";
export class Bitset
{
// The most common bits to set are all lower than 64,
// so optimize for this case. Bits spilling outside 64 go into a slower data structure.
// In almost all cases, higher data structure will not be used.
private lower: number;
private higher: Set<number> = new Set();
constructor(lower: number = 0)
{
this.lower = lower;
}
get(bit: number): boolean
{
if (bit < 32)
return (this.lower & (1 << bit)) !== 0;
else
return this.higher.has(bit);
}
set(bit: number)
{
if (bit < 32)
this.lower |= 1 << bit;
else
this.higher.add(bit);
}
clear(bit: number)
{
if (bit < 32)
this.lower &= ~(1 << bit);
else
this.higher.delete(bit);
}
get_lower()
{
return this.lower;
}
reset()
{
this.lower = 0;
this.higher.clear();
}
merge_and(other: Bitset)
{
this.lower &= other.lower;
const tmp_set = new Set<number>();
this.higher.forEach(v => {
if (other.higher.has(v))
tmp_set.add(v);
});
this.higher = tmp_set;
}
merge_or(other: Bitset)
{
this.lower |= other.lower;
other.higher.forEach(v => this.higher.add(v));
}
equals(other: Bitset)
{
if (this.lower !== other.lower)
return false;
return set_compare(this.higher, other.higher);
}
for_each_bit(op: (i: number) => void)
{
// TODO: Add ctz-based iteration.
for (let i = 0; i < 32; i++)
{
if (this.lower & (1 << i))
op(i);
}
if (this.higher.size === 0)
return;
// Need to enforce an order here for reproducible results,
// but hitting this path should happen extremely rarely, so having this slow path is fine.
const bits = Array.from(this.higher);
bits.sort();
bits.forEach(op);
}
empty(): boolean
{
return this.lower === 0 && this.higher.size === 0;
}
clone(): Bitset
{
return defaultClone(Bitset, this);
}
}
|
DerSchmale/spirv4web
|
build/types/spirv/Dim.d.ts
|
<filename>build/types/spirv/Dim.d.ts
export declare enum Dim {
Dim1D = 0,
Dim2D = 1,
Dim3D = 2,
Cube = 3,
Rect = 4,
Buffer = 5,
SubpassData = 6,
Max = 2147483647
}
|
DerSchmale/spirv4web
|
src/spirv/SamplerAddressingMode.ts
|
<gh_stars>0
export enum SamplerAddressingMode
{
None = 0,
ClampToEdge = 1,
Clamp = 2,
Repeat = 3,
RepeatMirrored = 4,
Max = 0x7fffffff,
}
|
DerSchmale/spirv4web
|
build/types/common/SPIRBlock.d.ts
|
<filename>build/types/common/SPIRBlock.d.ts
import { IVariant } from "./IVariant";
import { Types } from "./Types";
import { Instruction } from "./Instruction";
import { Pair } from "../utils/Pair";
export declare enum SPIRBlockTerminator {
Unknown = 0,
Direct = 1,
Select = 2,
MultiSelect = 3,
Return = 4,
Unreachable = 5,
Kill = 6,
IgnoreIntersection = 7,
TerminateRay = 8
}
export declare enum SPIRBlockMerge {
None = 0,
Loop = 1,
Selection = 2
}
export declare enum SPIRBlockHints {
None = 0,
Unroll = 1,
DontUnroll = 2,
Flatten = 3,
DontFlatten = 4
}
export declare enum SPIRBlockMethod {
MergeToSelectForLoop = 0,
MergeToDirectForLoop = 1,
MergeToSelectContinueForLoop = 2
}
export declare enum SPIRBlockContinueBlockType {
ContinueNone = 0,
ForLoop = 1,
WhileLoop = 2,
DoWhileLoop = 3,
ComplexLoop = 4
}
export declare class SPIRBlockPhi {
local_variable: ID;
parent: BlockID;
function_variable: BlockID;
clone(): SPIRBlockPhi;
constructor(local_variable?: ID, parent?: BlockID, function_variable?: BlockID);
}
export declare class SPIRBlockCase {
value: bigint;
block: BlockID;
clone(): SPIRBlockCase;
constructor();
constructor(value: bigint, block: BlockID);
}
export declare class SPIRBlock extends IVariant {
static type: Types;
static NoDominator: number;
terminator: SPIRBlockTerminator;
merge: SPIRBlockMerge;
hint: SPIRBlockHints;
next_block: BlockID;
merge_block: BlockID;
continue_block: BlockID;
return_value: ID;
condition: ID;
true_block: BlockID;
false_block: BlockID;
default_block: BlockID;
ops: Instruction[];
phi_variables: SPIRBlockPhi[];
declare_temporary: Pair<TypeID, ID>[];
potential_declare_temporary: Pair<TypeID, ID>[];
cases_32bit: SPIRBlockCase[];
cases_64bit: SPIRBlockCase[];
disable_block_optimization: boolean;
complex_continue: boolean;
need_ladder_break: boolean;
ignore_phi_from_block: BlockID;
loop_dominator: BlockID;
dominated_variables: VariableID[];
loop_variables: VariableID[];
invalidate_expressions: ID[];
constructor(other?: SPIRBlock);
}
|
DerSchmale/spirv4web
|
build/types/utils/defaultCopy.d.ts
|
import { DefaultConstructor } from "../common/ConstructorTypes";
export declare function defaultCopy<T>(src: T, dst: T): void;
export declare function defaultClone<T>(classRef: DefaultConstructor<T>, src: T): T;
|
DerSchmale/spirv4web
|
src/compiler/CombinedImageSampler.ts
|
<reponame>DerSchmale/spirv4web<filename>src/compiler/CombinedImageSampler.ts
export class CombinedImageSampler
{
// The ID of the sampler2D variable.
combined_id: VariableID;
// The ID of the texture2D variable.
image_id: VariableID;
// The ID of the sampler variable.
sampler_id: VariableID;
constructor(combined_id: VariableID, image_id: VariableID, sampler_id: VariableID)
{
this.combined_id = combined_id;
this.image_id = image_id;
this.sampler_id = sampler_id;
}
}
|
DerSchmale/spirv4web
|
build/types/spirv/MemoryModel.d.ts
|
export declare enum MemoryModel {
Simple = 0,
GLSL450 = 1,
OpenCL = 2,
Vulkan = 3,
VulkanKHR = 3,
Max = 2147483647
}
|
DerSchmale/spirv4web
|
build/types/compiler/StaticExpressionAccessHandler.d.ts
|
import { OpcodeHandler } from "./OpcodeHandler";
import { Compiler } from "./Compiler";
import { SPIRFunction } from "../common/SPIRFunction";
import { Op } from "../spirv/Op";
export declare class StaticExpressionAccessHandler extends OpcodeHandler {
compiler: Compiler;
variable_id: number;
static_expression: number;
write_count: number;
constructor(compiler: Compiler, variable_id: number);
follow_function_call(_: SPIRFunction): boolean;
handle(opcode: Op, args: Uint32Array, length: number): boolean;
}
|
DerSchmale/spirv4web
|
src/compiler/ActiveBuiltinHandler.ts
|
import { OpcodeHandler } from "./OpcodeHandler";
import { Compiler } from "./Compiler";
import { Bitset } from "../common/Bitset";
import { SPIRType } from "../common/SPIRType";
import { SPIRVariable } from "../common/SPIRVariable";
import { BuiltIn } from "../spirv/BuiltIn";
import { Op } from "../spirv/Op";
import { Decoration } from "../spirv/Decoration";
import { StorageClass } from "../spirv/StorageClass";
export class ActiveBuiltinHandler extends OpcodeHandler
{
compiler: Compiler;
constructor(compiler: Compiler)
{
super();
this.compiler = compiler;
}
handle(opcode: Op, args: Uint32Array, length: number): boolean
{
return false;
}
handle_builtin(type: SPIRType, builtin: BuiltIn, decoration_flags: Bitset)
{
// If used, we will need to explicitly declare a new array size for these builtins.
if (builtin === BuiltIn.ClipDistance) {
if (!type.array_size_literal[0])
throw new Error("Array size for ClipDistance must be a literal.");
const array_size = type.array[0];
if (array_size === 0)
throw new Error("Array size for ClipDistance must not be unsized.");
this.compiler.clip_distance_count = array_size;
}
else if (builtin === BuiltIn.CullDistance) {
if (!type.array_size_literal[0])
throw new Error("Array size for CullDistance must be a literal.");
const array_size = type.array[0];
if (array_size === 0)
throw new Error("Array size for CullDistance must not be unsized.");
this.compiler.cull_distance_count = array_size;
}
else if (builtin === BuiltIn.Position) {
if (decoration_flags.get(Decoration.Invariant))
this.compiler.position_invariant = true;
}
}
add_if_builtin_or_block(id: number)
{
this.add_if_builtin(id, true);
}
add_if_builtin(id: number, allow_blocks: boolean = false)
{
// Only handle plain variables here.
// Builtins which are part of a block are handled in AccessChain.
// If allow_blocks is used however, this is to handle initializers of blocks,
// which implies that all members are written to.
const compiler = this.compiler;
const var_ = compiler.maybe_get<SPIRVariable>(SPIRVariable, id);
const m = compiler.ir.find_meta(id);
if (var_ && m)
{
const type = compiler.get<SPIRType>(SPIRType, var_.basetype);
const decorations = m.decoration;
const flags = type.storage === StorageClass.Input ?
compiler.active_input_builtins : compiler.active_output_builtins;
if (decorations.builtin)
{
flags.set(decorations.builtin_type);
this.handle_builtin(type, decorations.builtin_type, decorations.decoration_flags);
}
else if (allow_blocks && compiler.has_decoration(type.self, Decoration.Block))
{
const member_count = type.member_types.length;
for (let i = 0; i < member_count; i++)
{
if (compiler.has_member_decoration(type.self, i, Decoration.BuiltIn))
{
const member_type = compiler.get<SPIRType>(SPIRType, type.member_types[i]);
const builtin = <BuiltIn>(compiler.get_member_decoration(type.self, i, Decoration.BuiltIn));
flags.set(builtin);
this.handle_builtin(member_type, builtin, compiler.get_member_decoration_bitset(type.self, i));
}
}
}
}
}
}
|
DerSchmale/spirv4web
|
src/spirv/ImageOperandsMask.ts
|
<filename>src/spirv/ImageOperandsMask.ts
export enum ImageOperandsMask {
None = 0,
Bias = 0x00000001,
Lod = 0x00000002,
Grad = 0x00000004,
ConstOffset = 0x00000008,
Offset = 0x00000010,
ConstOffsets = 0x00000020,
Sample = 0x00000040,
MinLod = 0x00000080,
MakeTexelAvailable = 0x00000100,
MakeTexelAvailableKHR = 0x00000100,
MakeTexelVisible = 0x00000200,
MakeTexelVisibleKHR = 0x00000200,
NonPrivateTexel = 0x00000400,
NonPrivateTexelKHR = 0x00000400,
VolatileTexel = 0x00000800,
VolatileTexelKHR = 0x00000800,
SignExtend = 0x00001000,
ZeroExtend = 0x00002000,
}
|
DerSchmale/spirv4web
|
build/types/compiler/glsl/GLSLFragmentOptions.d.ts
|
<filename>build/types/compiler/glsl/GLSLFragmentOptions.d.ts
import { GLSLPrecision } from "./GLSLPrecision";
export declare class GLSLFragmentOptions {
default_float_precision: GLSLPrecision;
default_int_precision: GLSLPrecision;
}
|
DerSchmale/spirv4web
|
src/common/SPIRExpression.ts
|
import { IVariant } from "./IVariant";
import { Types } from "./Types";
import { defaultCopy } from "../utils/defaultCopy";
export class SPIRExpression extends IVariant
{
static type = Types.Expression;
// If non-zero, prepend expression with to_expression(base_expression).
// Used in amortizing multiple calls to to_expression()
// where in certain cases that would quickly force a temporary when not needed.
base_expression: ID = 0;
expression: string = "";
expression_type: TypeID = 0;
// If this expression is a forwarded load,
// allow us to reference the original variable.
loaded_from: ID = 0;
// If this expression will never change, we can avoid lots of temporaries
// in high level source.
// An expression being immutable can be speculative,
// it is assumed that this is true almost always.
immutable: boolean = false;
// Before use, this expression must be transposed.
// This is needed for targets which don't support row_major layouts.
need_transpose: boolean = false;
// Whether or not this is an access chain expression.
access_chain: boolean = false;
// A list of expressions which this expression depends on.
expression_dependencies: ID[] = [];
// By reading this expression, we implicitly read these expressions as well.
// Used by access chain Store and Load since we read multiple expressions in this case.
implied_read_expressions: ID[] = [];
// The expression was emitted at a certain scope. Lets us track when an expression read means multiple reads.
emitted_loop_level: number = 0;
// Only created by the backend target to avoid creating tons of temporaries.
constructor(other: SPIRExpression);
constructor(expr: string, expression_type: TypeID, immutable: boolean);
constructor(param0: string | SPIRExpression = "", expression_type?: TypeID, immutable?: boolean)
{
super();
if (param0 instanceof SPIRExpression) {
defaultCopy(param0, this);
}
else {
this.expression = param0;
this.expression_type = expression_type;
this.immutable = immutable;
}
}
}
|
DerSchmale/spirv4web
|
build/types/compiler/PhysicalStorageBufferPointerHandler.d.ts
|
import { OpcodeHandler } from "./OpcodeHandler";
import { Compiler } from "./Compiler";
import { PhysicalBlockMeta } from "./PhysicalBlockMeta";
import { SPIRType } from "../common/SPIRType";
import { Op } from "../spirv/Op";
export declare class PhysicalStorageBufferPointerHandler extends OpcodeHandler {
compiler: Compiler;
non_block_types: Set<number>;
physical_block_type_meta: PhysicalBlockMeta[];
access_chain_to_physical_block: PhysicalBlockMeta[];
constructor(compiler: Compiler);
handle(op: Op, args: Uint32Array, length: number): boolean;
mark_aligned_access(id: number, args: Uint32Array, length: number): void;
find_block_meta(id: number): PhysicalBlockMeta;
type_is_bda_block_entry(type_id: number): boolean;
setup_meta_chain(type_id: number, var_id: number): void;
get_minimum_scalar_alignment(type: SPIRType): number;
analyze_non_block_types_from_block(type: SPIRType): void;
get_base_non_block_type_id(type_id: number): number;
}
|
DerSchmale/spirv4web
|
src/compiler/glsl/ExtraSubExpressionType.ts
|
<filename>src/compiler/glsl/ExtraSubExpressionType.ts
export enum ExtraSubExpressionType
{
// Create masks above any legal ID range to allow multiple address spaces into the extra_sub_expressions map.
STREAM_OFFSET = 0x10000000,
TYPE_AUX = 0x20000000
}
|
DerSchmale/spirv4web
|
src/spirv/SourceLanguage.ts
|
<gh_stars>0
export enum SourceLanguage {
Unknown = 0,
ESSL = 1,
GLSL = 2,
OpenCL_C = 3,
OpenCL_CPP = 4,
HLSL = 5,
Max = 0x7fffffff,
}
|
DerSchmale/spirv4web
|
src/containers/ObjectPoolBase.ts
|
import { FromConstructor } from "../common/ConstructorTypes";
export abstract class ObjectPoolBase
{
abstract deallocate_opaque(ptr: any);
}
|
DerSchmale/spirv4web
|
src/common/ConstructorTypes.ts
|
// this is a stand-in for copy-constructors etc
export type FromConstructor<T> = { from(...params): T }
export type DefaultConstructor<T> = { new(): T }
export type AnyConstructor<T> = { new(...args): T }
|
DerSchmale/spirv4web
|
build/types/spirv/RayFlagsMask.d.ts
|
<reponame>DerSchmale/spirv4web
export declare enum RayFlagsMask {
None = 0,
OpaqueKHR = 1,
NoOpaqueKHR = 2,
TerminateOnFirstHitKHR = 4,
SkipClosestHitShaderKHR = 8,
CullBackFacingTrianglesKHR = 16,
CullFrontFacingTrianglesKHR = 32,
CullOpaqueKHR = 64,
CullNoOpaqueKHR = 128,
SkipTrianglesKHR = 256,
SkipAABBsKHR = 512
}
|
DerSchmale/spirv4web
|
src/common/SPIRType.ts
|
<reponame>DerSchmale/spirv4web
import { IVariant } from "./IVariant";
import { Types } from "./Types";
import { defaultClone, defaultCopy } from "../utils/defaultCopy";
import { Dim } from "../spirv/Dim";
import { ImageFormat } from "../spirv/ImageFormat";
import { AccessQualifier } from "../spirv/AccessQualifier";
import { StorageClass } from "../spirv/StorageClass";
export enum SPIRBaseType
{
Unknown,
Void,
Boolean,
SByte,
UByte,
Short,
UShort,
Int,
UInt,
Int64,
UInt64,
AtomicCounter,
Half,
Float,
Double,
Struct,
Image,
SampledImage,
Sampler,
AccelerationStructure,
RayQuery,
// Keep internal types at the end.
ControlPointArray,
Interpolant,
Char
}
export class SPIRTypeImageType
{
type: TypeID;
dim: Dim;
depth: boolean;
arrayed: boolean;
ms: boolean;
sampled: number;
format: ImageFormat;
access: AccessQualifier;
clone() { return defaultClone(SPIRTypeImageType, this); }
equals(b: SPIRTypeImageType): boolean
{
return this.type === b.type && this.dim === b.dim && this.depth === b.depth && this.arrayed === b.arrayed &&
this.ms === b.ms && this.sampled === b.sampled && this.format === b.format && this.access === b.access;
}
}
export class SPIRType extends IVariant
{
static type = Types.Type;
// Scalar/vector/matrix support.
basetype: SPIRBaseType = SPIRBaseType.Unknown;
width: number = 0;
vecsize: number = 1;
columns: number = 1;
// Arrays, support array of arrays by having a vector of array sizes.
array: number[] = [];
// Array elements can be either specialization constants or specialization ops.
// This array determines how to interpret the array size.
// If an element is true, the element is a literal,
// otherwise, it's an expression, which must be resolved on demand.
// The actual size is not really known until runtime.
array_size_literal: boolean[] = [];
// Pointers
// Keep track of how many pointer layers we have.
pointer_depth: number = 0;
pointer: boolean = false;
forward_pointer: boolean = false;
storage: StorageClass = StorageClass.Generic;
member_types: TypeID[] = [];
// If member order has been rewritten to handle certain scenarios with Offset,
// allow codegen to rewrite the index.
member_type_index_redirection: number[] = [];
image: SPIRTypeImageType = new SPIRTypeImageType();
// Structs can be declared multiple times if they are used as part of interface blocks.
// We want to detect this so that we only emit the struct definition once.
// Since we cannot rely on OpName to be equal, we need to figure out aliases.
type_alias: TypeID = 0;
// Denotes the type which this type is based on.
// Allows the backend to traverse how a complex type is built up during access chains.
parent_type: TypeID = 0;
// Used in backends to avoid emitting members with conflicting names.
member_name_cache: Set<string> = new Set<string>();
constructor(other?: SPIRType)
{
super();
if (other)
defaultCopy(other, this);
}
}
|
DerSchmale/spirv4web
|
build/types/main.d.ts
|
import { Dict } from "./utils/Dict";
/**
* The target driver version to use.
*/
export declare enum Version {
WebGL1 = 100,
WebGL2 = 300
}
/**
* The available options.
*/
export declare type Options = {
/**
* Removes unused variables. Defaults to true.
*/
removeUnused?: boolean;
/**
* Specialization constants will be converted to `#define` macros. This allows setting a custom prefix for the
* macro names (defaults to `SPIRV_CROSS_CONSTANT_ID_`).
*/
specializationConstantPrefix?: string;
/**
* This keeps unnamed uniform blocks. If `false`, UBOs will have a temporary name assigned to them.
* If `true`, in WebGL 1, this will turn the members of unnamed uniform buffers into global uniforms. Defaults to
* `true`.
*/
keepUnnamedUBOs?: boolean;
/**
* If keepUnnamedUBOs === true and UBOs are not supported, this map is used to store the removed
* ubos and their members names. This can be used to implement UBO fallbacks on the shader.
*/
unnamedUBOInfo?: Dict<string[]>;
/**
* (WebGL2 only) Strips layout information from vertex attributes. This is useful when you've defined more
* attributes than supported (Depending on `gl.MAX_VERTEX_ATTRIBS`) but not all of them are used. You'll then need
* to query the attribute locations by name. Defaults to `false`.
*/
removeAttributeLayouts?: boolean;
/**
* Tries to use preprocessor macros as much as possible to handle specialization constants.
*/
preprocess_spec_const?: boolean;
};
/**
* Compiles Spir-V bytecode to GLSL.
* @param data An ArrayBuffer containing valid Spir-V bytecode.
* @param version Either `Version.WebGL1` or `Version.WebGL2`.
* @param options An optional object containing optional fields defined in Options.
*/
export declare function compile(data: ArrayBuffer, version: Version, options?: Options): string;
|
DerSchmale/spirv4web
|
build/types/spirv/ImageOperandsShift.d.ts
|
export declare enum ImageOperandsShift {
Bias = 0,
Lod = 1,
Grad = 2,
ConstOffset = 3,
Offset = 4,
ConstOffsets = 5,
Sample = 6,
MinLod = 7,
MakeTexelAvailable = 8,
MakeTexelAvailableKHR = 8,
MakeTexelVisible = 9,
MakeTexelVisibleKHR = 9,
NonPrivateTexel = 10,
NonPrivateTexelKHR = 10,
VolatileTexel = 11,
VolatileTexelKHR = 11,
SignExtend = 12,
ZeroExtend = 13,
Max = 2147483647
}
|
DerSchmale/spirv4web
|
src/spirv/RayFlagsMask.ts
|
<reponame>DerSchmale/spirv4web<filename>src/spirv/RayFlagsMask.ts<gh_stars>0
export enum RayFlagsMask {
None = 0,
OpaqueKHR = 0x00000001,
NoOpaqueKHR = 0x00000002,
TerminateOnFirstHitKHR = 0x00000004,
SkipClosestHitShaderKHR = 0x00000008,
CullBackFacingTrianglesKHR = 0x00000010,
CullFrontFacingTrianglesKHR = 0x00000020,
CullOpaqueKHR = 0x00000040,
CullNoOpaqueKHR = 0x00000080,
SkipTrianglesKHR = 0x00000100,
SkipAABBsKHR = 0x00000200,
}
|
DerSchmale/spirv4web
|
build/types/compiler/CombinedImageSamplerUsageHandler.d.ts
|
<reponame>DerSchmale/spirv4web<filename>build/types/compiler/CombinedImageSamplerUsageHandler.d.ts
import { OpcodeHandler } from "./OpcodeHandler";
import { Compiler } from "./Compiler";
import { Op } from "../spirv/Op";
export declare class CombinedImageSamplerUsageHandler extends OpcodeHandler {
compiler: Compiler;
dref_combined_samplers: Set<number>;
dependency_hierarchy: Set<number>[];
comparison_ids: Set<number>;
need_subpass_input: boolean;
constructor(compiler: Compiler, dref_combined_samplers: Set<number>);
begin_function_scope(args: Uint32Array, length: number): boolean;
handle(opcode: Op, args: Uint32Array, length: number): boolean;
add_hierarchy_to_comparison_ids(id: number): void;
add_dependency(dst: number, src: number): void;
}
|
DerSchmale/spirv4web
|
src/compiler/EntryPoint.ts
|
import { ExecutionModel } from "../spirv/ExecutionModel";
export class EntryPoint
{
name: string;
execution_model: ExecutionModel;
constructor(name: string, model: ExecutionModel)
{
this.name = name;
this.execution_model = model;
}
}
|
DerSchmale/spirv4web
|
src/cfg/DominatorBuilder.ts
|
import { CFG } from "./CFG";
import { SPIRBlock, SPIRBlockTerminator } from "../common/SPIRBlock";
export class DominatorBuilder
{
private cfg: CFG;
private dominator: number = 0;
constructor(cfg: CFG)
{
this.cfg = cfg;
}
add_block(block: number)
{
if (!this.cfg.get_immediate_dominator(block))
{
// Unreachable block via the CFG, we will never emit this code anyways.
return;
}
if (!this.dominator)
{
this.dominator = block;
return;
}
if (block !== this.dominator)
this.dominator = this.cfg.find_common_dominator(block, this.dominator);
}
get_dominator(): number
{
return this.dominator;
}
lift_continue_block_dominator()
{
// It is possible for a continue block to be the dominator of a variable is only accessed inside the while block of a do-while loop.
// We cannot safely declare variables inside a continue block, so move any variable declared
// in a continue block to the entry block to simplify.
// It makes very little sense for a continue block to ever be a dominator, so fall back to the simplest
// solution.
if (!this.dominator)
return;
const cfg = this.cfg;
const block = cfg.get_compiler().get<SPIRBlock>(SPIRBlock, this.dominator);
const post_order = cfg.get_visit_order(this.dominator);
// If we are branching to a block with a higher post-order traversal index (continue blocks), we have a problem
// since we cannot create sensible GLSL code for this, fallback to entry block.
let back_edge_dominator = false;
switch (block.terminator)
{
case SPIRBlockTerminator.Direct:
if (cfg.get_visit_order(block.next_block) > post_order)
back_edge_dominator = true;
break;
case SPIRBlockTerminator.Select:
if (cfg.get_visit_order(block.true_block) > post_order)
back_edge_dominator = true;
if (cfg.get_visit_order(block.false_block) > post_order)
back_edge_dominator = true;
break;
case SPIRBlockTerminator.MultiSelect:
{
const cases = cfg.get_compiler().get_case_list(block);
for (let target of cases)
{
if (cfg.get_visit_order(target.block) > post_order)
back_edge_dominator = true;
}
if (block.default_block && cfg.get_visit_order(block.default_block) > post_order)
back_edge_dominator = true;
break;
}
default:
break;
}
if (back_edge_dominator)
this.dominator = cfg.get_function().entry_block;
}
}
|
DerSchmale/spirv4web
|
build/types/compileIteration.d.ts
|
<filename>build/types/compileIteration.d.ts
import { Args } from "./Args";
import { Dict } from "./utils/Dict";
export declare function compile_iteration(args: Args, spirv_file: Uint32Array, unnamedUBOInfo: Dict<string[]>): string;
|
DerSchmale/spirv4web
|
src/compiler/InterlockedResourceAccessHandler.ts
|
<filename>src/compiler/InterlockedResourceAccessHandler.ts
import { OpcodeHandler } from "./OpcodeHandler";
import { Compiler } from "./Compiler";
import { SPIRExpression } from "../common/SPIRExpression";
import { SPIRType } from "../common/SPIRType";
import { Op } from "../spirv/Op";
import { StorageClass } from "../spirv/StorageClass";
import { Decoration } from "../spirv/Decoration";
export class InterlockedResourceAccessHandler extends OpcodeHandler
{
compiler: Compiler;
in_crit_sec: boolean = false;
interlock_function_id: number = 0;
split_function_case: boolean = false;
control_flow_interlock: boolean = false;
use_critical_section: boolean = false;
call_stack_is_interlocked: boolean = false;
call_stack: number[] = [];
constructor(compiler: Compiler, entry_point_id: number)
{
super();
this.compiler = compiler;
this.call_stack.push(entry_point_id);
}
handle(opcode: Op, args: Uint32Array, length: number): boolean
{
// Only care about critical section analysis if we have simple case.
if (this.use_critical_section) {
if (opcode === Op.BeginInvocationInterlockEXT) {
this.in_crit_sec = true;
return true;
}
if (opcode === Op.EndInvocationInterlockEXT) {
// End critical section--nothing more to do.
return false;
}
}
const compiler = this.compiler;
// We need to figure out where images and buffers are loaded from, so do only the bare bones compilation we need.
switch (opcode) {
case Op.Load: {
if (length < 3)
return false;
const ptr = args[2];
const var_ = this.compiler.maybe_get_backing_variable(ptr);
// We're only concerned with buffer and image memory here.
if (!var_)
break;
switch (var_.storage) {
default:
break;
case StorageClass.UniformConstant: {
const result_type = args[0];
const id = args[1];
compiler.set<SPIRExpression>(SPIRExpression, id, "", result_type, true);
compiler.register_read(id, ptr, true);
break;
}
case StorageClass.Uniform:
// Must have BufferBlock; we only care about SSBOs.
if (!compiler.has_decoration(compiler.get<SPIRType>(SPIRType, var_.basetype).self, Decoration.BufferBlock))
break;
// fallthrough
case StorageClass.StorageBuffer:
this.access_potential_resource(var_.self);
break;
}
break;
}
case Op.InBoundsAccessChain:
case Op.AccessChain:
case Op.PtrAccessChain: {
if (length < 3)
return false;
const result_type = args[0];
const type = compiler.get<SPIRType>(SPIRType, result_type);
if (type.storage === StorageClass.Uniform || type.storage === StorageClass.UniformConstant ||
type.storage === StorageClass.StorageBuffer) {
const id = args[1];
const ptr = args[2];
compiler.set<SPIRExpression>(SPIRExpression, id, "", result_type, true);
compiler.register_read(id, ptr, true);
compiler.ir.ids[id].set_allow_type_rewrite();
}
break;
}
case Op.ImageTexelPointer: {
if (length < 3)
return false;
const result_type = args[0];
const id = args[1];
const ptr = args[2];
const e = compiler.set<SPIRExpression>(SPIRExpression, id, "", result_type, true);
const var_ = compiler.maybe_get_backing_variable(ptr);
if (var_)
e.loaded_from = var_.self;
break;
}
case Op.Store:
case Op.ImageWrite:
case Op.AtomicStore: {
if (length < 1)
return false;
const ptr = args[0];
const var_ = compiler.maybe_get_backing_variable(ptr);
if (var_ && (var_.storage === StorageClass.Uniform || var_.storage === StorageClass.UniformConstant ||
var_.storage === StorageClass.StorageBuffer)) {
this.access_potential_resource(var_.self);
}
break;
}
case Op.CopyMemory: {
if (length < 2)
return false;
const dst = args[0];
const src = args[1];
const dst_var = compiler.maybe_get_backing_variable(dst);
const src_var = compiler.maybe_get_backing_variable(src);
if (dst_var && (dst_var.storage === StorageClass.Uniform || dst_var.storage === StorageClass.StorageBuffer))
this.access_potential_resource(dst_var.self);
if (src_var) {
if (src_var.storage !== StorageClass.Uniform && src_var.storage !== StorageClass.StorageBuffer)
break;
if (src_var.storage === StorageClass.Uniform &&
!compiler.has_decoration(compiler.get<SPIRType>(SPIRType, src_var.basetype).self, Decoration.BufferBlock)) {
break;
}
this.access_potential_resource(src_var.self);
}
break;
}
case Op.ImageRead:
case Op.AtomicLoad: {
if (length < 3)
return false;
const ptr = args[2];
const var_ = compiler.maybe_get_backing_variable(ptr);
// We're only concerned with buffer and image memory here.
if (!var_)
break;
switch (var_.storage) {
default:
break;
case StorageClass.Uniform:
// Must have BufferBlock; we only care about SSBOs.
if (!compiler.has_decoration(compiler.get<SPIRType>(SPIRType, var_.basetype).self, Decoration.BufferBlock))
break;
// fallthrough
case StorageClass.UniformConstant:
case StorageClass.StorageBuffer:
this.access_potential_resource(var_.self);
break;
}
break;
}
case Op.AtomicExchange:
case Op.AtomicCompareExchange:
case Op.AtomicIIncrement:
case Op.AtomicIDecrement:
case Op.AtomicIAdd:
case Op.AtomicISub:
case Op.AtomicSMin:
case Op.AtomicUMin:
case Op.AtomicSMax:
case Op.AtomicUMax:
case Op.AtomicAnd:
case Op.AtomicOr:
case Op.AtomicXor: {
if (length < 3)
return false;
const ptr = args[2];
const var_ = compiler.maybe_get_backing_variable(ptr);
if (var_ && (var_.storage === StorageClass.Uniform || var_.storage === StorageClass.UniformConstant ||
var_.storage === StorageClass.StorageBuffer)) {
this.access_potential_resource(var_.self);
}
break;
}
default:
break;
}
return true;
}
begin_function_scope(args: Uint32Array, length: number): boolean
{
if (length < 3)
return false;
if (args[2] === this.interlock_function_id)
this.call_stack_is_interlocked = true;
this.call_stack.push(args[2]);
return true;
}
end_function_scope(args: Uint32Array, length: number): boolean
{
if (this.call_stack[this.call_stack.length - 1] === this.interlock_function_id)
this.call_stack_is_interlocked = false;
this.call_stack.pop();
return true;
}
access_potential_resource(id: number)
{
if ((this.use_critical_section && this.in_crit_sec) || (this.control_flow_interlock && this.call_stack_is_interlocked) ||
this.split_function_case) {
this.compiler.interlocked_resources.add(id);
}
}
}
|
DerSchmale/spirv4web
|
src/spirv/AddressingModel.ts
|
export enum AddressingModel {
Logical = 0,
Physical32 = 1,
Physical64 = 2,
PhysicalStorageBuffer64 = 5348,
PhysicalStorageBuffer64EXT = 5348,
Max = 0x7fffffff,
}
|
DerSchmale/spirv4web
|
src/compiler/CombinedImageSamplerUsageHandler.ts
|
import { OpcodeHandler } from "./OpcodeHandler";
import { Compiler } from "./Compiler";
import { maplike_get } from "../utils/maplike_get";
import { SPIRFunction } from "../common/SPIRFunction";
import { Op } from "../spirv/Op";
export class CombinedImageSamplerUsageHandler extends OpcodeHandler
{
compiler: Compiler;
dref_combined_samplers: Set<number> = new Set();
dependency_hierarchy: Set<number>[] = []; // map<uint32_t, set<uint32_t>>
comparison_ids: Set<number> = new Set();
need_subpass_input: boolean = false;
constructor(compiler: Compiler, dref_combined_samplers: Set<number>)
{
super();
this.compiler = compiler;
this.dref_combined_samplers = dref_combined_samplers;
}
begin_function_scope(args: Uint32Array, length: number): boolean
{
if (length < 3)
return false;
const func = this.compiler.get<SPIRFunction>(SPIRFunction, args[2]);
const offset = 3;
length -= 3;
for (let i = 0; i < length; i++)
{
const argument = func.arguments[i];
this.add_dependency(argument.id, args[offset + i]);
}
return true;
}
handle(opcode: Op, args: Uint32Array, length: number): boolean
{
// Mark all sampled images which are used with Dref.
switch (opcode)
{
case Op.ImageSampleDrefExplicitLod:
case Op.ImageSampleDrefImplicitLod:
case Op.ImageSampleProjDrefExplicitLod:
case Op.ImageSampleProjDrefImplicitLod:
case Op.ImageSparseSampleProjDrefImplicitLod:
case Op.ImageSparseSampleDrefImplicitLod:
case Op.ImageSparseSampleProjDrefExplicitLod:
case Op.ImageSparseSampleDrefExplicitLod:
case Op.ImageDrefGather:
case Op.ImageSparseDrefGather:
this.dref_combined_samplers.add(args[2]);
return true;
default:
break;
}
return true;
}
add_hierarchy_to_comparison_ids(id: number)
{
// Traverse the variable dependency hierarchy and tag everything in its path with comparison ids.
this.comparison_ids.add(id);
maplike_get<Set<number>>(Set, this.dependency_hierarchy, id).forEach(dep_id => this.add_hierarchy_to_comparison_ids(dep_id));
}
add_dependency(dst: number, src: number)
{
maplike_get<Set<number>>(Set, this.dependency_hierarchy, dst).add(src);
// Propagate up any comparison state if we're loading from one such variable.
if (this.comparison_ids.has(src))
this.comparison_ids.add(dst);
}
}
|
DerSchmale/spirv4web
|
build/types/compiler/glsl/AccessChainFlagBits.d.ts
|
export declare enum AccessChainFlagBits {
INDEX_IS_LITERAL_BIT = 1,
CHAIN_ONLY_BIT = 2,
PTR_CHAIN_BIT = 4,
SKIP_REGISTER_EXPRESSION_READ_BIT = 8,
LITERAL_MSB_FORCE_ID = 16,
FLATTEN_ALL_MEMBERS_BIT = 32,
FORCE_COMPOSITE_BIT = 64
}
|
DerSchmale/spirv4web
|
src/compiler/InterfaceVariableAccessHandler.ts
|
<reponame>DerSchmale/spirv4web<gh_stars>0
import { OpcodeHandler } from "./OpcodeHandler";
import { Compiler } from "./Compiler";
import { SPIRVariable } from "../common/SPIRVariable";
import { SPIRExtension, SPIRExtensionExtension } from "../common/SPIRExtension";
import { GLSLstd450 } from "./glsl/glsl";
import { Op } from "../spirv/Op";
import { StorageClass } from "../spirv/StorageClass";
export class InterfaceVariableAccessHandler extends OpcodeHandler
{
compiler: Compiler;
variables: Set<VariableID>;
constructor(compiler: Compiler, variables: Set<VariableID>)
{
super();
this.compiler = compiler;
this.variables = variables;
}
handle(opcode: Op, args: Uint32Array, length: number): boolean
{
const compiler = this.compiler;
const variables = this.variables;
let variable = 0;
let offset = 0;
switch (opcode)
{
// Need this first, otherwise, GCC complains about unhandled switch statements.
default:
break;
case Op.FunctionCall:
{
// Invalid SPIR-V.
if (length < 3)
return false;
const count = length - 3;
offset += 3;
for (let i = 0; i < count; i++)
{
const var_ = compiler.maybe_get<SPIRVariable>(SPIRVariable, args[offset + i]);
if (var_ && storage_class_is_interface(var_.storage))
variables.add(args[offset + i]);
}
break;
}
case Op.Select:
{
// Invalid SPIR-V.
if (length < 5)
return false;
const count = length - 3;
offset += 3;
for (let i = 0; i < count; i++)
{
const var_ = compiler.maybe_get<SPIRVariable>(SPIRVariable, args[offset + i]);
if (var_ && storage_class_is_interface(var_.storage))
variables.add(args[offset + i]);
}
break;
}
case Op.Phi:
{
// Invalid SPIR-V.
if (length < 2)
return false;
const count = length - 2;
offset += 2;
for (let i = 0; i < count; i += 2)
{
const var_ = compiler.maybe_get<SPIRVariable>(SPIRVariable, args[offset + i]);
if (var_ && storage_class_is_interface(var_.storage))
variables.add(args[offset + i]);
}
break;
}
case Op.AtomicStore:
case Op.Store:
// Invalid SPIR-V.
if (length < 1)
return false;
variable = args[offset];
break;
case Op.CopyMemory:
{
if (length < 2)
return false;
let var_ = compiler.maybe_get<SPIRVariable>(SPIRVariable, args[offset]);
if (var_ && storage_class_is_interface(var_.storage))
variables.add(args[offset]);
var_ = compiler.maybe_get<SPIRVariable>(SPIRVariable, args[offset + 1]);
if (var_ && storage_class_is_interface(var_.storage))
variables.add(args[offset + 1]);
break;
}
case Op.ExtInst:
{
if (length < 5)
return false;
const extension_set = compiler.get<SPIRExtension>(SPIRExtension, args[offset + 2]);
switch (extension_set.ext)
{
case SPIRExtensionExtension.GLSL:
{
const op = <GLSLstd450>(args[offset + 3]);
switch (op)
{
case GLSLstd450.InterpolateAtCentroid:
case GLSLstd450.InterpolateAtSample:
case GLSLstd450.InterpolateAtOffset:
{
const var_ = compiler.maybe_get<SPIRVariable>(SPIRVariable, args[offset + 4]);
if (var_ && storage_class_is_interface(var_.storage))
variables.add(args[offset + 4]);
break;
}
case GLSLstd450.Modf:
case GLSLstd450.Fract:
{
const var_ = compiler.maybe_get<SPIRVariable>(SPIRVariable, args[offset + 4]);
if (var_ && storage_class_is_interface(var_.storage))
variables.add(args[offset + 4]);
break;
}
default:
break;
}
break;
}
case SPIRExtensionExtension.SPV_AMD_shader_explicit_vertex_parameter:
{
const InterpolateAtVertexAMD = 1
const op = args[offset + 3];
switch (op)
{
case InterpolateAtVertexAMD:
{
const var_ = compiler.maybe_get<SPIRVariable>(SPIRVariable, args[offset + 4]);
if (var_ && storage_class_is_interface(var_.storage))
variables.add(args[offset + 4]);
break;
}
default:
break;
}
break;
}
default:
break;
}
break;
}
case Op.AccessChain:
case Op.InBoundsAccessChain:
case Op.PtrAccessChain:
case Op.Load:
case Op.CopyObject:
case Op.ImageTexelPointer:
case Op.AtomicLoad:
case Op.AtomicExchange:
case Op.AtomicCompareExchange:
case Op.AtomicCompareExchangeWeak:
case Op.AtomicIIncrement:
case Op.AtomicIDecrement:
case Op.AtomicIAdd:
case Op.AtomicISub:
case Op.AtomicSMin:
case Op.AtomicUMin:
case Op.AtomicSMax:
case Op.AtomicUMax:
case Op.AtomicAnd:
case Op.AtomicOr:
case Op.AtomicXor:
case Op.ArrayLength:
// Invalid SPIR-V.
if (length < 3)
return false;
variable = args[offset + 2];
break;
}
if (variable)
{
const var_ = compiler.maybe_get<SPIRVariable>(SPIRVariable, variable);
if (var_ && storage_class_is_interface(var_.storage))
variables.add(variable);
}
return true;
}
}
function storage_class_is_interface(storage: StorageClass): boolean
{
switch (storage)
{
case StorageClass.Input:
case StorageClass.Output:
case StorageClass.Uniform:
case StorageClass.UniformConstant:
case StorageClass.AtomicCounter:
case StorageClass.PushConstant:
case StorageClass.StorageBuffer:
return true;
default:
return false;
}
}
|
DerSchmale/spirv4web
|
src/common/SPIRCombinedImageSampler.ts
|
import { IVariant } from "./IVariant";
import { Types } from "./Types";
import { defaultCopy } from "../utils/defaultCopy";
export class SPIRCombinedImageSampler extends IVariant
{
static type = Types.CombinedImageSampler;
combined_type: TypeID;
image: VariableID;
sampler: VariableID;
constructor(other: SPIRCombinedImageSampler);
constructor(type: TypeID, image: VariableID, sampler: VariableID)
constructor(param0: TypeID | SPIRCombinedImageSampler, image?: VariableID, sampler?: VariableID)
{
super();
if (param0 instanceof SPIRCombinedImageSampler) {
defaultCopy(param0, this);
}
else {
this.combined_type = param0;
this.image = image;
this.sampler = sampler;
}
}
}
|
DerSchmale/spirv4web
|
build/types/spirv/LoopControlMask.d.ts
|
export declare enum LoopControlMask {
None = 0,
Unroll = 1,
DontUnroll = 2,
DependencyInfinite = 4,
DependencyLength = 8,
MinIterations = 16,
MaxIterations = 32,
IterationMultiple = 64,
PeelCount = 128,
PartialCount = 256,
InitiationIntervalINTEL = 65536,
MaxConcurrencyINTEL = 131072,
DependencyArrayINTEL = 262144,
PipelineEnableINTEL = 524288,
LoopCoalesceINTEL = 1048576,
MaxInterleavingINTEL = 2097152,
SpeculatedIterationsINTEL = 4194304
}
|
DerSchmale/spirv4web
|
build/types/spirv/MemoryAccessMask.d.ts
|
export declare enum MemoryAccessMask {
None = 0,
Volatile = 1,
Aligned = 2,
Nontemporal = 4,
MakePointerAvailable = 8,
MakePointerAvailableKHR = 8,
MakePointerVisible = 16,
MakePointerVisibleKHR = 16,
NonPrivatePointer = 32,
NonPrivatePointerKHR = 32
}
|
DerSchmale/spirv4web
|
src/common/SPIRExtension.ts
|
import { IVariant } from "./IVariant";
import { Types } from "./Types";
import { defaultCopy } from "../utils/defaultCopy";
export enum SPIRExtensionExtension {
Unsupported,
GLSL,
SPV_debug_info,
SPV_AMD_shader_ballot,
SPV_AMD_shader_explicit_vertex_parameter,
SPV_AMD_shader_trinary_minmax,
SPV_AMD_gcn_shader
}
export class SPIRExtension extends IVariant
{
static type = Types.Extension;
ext: SPIRExtensionExtension;
constructor(ext: SPIRExtensionExtension);
constructor(other: SPIRExtension);
constructor(param0: SPIRExtensionExtension | SPIRExtension)
{
super();
if (param0 instanceof SPIRExtension)
defaultCopy(param0, this);
else
this.ext = param0;
}
}
|
DerSchmale/spirv4web
|
build/types/spirv/FragmentShadingRateMask.d.ts
|
export declare enum FragmentShadingRateMask {
None = 0,
Vertical2Pixels = 1,
Vertical4Pixels = 2,
Horizontal2Pixels = 4,
Horizontal4Pixels = 8
}
|
DerSchmale/spirv4web
|
build/types/utils/bigint.d.ts
|
declare function bigintFrom(high: number, low: number): bigint;
|
DerSchmale/spirv4web
|
src/compiler/Compiler.ts
|
<filename>src/compiler/Compiler.ts
// @ts-ignore
import { count, unique } from "@derschmale/array-utils";
import { ParsedIR } from "../parser/ParsedIR";
import { SPIRType, SPIRBaseType } from "../common/SPIRType";
import { Types } from "../common/Types";
import { SPIRConstant } from "../common/SPIRConstant";
import { SPIRVariable } from "../common/SPIRVariable";
import { IVariant, IVariantType } from "../common/IVariant";
import { variant_get, variant_set } from "../common/Variant";
import { SPIREntryPoint } from "../common/SPIREntryPoint";
import { EntryPoint } from "./EntryPoint";
import { DummySamplerForCombinedImageHandler } from "./DummySamplerForCombinedImageHandler";
import { SPIRFunction } from "../common/SPIRFunction";
import { SPIRExpression } from "../common/SPIRExpression";
import {
SPIRBlock,
SPIRBlockCase,
SPIRBlockContinueBlockType,
SPIRBlockMerge,
SPIRBlockMethod,
SPIRBlockTerminator
} from "../common/SPIRBlock";
import { SPIRAccessChain } from "../common/SPIRAccessChain";
import { SPIRConstantOp } from "../common/SPIRConstantOp";
import { SPIRCombinedImageSampler } from "../common/SPIRCombinedImageSampler";
import { SPIRUndef } from "../common/SPIRUndef";
import { OpcodeHandler } from "./OpcodeHandler";
import { EmbeddedInstruction, Instruction } from "../common/Instruction";
import { defaultCopy } from "../utils/defaultCopy";
import { InterfaceVariableAccessHandler } from "./InterfaceVariableAccessHandler";
import { BuiltInResource, Resource, ShaderResources } from "./ShaderResources";
import { Meta, MetaDecoration } from "../common/Meta";
import { Bitset } from "../common/Bitset";
import { CombinedImageSampler } from "./CombinedImageSampler";
import { CombinedImageSamplerHandler } from "./CombinedImageSamplerHandler";
import { CFGBuilder } from "./CFGBuilder";
import { CFG } from "../cfg/CFG";
import { AnalyzeVariableScopeAccessHandler } from "./AnalyzeVariableScopeAccessHandler";
import { maplike_get } from "../utils/maplike_get";
import { Pair } from "../utils/Pair";
import { DominatorBuilder } from "../cfg/DominatorBuilder";
import { StaticExpressionAccessHandler } from "./StaticExpressionAccessHandler";
import { ActiveBuiltinHandler } from "./ActiveBuiltinHandler";
import { CombinedImageSamplerDrefHandler } from "./CombinedImageSamplerDrefHandler";
import { CombinedImageSamplerUsageHandler } from "./CombinedImageSamplerUsageHandler";
import { InterlockedResourceAccessPrepassHandler } from "./InterlockedResourceAccessPrepassHandler";
import { InterlockedResourceAccessHandler } from "./InterlockedResourceAccessHandler";
import { PhysicalBlockMeta } from "./PhysicalBlockMeta";
import { PhysicalStorageBufferPointerHandler } from "./PhysicalStorageBufferPointerHandler";
import { convert_to_string } from "../utils/string";
import { SPIRExtension, SPIRExtensionExtension } from "../common/SPIRExtension";
import { GLSLstd450 } from "./glsl/glsl";
import { Decoration } from "../spirv/Decoration";
import { StorageClass } from "../spirv/StorageClass";
import { ExecutionModel } from "../spirv/ExecutionModel";
import { BuiltIn } from "../spirv/BuiltIn";
import { Dim } from "../spirv/Dim";
import { Op } from "../spirv/Op";
import { ExecutionMode } from "../spirv/ExecutionMode";
import { ImageFormat } from "../spirv/ImageFormat";
import { SpecializationConstant } from "./SpecializationConstant";
import { ExtendedDecorations } from "../common/ExtendedDecorations";
import { BlockMetaFlagBits } from "../parser/BlockMetaFlagBits";
type VariableTypeRemapCallback = (type: SPIRType, name: string, type_name: string) => string;
export abstract class Compiler
{
ir: ParsedIR;
// Marks variables which have global scope and variables which can alias with other variables
// (SSBO, image load store, etc)
protected global_variables: number[] = [];
protected aliased_variables: number[] = [];
protected current_function: SPIRFunction;
protected current_block: SPIRBlock;
protected current_loop_level: number = 0;
protected active_interface_variables: Set<VariableID> = new Set();
protected check_active_interface_variables: boolean = false;
protected invalid_expressions: Set<number> = new Set();
protected is_force_recompile: boolean = false;
combined_image_samplers: CombinedImageSampler[] = [];
protected variable_remap_callback: VariableTypeRemapCallback;
protected forced_temporaries: Set<number> = new Set();
protected forwarded_temporaries: Set<number> = new Set();
protected suppressed_usage_tracking: Set<number> = new Set();
protected hoisted_temporaries: Set<number> = new Set();
protected forced_invariant_temporaries: Set<number> = new Set();
active_input_builtins: Bitset = new Bitset();
active_output_builtins: Bitset = new Bitset();
clip_distance_count: number = 0;
cull_distance_count: number = 0;
position_invariant: boolean = false;
// If a variable ID or parameter ID is found in this set, a sampler is actually a shadow/comparison sampler.
// SPIR-V does not support this distinction, so we must keep track of this information outside the type system.
// There might be unrelated IDs found in this set which do not correspond to actual variables.
// This set should only be queried for the existence of samplers which are already known to be variables or parameter IDs.
// Similar is implemented for images, as well as if subpass inputs are needed.
protected comparison_ids: Set<number> = new Set<number>();
protected need_subpass_input: boolean = false;
// In certain backends, we will need to use a dummy sampler to be able to emit code.
// GLSL does not support texelFetch on texture2D objects, but SPIR-V does,
// so we need to workaround by having the application inject a dummy sampler.
dummy_sampler_id: number;
protected function_cfgs: CFG[]; // std::unordered_map<uint32_t, std::unique_ptr<CFG>>
protected physical_storage_non_block_pointer_types: number[] = [];
protected physical_storage_type_to_alignment: PhysicalBlockMeta[] = []; // map<uint32_t, PhysicalBlockMeta>
// The set of all resources written while inside the critical section, if present.
interlocked_resources: Set<number> = new Set();
protected interlocked_is_complex: boolean = false;
protected declared_block_names: string[] = [];
constructor(parsedIR: ParsedIR)
{
this.set_ir(parsedIR);
}
// After parsing, API users can modify the SPIR-V via reflection and call this
// to disassemble the SPIR-V into the desired langauage.
// Sub-classes actually implement this.
abstract compile(): string;
// Gets the identifier (OpName) of an ID. If not defined, an empty string will be returned.
get_name(id: ID): string
{
return this.ir.get_name(id);
}
// Applies a decoration to an ID. Effectively injects OpDecorate.
set_decoration(id: ID, decoration: Decoration, argument: number = 0)
{
this.ir.set_decoration(id, decoration, argument);
}
protected set_decoration_string(id: ID, decoration: Decoration, argument: string)
{
this.ir.set_decoration_string(id, decoration, argument);
}
// Overrides the identifier OpName of an ID.
// Identifiers beginning with underscores or identifiers which contain double underscores
// are reserved by the implementation.
set_name(id: ID, name: string)
{
this.ir.set_name(id, name);
}
// Gets a bitmask for the decorations which are applied to ID.
// I.e. (1ull << Op.DecorationFoo) | (1ull << Op.DecorationBar)
protected get_decoration_bitset(id: ID): Bitset
{
return this.ir.get_decoration_bitset(id);
}
// Returns the effective size of a buffer block struct member.
protected get_declared_struct_member_size(struct_type: SPIRType, index: number): number
{
if (struct_type.member_types.length === 0)
throw new Error("Declared struct in block cannot be empty.");
const flags = this.get_member_decoration_bitset(struct_type.self, index);
const type = this.get<SPIRType>(SPIRType, struct_type.member_types[index]);
switch (type.basetype) {
case SPIRBaseType.Unknown:
case SPIRBaseType.Void:
case SPIRBaseType.Boolean: // Bools are purely logical, and cannot be used for externally visible types.
case SPIRBaseType.AtomicCounter:
case SPIRBaseType.Image:
case SPIRBaseType.SampledImage:
case SPIRBaseType.Sampler:
throw new Error("Querying size for object with opaque size.");
default:
break;
}
if (type.pointer && type.storage === StorageClass.PhysicalStorageBuffer) {
// Check if this is a top-level pointer type, and not an array of pointers.
if (type.pointer_depth > this.get<SPIRType>(SPIRType, type.parent_type).pointer_depth)
return 8;
}
if (type.array.length > 0) {
// For arrays, we can use ArrayStride to get an easy check.
const array_size_literal = type.array_size_literal[type.array_size_literal.length - 1];
const array_size = array_size_literal ? type.array[type.array.length - 1] : this.evaluate_constant_u32(type.array[type.array.length - 1]);
return this.type_struct_member_array_stride(struct_type, index) * array_size;
}
else if (type.basetype === SPIRBaseType.Struct) {
return this.get_declared_struct_size(type);
}
else {
const vecsize = type.vecsize;
const columns = type.columns;
// Vectors.
if (columns === 1) {
const component_size = type.width / 8;
return vecsize * component_size;
}
else {
const matrix_stride = this.type_struct_member_matrix_stride(struct_type, index);
// Per SPIR-V spec, matrices must be tightly packed and aligned up for vec3 accesses.
if (flags.get(Decoration.RowMajor))
return matrix_stride * vecsize;
else if (flags.get(Decoration.ColMajor))
return matrix_stride * columns;
else
throw new Error("Either row-major or column-major must be declared for matrices.");
}
}
}
// Returns a set of all global variables which are statically accessed
// by the control flow graph from the current entry point.
// Only variables which change the interface for a shader are returned, that is,
// variables with storage class of Input, Output, Uniform, UniformConstant, PushConstant and AtomicCounter
// storage classes are returned.
//
// To use the returned set as the filter for which variables are used during compilation,
// this set can be moved to set_enabled_interface_variables().
get_active_interface_variables(): Set<VariableID>
{
// Traverse the call graph and find all interface variables which are in use.
const ir = this.ir;
const variables: Set<VariableID> = new Set();
const handler = new InterfaceVariableAccessHandler(this, variables);
this.traverse_all_reachable_opcodes(this.get<SPIRFunction>(SPIRFunction, ir.default_entry_point), handler);
ir.for_each_typed_id<SPIRVariable>(SPIRVariable, (_: number, var_: SPIRVariable) =>
{
if (var_.storage !== StorageClass.Output)
return;
if (!this.interface_variable_exists_in_entry_point(var_.self))
return;
// An output variable which is just declared (but uninitialized) might be read by subsequent stages
// so we should force-enable these outputs,
// since compilation will fail if a subsequent stage attempts to read from the variable in question.
// Also, make sure we preserve output variables which are only initialized, but never accessed by any code.
if (var_.initializer !== <ID>0 || this.get_execution_model() !== ExecutionModel.Fragment)
variables.add(var_.self);
});
// If we needed to create one, we'll need it.
if (this.dummy_sampler_id)
variables.add(this.dummy_sampler_id);
return variables;
}
// Sets the interface variables which are used during compilation.
// By default, all variables are used.
// Once set, compile() will only consider the set in active_variables.
set_enabled_interface_variables(active_variables: Set<VariableID>)
{
this.active_interface_variables = active_variables;
this.check_active_interface_variables = true;
}
// Query shader resources, use ids with reflection interface to modify or query binding points, etc.
get_shader_resources(): ShaderResources;
// Query shader resources, but only return the variables which are part of active_variables.
// E.g.: get_shader_resources(get_active_variables()) to only return the variables which are statically
// accessed.
get_shader_resources(active_variables: Set<VariableID>): ShaderResources;
get_shader_resources(active_variables?: Set<VariableID>): ShaderResources
{
const res = new ShaderResources();
const ir = this.ir;
const ssbo_instance_name = this.reflection_ssbo_instance_name_is_significant();
ir.for_each_typed_id<SPIRVariable>(SPIRVariable, (_, var_) =>
{
const type = this.get<SPIRType>(SPIRType, var_.basetype);
// It is possible for uniform storage classes to be passed as function parameters, so detect
// that. To detect function parameters, check of StorageClass of variable is function scope.
if (var_.storage === StorageClass.Function || !type.pointer)
return;
if (active_variables && !active_variables.has(var_.self))
return;
// In SPIR-V 1.4 and up, every global must be present in the entry point interface list,
// not just IO variables.
let active_in_entry_point = true;
if (ir.get_spirv_version() < 0x10400) {
if (var_.storage === StorageClass.Input || var_.storage === StorageClass.Output)
active_in_entry_point = this.interface_variable_exists_in_entry_point(var_.self);
}
else
active_in_entry_point = this.interface_variable_exists_in_entry_point(var_.self);
if (!active_in_entry_point)
return;
const is_builtin = this.is_builtin_variable(var_);
if (is_builtin) {
if (var_.storage !== StorageClass.Input && var_.storage !== StorageClass.Output)
return;
const list = var_.storage === StorageClass.Input ? res.builtin_inputs : res.builtin_outputs;
const resource: BuiltInResource = new BuiltInResource();
if (this.has_decoration(type.self, Decoration.Block)) {
resource.resource = new Resource(
var_.self, var_.basetype, type.self,
this.get_remapped_declared_block_name(var_.self, false)
);
for (let i = 0; i < type.member_types.length; i++) {
resource.value_type_id = type.member_types[i];
resource.builtin = <BuiltIn>this.get_member_decoration(type.self, i, Decoration.BuiltIn);
list.push(resource);
}
}
else {
const strip_array = !this.has_decoration(var_.self, Decoration.Patch) && (
this.get_execution_model() === ExecutionModel.TessellationControl ||
(this.get_execution_model() === ExecutionModel.TessellationEvaluation &&
var_.storage === StorageClass.Input));
resource.resource = new Resource(var_.self, var_.basetype, type.self, this.get_name(var_.self));
if (strip_array && type.array.length > 0)
resource.value_type_id = this.get_variable_data_type(var_).parent_type;
else
resource.value_type_id = this.get_variable_data_type_id(var_);
console.assert(resource.value_type_id);
resource.builtin = <BuiltIn>this.get_decoration(var_.self, Decoration.BuiltIn);
list.push(resource);
}
return;
}
// Input
if (var_.storage === StorageClass.Input) {
if (this.has_decoration(type.self, Decoration.Block)) {
res.stage_inputs.push(new Resource(
var_.self, var_.basetype, type.self,
this.get_remapped_declared_block_name(var_.self, false)
));
}
else
res.stage_inputs.push(new Resource(var_.self, var_.basetype, type.self, this.get_name(var_.self)));
}
// Subpass inputs
else if (var_.storage === StorageClass.UniformConstant && type.image.dim === Dim.SubpassData) {
res.subpass_inputs.push(new Resource(var_.self, var_.basetype, type.self, this.get_name(var_.self)));
}
// Outputs
else if (var_.storage === StorageClass.Output) {
if (this.has_decoration(type.self, Decoration.Block)) {
res.stage_outputs.push(
new Resource(var_.self, var_.basetype, type.self, this.get_remapped_declared_block_name(var_.self, false))
);
}
else
res.stage_outputs.push(new Resource(var_.self, var_.basetype, type.self, this.get_name(var_.self)));
}
// UBOs
else if (type.storage === StorageClass.Uniform && this.has_decoration(type.self, Decoration.Block)) {
res.uniform_buffers.push(new Resource(
var_.self, var_.basetype, type.self, this.get_remapped_declared_block_name(var_.self, false)
));
}
// Old way to declare SSBOs.
else if (type.storage === StorageClass.Uniform && this.has_decoration(type.self, Decoration.BufferBlock)) {
res.storage_buffers.push(new Resource(
var_.self, var_.basetype, type.self, this.get_remapped_declared_block_name(var_.self, ssbo_instance_name)
));
}
// Modern way to declare SSBOs.
else if (type.storage === StorageClass.StorageBuffer) {
res.storage_buffers.push(new Resource(
var_.self, var_.basetype, type.self, this.get_remapped_declared_block_name(var_.self, ssbo_instance_name)
));
}
// Push constant blocks
else if (type.storage === StorageClass.PushConstant) {
// There can only be one push constant block, but keep the vector in case this restriction is lifted
// in the future.
res.push_constant_buffers.push(new Resource(var_.self, var_.basetype, type.self, this.get_name(var_.self)));
}
// Images
else if (type.storage === StorageClass.UniformConstant && type.basetype === SPIRBaseType.Image &&
type.image.sampled === 2) {
res.storage_images.push(new Resource(var_.self, var_.basetype, type.self, this.get_name(var_.self)));
}
// Separate images
else if (type.storage === StorageClass.UniformConstant && type.basetype === SPIRBaseType.Image &&
type.image.sampled === 1) {
res.separate_images.push(new Resource(var_.self, var_.basetype, type.self, this.get_name(var_.self)));
}
// Separate samplers
else if (type.storage === StorageClass.UniformConstant && type.basetype === SPIRBaseType.Sampler) {
res.separate_samplers.push(new Resource(var_.self, var_.basetype, type.self, this.get_name(var_.self)));
}
// Textures
else if (type.storage === StorageClass.UniformConstant && type.basetype === SPIRBaseType.SampledImage) {
res.sampled_images.push(new Resource(var_.self, var_.basetype, type.self, this.get_name(var_.self)));
}
// Atomic counters
else if (type.storage === StorageClass.AtomicCounter) {
res.atomic_counters.push(new Resource(var_.self, var_.basetype, type.self, this.get_name(var_.self)));
}
// Acceleration structures
else if (type.storage === StorageClass.UniformConstant && type.basetype === SPIRBaseType.AccelerationStructure) {
res.acceleration_structures.push(new Resource(var_.self, var_.basetype, type.self, this.get_name(var_.self)));
}
});
return res;
}
get_common_basic_type(type: SPIRType): SPIRBaseType
{
if (type.basetype === SPIRBaseType.Struct) {
let base_type = SPIRBaseType.Unknown;
for (let member_type of type.member_types) {
const member_base = this.get_common_basic_type(this.get<SPIRType>(SPIRType, member_type));
if (member_base === undefined)
return undefined;
if (base_type === SPIRBaseType.Unknown)
base_type = member_base;
else if (base_type !== member_base)
return undefined;
}
return base_type;
}
else {
return type.basetype;
}
}
// Remapped variables are considered built-in variables and a backend will
// not emit a declaration for this variable.
// This is mostly useful for making use of builtins which are dependent on extensions.
set_remapped_variable_state(id: VariableID, remap_enable: boolean)
{
this.get<SPIRVariable>(SPIRVariable, id).remapped_variable = remap_enable;
}
get_remapped_variable_state(id: VariableID): boolean
{
return this.get<SPIRVariable>(SPIRVariable, id).remapped_variable;
}
// For subpassInput variables which are remapped to plain variables,
// the number of components in the remapped
// variable must be specified as the backing type of subpass inputs are opaque.
set_subpass_input_remapped_components(id: VariableID, components: number)
{
this.get<SPIRVariable>(SPIRVariable, id).remapped_components = components;
}
get_subpass_input_remapped_components(id: VariableID): number
{
return this.get<SPIRVariable>(SPIRVariable, id).remapped_components;
}
// All operations work on the current entry point.
// Entry points can be swapped out with set_entry_point().
// Entry points should be set right after the constructor completes as some reflection functions traverse the graph from the entry point.
// Resource reflection also depends on the entry point.
// By default, the current entry point is set to the first OpEntryPoint which appears in the SPIR-V module.
// Some shader languages restrict the names that can be given to entry points, and the
// corresponding backend will automatically rename an entry point name, during the call
// to compile() if it is illegal. For example, the common entry point name main() is
// illegal in MSL, and is renamed to an alternate name by the MSL backend.
// Given the original entry point name contained in the SPIR-V, this function returns
// the name, as updated by the backend during the call to compile(). If the name is not
// illegal, and has not been renamed, or if this function is called before compile(),
// this function will simply return the same name.
// New variants of entry point query and reflection.
// Names for entry points in the SPIR-V module may alias if they belong to different execution models.
// To disambiguate, we must pass along with the entry point names the execution model.
get_entry_points_and_stages(): EntryPoint[]
{
const entries: EntryPoint[] = [];
this.ir.entry_points.forEach(entry =>
entries.push(new EntryPoint(entry.orig_name, entry.model))
);
return entries;
}
set_entry_point(name: string, model: ExecutionModel)
{
const entry = this.get_entry_point(name, model);
this.ir.default_entry_point = entry.self;
}
// Renames an entry point from old_name to new_name.
// If old_name is currently selected as the current entry point, it will continue to be the current entry point,
// albeit with a new name.
// get_entry_points() is essentially invalidated at this point.
rename_entry_point(old_name: string, new_name: string, model: ExecutionModel)
{
const entry = this.get_entry_point(old_name, model);
entry.orig_name = new_name;
entry.name = new_name;
}
get_entry_point(): SPIREntryPoint;
get_entry_point(name: string, model: ExecutionModel): SPIREntryPoint;
get_entry_point(...args): SPIREntryPoint
{
const ir = this.ir;
if (args.length === 0) {
return ir.entry_points[ir.default_entry_point];
}
else {
const entry = ir.entry_points.find(entry => entry.orig_name === args[0] && entry.model === args[1]);
if (!entry)
throw new Error("Entry point does not exist.");
return entry;
}
}
// Traverses all reachable opcodes and sets active_builtins to a bitmask of all builtin variables which are accessed in the shader.
update_active_builtins()
{
const ir = this.ir;
this.active_input_builtins.reset();
this.active_output_builtins.reset();
this.cull_distance_count = 0;
this.clip_distance_count = 0;
const handler = new ActiveBuiltinHandler(this);
this.traverse_all_reachable_opcodes(this.get<SPIRFunction>(SPIRFunction, ir.default_entry_point), handler);
ir.for_each_typed_id<SPIRVariable>(SPIRVariable, (_, var_: SPIRVariable) =>
{
if (var_.storage !== StorageClass.Output)
return;
if (!this.interface_variable_exists_in_entry_point(var_.self))
return;
// Also, make sure we preserve output variables which are only initialized, but never accessed by any code.
if (var_.initializer !== <ID>(0))
handler.add_if_builtin_or_block(var_.self);
});
}
has_active_builtin(builtin: BuiltIn, storage: StorageClass): boolean
{
let flags: Bitset;
switch (storage) {
case StorageClass.Input:
flags = this.active_input_builtins;
break;
case StorageClass.Output:
flags = this.active_output_builtins;
break;
default:
return false;
}
return flags.get(builtin);
}
get_execution_model(): ExecutionModel
{
return this.get_entry_point().model;
}
// In SPIR-V, the compute work group size can be represented by a constant vector, in which case
// the LocalSize execution mode is ignored.
//
// This constant vector can be a constant vector, specialization constant vector, or partly specialized constant vector.
// To modify and query work group dimensions which are specialization constants, SPIRConstant values must be modified
// directly via get_constant() rather than using LocalSize directly. This function will return which constants should be modified.
//
// To modify dimensions which are *not* specialization constants, set_execution_mode should be used directly.
// Arguments to set_execution_mode which are specialization constants are effectively ignored during compilation.
// NOTE: This is somewhat different from how SPIR-V works. In SPIR-V, the constant vector will completely replace LocalSize,
// while in this interface, LocalSize is only ignored for specialization constants.
//
// The specialization constant will be written to x, y and z arguments.
// If the component is not a specialization constant, a zeroed out struct will be written.
// The return value is the constant ID of the builtin WorkGroupSize, but this is not expected to be useful
// for most use cases.
// If LocalSizeId is used, there is no uvec3 value representing the workgroup size, so the return value is 0,
// but x, y and z are written as normal if the components are specialization constants.
protected get_work_group_size_specialization_constants(x: SpecializationConstant, y: SpecializationConstant, z: SpecializationConstant)
{
const execution = this.get_entry_point();
x.constant_id = y.constant_id = z.constant_id = 0;
x.id = y.id = z.id = 0;
// WorkgroupSize builtin takes precedence over LocalSize / LocalSizeId.
if (execution.workgroup_size.constant !== 0)
{
const c = this.get<SPIRConstant>(SPIRConstant, execution.workgroup_size.constant);
if (c.m.c[0].id[0] !== 0)
{
x.id = c.m.c[0].id[0];
x.constant_id = this.get_decoration(c.m.c[0].id[0], Decoration.SpecId);
}
if (c.m.c[0].id[1] !== 0)
{
y.id = c.m.c[0].id[1];
y.constant_id = this.get_decoration(c.m.c[0].id[1], Decoration.SpecId);
}
if (c.m.c[0].id[2] !== 0)
{
z.id = c.m.c[0].id[2];
z.constant_id = this.get_decoration(c.m.c[0].id[2], Decoration.SpecId);
}
}
else if (execution.flags.get(ExecutionMode.LocalSizeId))
{
const cx = this.get<SPIRConstant>(SPIRConstant, execution.workgroup_size.id_x);
if (cx.specialization)
{
x.id = execution.workgroup_size.id_x;
x.constant_id = this.get_decoration(execution.workgroup_size.id_x, Decoration.SpecId);
}
const cy = this.get<SPIRConstant>(SPIRConstant, execution.workgroup_size.id_y);
if (cy.specialization)
{
y.id = execution.workgroup_size.id_y;
y.constant_id = this.get_decoration(execution.workgroup_size.id_y, Decoration.SpecId);
}
const cz = this.get<SPIRConstant>(SPIRConstant, execution.workgroup_size.id_z);
if (cz.specialization)
{
z.id = execution.workgroup_size.id_z;
z.constant_id = this.get_decoration(execution.workgroup_size.id_z, Decoration.SpecId);
}
}
return execution.workgroup_size.constant;
}
// Analyzes all OpImageFetch (texelFetch) opcodes and checks if there are instances where
// said instruction is used without a combined image sampler.
// GLSL targets do not support the use of texelFetch without a sampler.
// To workaround this, we must inject a dummy sampler which can be used to form a sampler2D at the call-site of
// texelFetch as necessary.
//
// This must be called before build_combined_image_samplers().
// build_combined_image_samplers() may refer to the ID returned by this method if the returned ID is non-zero.
// The return value will be the ID of a sampler object if a dummy sampler is necessary, or 0 if no sampler object
// is required.
//
// If the returned ID is non-zero, it can be decorated with set/bindings as desired before calling compile().
// Calling this function also invalidates get_active_interface_variables(), so this should be called
// before that function.
build_dummy_sampler_for_combined_images(): VariableID
{
const handler = new DummySamplerForCombinedImageHandler(this);
this.traverse_all_reachable_opcodes(this.get<SPIRFunction>(SPIRFunction, this.ir.default_entry_point), handler);
const ir = this.ir;
if (handler.need_dummy_sampler) {
const offset: number = ir.increase_bound_by(3);
const type_id = offset;
const ptr_type_id = offset + 1;
const var_id = offset + 2;
// let sampler_type: SPIRType;
const sampler = this.set<SPIRType>(SPIRType, type_id);
sampler.basetype = SPIRBaseType.Sampler;
const ptr_sampler = this.set<SPIRType>(SPIRType, ptr_type_id);
defaultCopy(sampler, ptr_sampler);
ptr_sampler.self = type_id;
ptr_sampler.storage = StorageClass.UniformConstant;
ptr_sampler.pointer = true;
ptr_sampler.parent_type = type_id;
this.set<SPIRVariable>(SPIRVariable, var_id, ptr_type_id, StorageClass.UniformConstant, 0);
this.set_name(var_id, "SPIRV_Cross_DummySampler");
this.dummy_sampler_id = var_id;
return var_id;
}
else
return 0;
}
// Analyzes all separate image and samplers used from the currently selected entry point,
// and re-routes them all to a combined image sampler instead.
// This is required to "support" separate image samplers in targets which do not natively support
// this feature, like GLSL/ESSL.
//
// This must be called before compile() if such remapping is desired.
// This call will add new sampled images to the SPIR-V,
// so it will appear in reflection if get_shader_resources() is called after build_combined_image_samplers.
//
// If any image/sampler remapping was found, no separate image/samplers will appear in the decompiled output,
// but will still appear in reflection.
//
// The resulting samplers will be void of any decorations like name, descriptor sets and binding points,
// so this can be added before compile() if desired.
//
// Combined image samplers originating from this set are always considered active variables.
// Arrays of separate samplers are not supported, but arrays of separate images are supported.
// Array of images + sampler -> Array of combined image samplers.
build_combined_image_samplers()
{
this.ir.for_each_typed_id<SPIRFunction>(SPIRFunction, (_, func) =>
{
func.combined_parameters = [];
func.shadow_arguments = [];
func.do_combined_parameters = true;
});
this.combined_image_samplers = [];
const handler = new CombinedImageSamplerHandler(this);
this.traverse_all_reachable_opcodes(this.get<SPIRFunction>(SPIRFunction, this.ir.default_entry_point), handler);
}
// Gets a remapping for the combined image samplers.
get_combined_image_samplers(): CombinedImageSampler[]
{
return this.combined_image_samplers;
}
// Set a new variable type remap callback.
// The type remapping is designed to allow global interface variable to assume more special types.
// A typical example here is to remap sampler2D into samplerExternalOES, which currently isn't supported
// directly by SPIR-V.
//
// In compile() while emitting code,
// for every variable that is declared, including function parameters, the callback will be called
// and the API user has a chance to change the textual representation of the type used to declare the variable.
// The API user can detect special patterns in names to guide the remapping.
set_variable_type_remap_callback(cb: VariableTypeRemapCallback)
{
this.variable_remap_callback = cb;
}
get_current_id_bound(): number
{
return this.ir.ids.length;
}
protected stream(instr: Instruction): Uint32Array
{
// If we're not going to use any arguments, just return nullptr.
// We want to avoid case where we return an out of range pointer
// that trips debug assertions on some platforms.
if (!instr.length)
return null;
if (instr.is_embedded()) {
const embedded = <EmbeddedInstruction>(instr);
console.assert(embedded.ops.length === instr.length);
return new Uint32Array(embedded.ops);
}
else {
if (instr.offset + instr.length > this.ir.spirv.length)
throw new Error("Compiler::stream() out of range.");
return this.ir.spirv.slice(instr.offset, instr.offset + instr.length);
}
}
execution_is_branchless(from: SPIRBlock, to: SPIRBlock): boolean
{
let start = from;
for (; ;) {
if (start.self === to.self)
return true;
if (start.terminator === SPIRBlockTerminator.Direct && start.merge === SPIRBlockMerge.None)
start = this.get<SPIRBlock>(SPIRBlock, start.next_block);
else
return false;
}
}
execution_is_direct_branch(from: SPIRBlock, to: SPIRBlock): boolean
{
return from.terminator === SPIRBlockTerminator.Direct && from.merge === SPIRBlockMerge.None && from.next_block === to.self;
}
protected is_break(next: number): boolean
{
this.ir.block_meta[next] = this.ir.block_meta[next] || 0;
return (this.ir.block_meta[next] & (BlockMetaFlagBits.LOOP_MERGE_BIT | BlockMetaFlagBits.MULTISELECT_MERGE_BIT)) !== 0;
}
protected is_loop_break(next: number): boolean
{
this.ir.block_meta[next] = this.ir.block_meta[next] || 0;
return (this.ir.block_meta[next] & BlockMetaFlagBits.LOOP_MERGE_BIT) !== 0;
}
protected is_conditional(next: number): boolean
{
this.ir.block_meta[next] = this.ir.block_meta[next] || 0;
return (this.ir.block_meta[next] & (BlockMetaFlagBits.SELECTION_MERGE_BIT | BlockMetaFlagBits.MULTISELECT_MERGE_BIT)) !== 0;
}
protected flush_dependees(var_: SPIRVariable)
{
for (let expr of var_.dependees)
this.invalid_expressions.add(expr);
var_.dependees = [];
}
protected flush_all_active_variables()
{
// Invalidate all temporaries we read from variables in this block since they were forwarded.
// Invalidate all temporaries we read from globals.
for (let v of this.current_function.local_variables)
this.flush_dependees(this.get<SPIRVariable>(SPIRVariable, v));
for (let arg of this.current_function.arguments)
this.flush_dependees(this.get<SPIRVariable>(SPIRVariable, arg.id));
for (let global of this.global_variables)
this.flush_dependees(this.get<SPIRVariable>(SPIRVariable, global));
this.flush_all_aliased_variables();
}
protected flush_all_aliased_variables()
{
for (let aliased of this.aliased_variables)
this.flush_dependees(this.get<SPIRVariable>(SPIRVariable, aliased));
}
protected flush_control_dependent_expressions(block_id: number)
{
const block = this.get<SPIRBlock>(SPIRBlock, block_id);
for (let expr of block.invalidate_expressions)
this.invalid_expressions.add(expr);
block.invalidate_expressions = [];
}
protected register_global_read_dependencies(func: SPIRBlock | SPIRFunction, id: number)
{
if (func instanceof SPIRFunction) {
for (let block of func.blocks)
this.register_global_read_dependencies(this.get<SPIRBlock>(SPIRBlock, block), id);
return;
}
const block = func;
for (let i of block.ops)
{
const ops = this.stream(i);
const op = <Op>(i.op);
switch (op)
{
case Op.FunctionCall:
{
const func = ops[2];
this.register_global_read_dependencies(this.get<SPIRFunction>(SPIRFunction, func), id);
break;
}
case Op.Load:
case Op.ImageRead:
{
// If we're in a storage class which does not get invalidated, adding dependencies here is no big deal.
const var_ = this.maybe_get_backing_variable(ops[2]);
if (var_ && var_.storage !== StorageClass.Function)
{
const type = this.get<SPIRType>(SPIRType, var_.basetype);
// InputTargets are immutable.
if (type.basetype !== SPIRBaseType.Image && type.image.dim !== Dim.SubpassData)
var_.dependees.push(id);
}
break;
}
default:
break;
}
}
}
update_name_cache(cache_primary: Set<string>, name: string): string;
update_name_cache(cache_primary: Set<string>, cache_secondary: Set<string>, name: string): string;
// A variant which takes two sets of names. The secondary is only used to verify there are no collisions,
// but the set is not updated when we have found a new name.
// Used primarily when adding block interface names.
update_name_cache(cache_primary: Set<string>, cache_secondary: Set<string> | string, name?: string): string
{
if (!name) {
// first overload
name = <string>cache_secondary;
cache_secondary = cache_primary;
return this.update_name_cache(cache_primary, cache_secondary, name);
}
if (name === "")
return name;
const find_name = (n: string): boolean =>
{
if (cache_primary.has(n))
return true;
if (cache_primary !== cache_secondary)
if ((<Set<string>>cache_secondary).has(n))
return true;
return false;
};
const insert_name = (n: string) =>
{
cache_primary.add(n);
};
if (!find_name(name)) {
insert_name(name);
return name;
}
let counter = 0;
let tmpname = name;
let use_linked_underscore = true;
if (tmpname === "_") {
// We cannot just append numbers, as we will end up creating internally reserved names.
// Make it like _0_<counter> instead.
tmpname += "0";
}
else if (tmpname.charAt(tmpname.length - 1) === "_") {
// The last_character is an underscore, so we don't need to link in underscore.
// This would violate double underscore rules.
use_linked_underscore = false;
}
// If there is a collision (very rare),
// keep tacking on extra identifier until it's unique.
do {
counter++;
name = tmpname + (use_linked_underscore ? "_" : "") + convert_to_string(counter);
} while (find_name(name));
insert_name(name);
return name;
}
protected function_is_pure(func: SPIRFunction): boolean
{
for (const block of func.blocks)
{
if (!this.block_is_pure(this.get<SPIRBlock>(SPIRBlock, block)))
{
//fprintf(stderr, "Function %s is impure!\n", to_name(func.self).c_str());
return false;
}
}
//fprintf(stderr, "Function %s is pure!\n", to_name(func.self).c_str());
return true;
}
protected block_is_pure(block: SPIRBlock)
{
// This is a global side effect of the function.
if (block.terminator === SPIRBlockTerminator.Kill ||
block.terminator === SPIRBlockTerminator.TerminateRay ||
block.terminator === SPIRBlockTerminator.IgnoreIntersection)
return false;
for (let i of block.ops)
{
const ops = this.stream(i);
const op = <Op>(i.op);
switch (op)
{
case Op.FunctionCall:
{
const func = ops[2];
if (!this.function_is_pure(this.get<SPIRFunction>(SPIRFunction, func)))
return false;
break;
}
case Op.CopyMemory:
case Op.Store:
{
const type = this.expression_type(ops[0]);
if (type.storage !== StorageClass.Function)
return false;
break;
}
case Op.ImageWrite:
return false;
// Atomics are impure.
/*case OpAtomicLoad:
case OpAtomicStore:
case OpAtomicExchange:
case OpAtomicCompareExchange:
case OpAtomicCompareExchangeWeak:
case OpAtomicIIncrement:
case OpAtomicIDecrement:
case OpAtomicIAdd:
case OpAtomicISub:
case OpAtomicSMin:
case OpAtomicUMin:
case OpAtomicSMax:
case OpAtomicUMax:
case OpAtomicAnd:
case OpAtomicOr:
case OpAtomicXor:
return false;*/
// Geometry shader builtins modify global state.
/*case OpEndPrimitive:
case OpEmitStreamVertex:
case OpEndStreamPrimitive:
case OpEmitVertex:
return false;*/
// Barriers disallow any reordering, so we should treat blocks with barrier as writing.
case Op.ControlBarrier:
case Op.MemoryBarrier:
return false;
// Ray tracing builtins are impure.
/*case OpReportIntersectionKHR:
case OpIgnoreIntersectionNV:
case OpTerminateRayNV:
case OpTraceNV:
case OpTraceRayKHR:
case OpExecuteCallableNV:
case OpExecuteCallableKHR:
case OpRayQueryInitializeKHR:
case OpRayQueryTerminateKHR:
case OpRayQueryGenerateIntersectionKHR:
case OpRayQueryConfirmIntersectionKHR:
case OpRayQueryProceedKHR:
// There are various getters in ray query, but they are considered pure.
return false;*/
// OpExtInst is potentially impure depending on extension, but GLSL builtins are at least pure.
case Op.DemoteToHelperInvocationEXT:
// This is a global side effect of the function.
return false;
case Op.ExtInst:
{
const extension_set = ops[2];
if (this.get<SPIRExtension>(SPIRExtension, extension_set).ext === SPIRExtensionExtension.GLSL)
{
const op_450 = <GLSLstd450>(ops[3]);
switch (op_450)
{
case GLSLstd450.Modf:
case GLSLstd450.Frexp:
{
const type = this.expression_type(ops[5]);
if (type.storage !== StorageClass.Function)
return false;
break;
}
default:
break;
}
}
break;
}
default:
break;
}
}
return true;
}
protected execution_is_noop(from: SPIRBlock, to: SPIRBlock): boolean
{
if (!this.execution_is_branchless(from, to))
return false;
let start = from;
for (; ;) {
if (start.self === to.self)
return true;
if (start.ops.length > 0)
return false;
const next = this.get<SPIRBlock>(SPIRBlock, start.next_block);
// Flushing phi variables does not count as noop.
for (let phi of next.phi_variables)
if (phi.parent === start.self)
return false;
start = next;
}
}
protected continue_block_type(block: SPIRBlock): SPIRBlockContinueBlockType
{
// The block was deemed too complex during code emit, pick conservative fallback paths.
if (block.complex_continue)
return SPIRBlockContinueBlockType.ComplexLoop;
// In older glslang output continue block can be equal to the loop header.
// In this case, execution is clearly branchless, so just assume a while loop header here.
if (block.merge === SPIRBlockMerge.Loop)
return SPIRBlockContinueBlockType.WhileLoop;
if (block.loop_dominator === SPIRBlock.NoDominator) {
// Continue block is never reached from CFG.
return SPIRBlockContinueBlockType.ComplexLoop;
}
const dominator = this.get<SPIRBlock>(SPIRBlock, block.loop_dominator);
if (this.execution_is_noop(block, dominator))
return SPIRBlockContinueBlockType.WhileLoop;
else if (this.execution_is_branchless(block, dominator))
return SPIRBlockContinueBlockType.ForLoop;
else {
const false_block = this.maybe_get<SPIRBlock>(SPIRBlock, block.false_block);
const true_block = this.maybe_get<SPIRBlock>(SPIRBlock, block.true_block);
const merge_block = this.maybe_get<SPIRBlock>(SPIRBlock, dominator.merge_block);
// If we need to flush Phi in this block, we cannot have a DoWhile loop.
const flush_phi_to_false = false_block && this.flush_phi_required(block.self, block.false_block);
const flush_phi_to_true = true_block && this.flush_phi_required(block.self, block.true_block);
if (flush_phi_to_false || flush_phi_to_true)
return SPIRBlockContinueBlockType.ComplexLoop;
const positive_do_while = block.true_block === dominator.self &&
(block.false_block === dominator.merge_block ||
(false_block && merge_block && this.execution_is_noop(false_block, merge_block)));
const negative_do_while = block.false_block === dominator.self &&
(block.true_block === dominator.merge_block ||
(true_block && merge_block && this.execution_is_noop(true_block, merge_block)));
if (block.merge === SPIRBlockMerge.None && block.terminator === SPIRBlockTerminator.Select &&
(positive_do_while || negative_do_while)) {
return SPIRBlockContinueBlockType.DoWhileLoop;
}
else
return SPIRBlockContinueBlockType.ComplexLoop;
}
}
protected force_recompile()
{
this.is_force_recompile = true;
}
protected is_forcing_recompilation(): boolean
{
return this.is_force_recompile;
}
protected block_is_loop_candidate(block: SPIRBlock, method: SPIRBlockMethod): boolean
{
// Tried and failed.
if (block.disable_block_optimization || block.complex_continue)
return false;
if (method === SPIRBlockMethod.MergeToSelectForLoop || method === SPIRBlockMethod.MergeToSelectContinueForLoop) {
// Try to detect common for loop pattern
// which the code backend can use to create cleaner code.
// for(;;) { if (cond) { some_body; } else { break; } }
// is the pattern we're looking for.
const false_block = this.maybe_get<SPIRBlock>(SPIRBlock, block.false_block);
const true_block = this.maybe_get<SPIRBlock>(SPIRBlock, block.true_block);
const merge_block = this.maybe_get<SPIRBlock>(SPIRBlock, block.merge_block);
const false_block_is_merge = block.false_block === block.merge_block ||
(false_block && merge_block && this.execution_is_noop(false_block, merge_block));
const true_block_is_merge = block.true_block === block.merge_block ||
(true_block && merge_block && this.execution_is_noop(true_block, merge_block));
const positive_candidate =
block.true_block !== block.merge_block && block.true_block !== block.self && false_block_is_merge;
const negative_candidate =
block.false_block !== block.merge_block && block.false_block !== block.self && true_block_is_merge;
let ret = block.terminator === SPIRBlockTerminator.Select && block.merge === SPIRBlockMerge.Loop &&
(positive_candidate || negative_candidate);
if (ret && positive_candidate && method === SPIRBlockMethod.MergeToSelectContinueForLoop)
ret = block.true_block === block.continue_block;
else if (ret && negative_candidate && method === SPIRBlockMethod.MergeToSelectContinueForLoop)
ret = block.false_block === block.continue_block;
// If we have OpPhi which depends on branches which came from our own block,
// we need to flush phi variables in else block instead of a trivial break,
// so we cannot assume this is a for loop candidate.
if (ret) {
for (let phi of block.phi_variables)
if (phi.parent === block.self)
return false;
const merge = this.maybe_get<SPIRBlock>(SPIRBlock, block.merge_block);
if (merge)
for (let phi of merge.phi_variables)
if (phi.parent === block.self)
return false;
}
return ret;
}
else if (method === SPIRBlockMethod.MergeToDirectForLoop) {
// Empty loop header that just sets up merge target
// and branches to loop body.
let ret = block.terminator === SPIRBlockTerminator.Direct && block.merge === SPIRBlockMerge.Loop && block.ops.length === 0;
if (!ret)
return false;
const child = this.get<SPIRBlock>(SPIRBlock, block.next_block);
const false_block = this.maybe_get<SPIRBlock>(SPIRBlock, child.false_block);
const true_block = this.maybe_get<SPIRBlock>(SPIRBlock, child.true_block);
const merge_block = this.maybe_get<SPIRBlock>(SPIRBlock, block.merge_block);
const false_block_is_merge = child.false_block === block.merge_block ||
(false_block && merge_block && this.execution_is_noop(false_block, merge_block));
const true_block_is_merge = child.true_block === block.merge_block ||
(true_block && merge_block && this.execution_is_noop(true_block, merge_block));
const positive_candidate = child.true_block !== block.merge_block && child.true_block !== block.self && false_block_is_merge;
const negative_candidate = child.false_block !== block.merge_block && child.false_block !== block.self && true_block_is_merge;
ret = child.terminator === SPIRBlockTerminator.Select && child.merge === SPIRBlockMerge.None &&
(positive_candidate || negative_candidate);
// If we have OpPhi which depends on branches which came from our own block,
// we need to flush phi variables in else block instead of a trivial break,
// so we cannot assume this is a for loop candidate.
if (ret) {
for (let phi of block.phi_variables)
if (phi.parent === block.self || phi.parent === child.self)
return false;
for (let phi of child.phi_variables)
if (phi.parent === block.self)
return false;
const merge = this.maybe_get<SPIRBlock>(SPIRBlock, block.merge_block);
if (merge)
for (let phi of merge.phi_variables)
if (phi.parent === block.self || phi.parent === child.false_block)
return false;
}
return ret;
}
else
return false;
}
protected inherit_expression_dependencies(dst: number, source_expression: number)
{
// Don't inherit any expression dependencies if the expression in dst
// is not a forwarded temporary.
if (!this.forwarded_temporaries.has(dst) ||
this.forced_temporaries.has(dst)) {
return;
}
const e = this.get<SPIRExpression>(SPIRExpression, dst);
const phi = this.maybe_get<SPIRVariable>(SPIRVariable, source_expression);
if (phi?.phi_variable) {
// We have used a phi variable, which can change at the end of the block,
// so make sure we take a dependency on this phi variable.
phi.dependees.push(dst);
}
const s = this.maybe_get<SPIRExpression>(SPIRExpression, source_expression);
if (!s)
return;
const e_deps = e.expression_dependencies;
const s_deps = s.expression_dependencies;
// If we depend on a expression, we also depend on all sub-dependencies from source.
e_deps.push(source_expression);
e_deps.push(...s_deps);
// Eliminate duplicated dependencies.
e.expression_dependencies = unique(e_deps);
}
protected add_implied_read_expression(e: SPIRExpression | SPIRAccessChain, source: number)
{
const itr = e.implied_read_expressions.indexOf(<ID>(source));
if (itr < 0)
e.implied_read_expressions.push(source);
}
protected clear_force_recompile()
{
this.is_force_recompile = false;
}
// For proper multiple entry point support, allow querying if an Input or Output
// variable is part of that entry points interface.
protected interface_variable_exists_in_entry_point(id: number): boolean
{
const var_ = this.get<SPIRVariable>(SPIRVariable, id);
const ir = this.ir;
if (ir.get_spirv_version() < 0x10400) {
if (var_.storage !== StorageClass.Input &&
var_.storage !== StorageClass.Output &&
var_.storage !== StorageClass.UniformConstant)
throw new Error("Only Input, Output variables and Uniform constants are part of a shader linking" +
" interface.");
// This is to avoid potential problems with very old glslang versions which did
// not emit input/output interfaces properly.
// We can assume they only had a single entry point, and single entry point
// shaders could easily be assumed to use every interface variable anyways.
if (count(ir.entry_points) <= 1)
return true;
}
// In SPIR-V 1.4 and later, all global resource variables must be present.
const execution = this.get_entry_point();
return execution.interface_variables.indexOf(id) >= 0;
}
protected remap_variable_type_name(type: SPIRType, var_name: string, type_name: string)
{
if (this.variable_remap_callback)
return this.variable_remap_callback(type, var_name, type_name);
return type_name;
}
protected set_ir(ir: ParsedIR): void
{
this.ir = ir;
this.parse_fixup();
}
protected parse_fixup(): void
{
const ir = this.ir;
// Figure out specialization constants for work group sizes.
for (let id_ of ir.ids_for_constant_or_variable) {
const id = ir.ids[id_];
if (id.get_type() === Types.Constant) {
const c = id.get<SPIRConstant>(SPIRConstant);
if (ir.get_meta(c.self).decoration.builtin && ir.get_meta(c.self).decoration.builtin_type === BuiltIn.WorkgroupSize) {
// In current SPIR-V, there can be just one constant like this.
// All entry points will receive the constant value.
for (let entry of ir.entry_points) {
entry.workgroup_size.constant = c.self;
entry.workgroup_size.x = c.scalar(0, 0);
entry.workgroup_size.y = c.scalar(0, 1);
entry.workgroup_size.z = c.scalar(0, 2);
}
}
}
else if (id.get_type() === Types.Variable) {
const var_ = id.get<SPIRVariable>(SPIRVariable);
if (var_.storage === StorageClass.Private ||
var_.storage === StorageClass.Workgroup ||
var_.storage === StorageClass.Output)
this.global_variables.push(var_.self);
if (this.variable_storage_is_aliased(var_))
this.aliased_variables.push(var_.self);
}
}
}
protected variable_storage_is_aliased(v: SPIRVariable): boolean
{
const type = this.get<SPIRType>(SPIRType, v.basetype);
const ssbo = v.storage === StorageClass.StorageBuffer ||
this.ir.get_meta(type.self).decoration.decoration_flags.get(Decoration.BufferBlock);
const image = type.basetype === SPIRBaseType.Image;
const counter = type.basetype === SPIRBaseType.AtomicCounter;
const buffer_reference = type.storage === StorageClass.PhysicalStorageBufferEXT;
let is_restrict: boolean;
if (ssbo)
is_restrict = this.ir.get_buffer_block_flags(v).get(Decoration.Restrict);
else
is_restrict = this.has_decoration(v.self, Decoration.Restrict);
return !is_restrict && (ssbo || image || counter || buffer_reference);
}
protected add_loop_level()
{
this.current_loop_level++;
}
protected set_initializers(e: IVariant)
{
if (e instanceof SPIRExpression)
e.emitted_loop_level = this.current_loop_level;
}
// If our IDs are out of range here as part of opcodes, throw instead of
// undefined behavior.
set<T extends IVariant>(classRef: IVariantType<T>, id: number, ...args): T
{
this.ir.add_typed_id(classRef.type, id);
const var_ = variant_set<T>(classRef, this.ir.ids[id], ...args);
var_.self = id;
this.set_initializers(var_);
return var_;
}
get<T extends IVariant>(classRef: IVariantType<T>, id: number)
{
return variant_get<T>(classRef, this.ir.ids[id]);
}
has_decoration(id: ID, decoration: Decoration): boolean
{
return this.ir.has_decoration(id, decoration);
}
// Gets the value for decorations which take arguments.
// If the decoration is a boolean (i.e. Op.DecorationNonWritable),
// 1 will be returned.
// If decoration doesn't exist or decoration is not recognized,
// 0 will be returned.
get_decoration(id: ID, decoration: Decoration): number
{
return this.ir.get_decoration(id, decoration);
}
protected get_decoration_string(id: ID, decoration: Decoration): string
{
return this.ir.get_decoration_string(id, decoration);
}
// Removes the decoration for an ID.
protected unset_decoration(id: ID, decoration: Decoration)
{
this.ir.unset_decoration(id, decoration);
}
// Gets the SPIR-V type associated with ID.
// Mostly used with Resource::type_id and Resource::base_type_id to parse the underlying type of a resource.
get_type(id: TypeID): SPIRType
{
return this.get<SPIRType>(SPIRType, id);
}
// If get_name() is an empty string, get the fallback name which will be used
// instead in the disassembled source.
protected get_fallback_name(id: ID): string
{
return "_" + id;
}
// If get_name() of a Block struct is an empty string, get the fallback name.
// This needs to be per-variable as multiple variables can use the same block type.
protected get_block_fallback_name(id: VariableID): string
{
const var_ = this.get<SPIRVariable>(SPIRVariable, id);
if (this.get_name(id) === "")
return "_" + this.get<SPIRType>(SPIRType, var_.basetype).self + "_" + id;
else
return this.get_name(id);
}
// Given an OpTypeStruct in ID, obtain the identifier for member number "index".
// This may be an empty string.
protected get_member_name(id: TypeID, index: number): string
{
return this.ir.get_member_name(id, index);
}
// Given an OpTypeStruct in ID, obtain the OpMemberDecoration for member number "index".
get_member_decoration(id: TypeID, index: number, decoration: Decoration): number
{
return this.ir.get_member_decoration(id, index, decoration);
}
protected get_member_decoration_string(id: TypeID, index: number, decoration: Decoration): string
{
return this.ir.get_member_decoration_string(id, index, decoration);
}
// Sets the member identifier for OpTypeStruct ID, member number "index".
set_member_name(id: TypeID, index: number, name: string)
{
this.ir.set_member_name(id, index, name);
}
// Returns the qualified member identifier for OpTypeStruct ID, member number "index",
// or an empty string if no qualified alias exists
protected get_member_qualified_name(type_id: TypeID, index: number): string
{
const m = this.ir.find_meta(type_id);
if (m && index < m.members.length)
return m.members[index].qualified_alias;
else
return this.ir.get_empty_string();
}
// Gets the decoration mask for a member of a struct, similar to get_decoration_mask.
get_member_decoration_bitset(id: TypeID, index: number): Bitset
{
return this.ir.get_member_decoration_bitset(id, index);
}
// Returns whether the decoration has been applied to a member of a struct.
has_member_decoration(id: TypeID, index: number, decoration: Decoration): boolean
{
return this.ir.has_member_decoration(id, index, decoration);
}
// Similar to set_decoration, but for struct members.
protected set_member_decoration(id: TypeID, index: number, decoration: Decoration, argument: number = 0)
{
this.ir.set_member_decoration(id, index, decoration, argument);
}
protected set_member_decoration_string(id: TypeID, index: number, decoration: Decoration, argument: string)
{
this.ir.set_member_decoration_string(id, index, decoration, argument);
}
// Unsets a member decoration, similar to unset_decoration.
protected unset_member_decoration(id: TypeID, index: number, decoration: Decoration)
{
this.ir.unset_member_decoration(id, index, decoration);
}
// Gets the fallback name for a member, similar to get_fallback_name.
protected get_fallback_member_name(index: number): string
{
return "_" + index;
}
// Returns the effective size of a buffer block.
protected get_declared_struct_size(type: SPIRType): number
{
if (type.member_types.length === 0)
throw new Error("Declared struct in block cannot be empty.");
// Offsets can be declared out of order, so we need to deduce the actual size
// based on last member instead.
let member_index = 0;
let highest_offset = 0;
for (let i = 0; i < type.member_types.length; i++) {
const offset = this.type_struct_member_offset(type, i);
if (offset > highest_offset) {
highest_offset = offset;
member_index = i;
}
}
const size = this.get_declared_struct_member_size(type, member_index);
return highest_offset + size;
}
maybe_get<T extends IVariant>(classRef: IVariantType<T>, id: number)
{
const ir = this.ir;
if (id >= ir.ids.length)
return null;
else if (ir.ids[id].get_type() === classRef.type)
return this.get<T>(classRef, id);
else
return null;
}
// Gets the id of SPIR-V type underlying the given type_id, which might be a pointer.
protected get_pointee_type_id(type_id: number): number
{
const p_type = this.get<SPIRType>(SPIRType, type_id);
if (p_type.pointer) {
console.assert(p_type.parent_type);
type_id = p_type.parent_type;
}
return type_id;
}
// Gets the SPIR-V type underlying the given type, which might be a pointer.
get_pointee_type<T>(type: SPIRType): SPIRType;
get_pointee_type<T>(type: number): SPIRType;
get_pointee_type<T>(type: SPIRType | number): SPIRType
{
if (typeof type === "number") {
return this.get_pointee_type(this.get<SPIRType>(SPIRType, type));
}
let p_type = type;
if (p_type.pointer) {
console.assert(p_type.parent_type);
p_type = this.get<SPIRType>(SPIRType, p_type.parent_type);
}
return p_type;
}
// Gets the ID of the SPIR-V type underlying a variable.
protected get_variable_data_type_id(var_: SPIRVariable): number
{
if (var_.phi_variable)
return var_.basetype;
return this.get_pointee_type_id(var_.basetype);
}
// Gets the SPIR-V type underlying a variable.
protected get_variable_data_type(var_: SPIRVariable): SPIRType
{
return this.get<SPIRType>(SPIRType, this.get_variable_data_type_id(var_));
}
protected is_immutable(id: number): boolean
{
const ir = this.ir;
if (ir.ids[id].get_type() === Types.Variable) {
const var_ = this.get<SPIRVariable>(SPIRVariable, id);
// Anything we load from the UniformConstant address space is guaranteed to be immutable.
const pointer_to_const = var_.storage === StorageClass.UniformConstant;
return pointer_to_const || var_.phi_variable || !this.expression_is_lvalue(id);
}
else if (ir.ids[id].get_type() === Types.AccessChain)
return this.get<SPIRAccessChain>(SPIRAccessChain, id).immutable;
else if (ir.ids[id].get_type() === Types.Expression)
return this.get<SPIRExpression>(SPIRExpression, id).immutable;
else if (
ir.ids[id].get_type() === Types.Constant ||
ir.ids[id].get_type() === Types.ConstantOp ||
ir.ids[id].get_type() === Types.Undef
)
return true;
else
return false;
}
maybe_get_backing_variable(chain: number): SPIRVariable
{
let var_ = this.maybe_get<SPIRVariable>(SPIRVariable, chain);
if (!var_) {
const cexpr = this.maybe_get<SPIRExpression>(SPIRExpression, chain);
if (cexpr)
var_ = this.maybe_get<SPIRVariable>(SPIRVariable, cexpr.loaded_from);
const access_chain = this.maybe_get<SPIRAccessChain>(SPIRAccessChain, chain);
if (access_chain)
var_ = this.maybe_get<SPIRVariable>(SPIRVariable, access_chain.loaded_from);
}
return var_;
}
to_name(id: number, allow_alias: boolean = true): string
{
const ir = this.ir;
if (allow_alias && ir.ids[id].get_type() === Types.Type) {
// If this type is a simple alias, emit the
// name of the original type instead.
// We don't want to override the meta alias
// as that can be overridden by the reflection APIs after parse.
const type = this.get<SPIRType>(SPIRType, id);
if (type.type_alias) {
// If the alias master has been specially packed, we will have emitted a clean variant as well,
// so skip the name aliasing here.
if (!this.has_extended_decoration(type.type_alias, ExtendedDecorations.BufferBlockRepacked))
return this.to_name(type.type_alias);
}
}
const alias = ir.get_name(id);
if (!alias || alias === "")
return "_" + id;
else
return alias;
}
protected is_builtin_variable(var_: SPIRVariable): boolean
{
const m = this.ir.find_meta(var_.self);
if (var_.compat_builtin || (m && m.decoration.builtin))
return true;
else
return this.is_builtin_type(this.get<SPIRType>(SPIRType, var_.basetype));
}
protected is_builtin_type(type: SPIRType): boolean
{
const type_meta = this.ir.find_meta(type.self);
// We can have builtin structs as well. If one member of a struct is builtin, the struct must also be builtin.
if (type_meta)
for (let m of type_meta.members)
if (m.builtin)
return true;
return false;
}
protected is_hidden_variable(var_: SPIRVariable, include_builtins: boolean = false): boolean
{
if ((this.is_builtin_variable(var_) && !include_builtins) || var_.remapped_variable)
return true;
// Combined image samplers are always considered active as they are "magic" variables.
const rs = this.combined_image_samplers.find(samp => samp.combined_id === var_.self);
if (rs)
return false;
const { ir } = this;
// In SPIR-V 1.4 and up we must also use the active variable interface to disable global variables
// which are not part of the entry point.
if (ir.get_spirv_version() >= 0x10400 && var_.storage !== StorageClass.Generic &&
var_.storage !== StorageClass.Function && !this.interface_variable_exists_in_entry_point(var_.self)) {
return true;
}
return this.check_active_interface_variables && storage_class_is_interface(var_.storage) && !this.active_interface_variables.has(var_.self);
}
protected is_member_builtin(type: SPIRType, index: number): BuiltIn
{
const type_meta = this.ir.find_meta(type.self);
if (type_meta) {
const memb = type_meta.members;
if (index < memb.length && memb[index].builtin) {
return memb[index].builtin_type;
}
}
return undefined;
}
protected is_scalar(type: SPIRType)
{
return type.basetype !== SPIRBaseType.Struct && type.vecsize === 1 && type.columns === 1;
}
protected is_vector(type: SPIRType)
{
return type.vecsize > 1 && type.columns === 1;
}
protected is_matrix(type: SPIRType): boolean
{
return type.vecsize > 1 && type.columns > 1;
}
protected is_array(type: SPIRType): boolean
{
return type.array.length > 0;
}
protected expression_type_id(id: number): number
{
switch (this.ir.ids[id].get_type()) {
case Types.Variable:
return this.get<SPIRVariable>(SPIRVariable, id).basetype;
case Types.Expression:
return this.get<SPIRExpression>(SPIRExpression, id).expression_type;
case Types.Constant:
return this.get<SPIRConstant>(SPIRConstant, id).constant_type;
case Types.ConstantOp:
return this.get<SPIRConstantOp>(SPIRConstantOp, id).basetype;
case Types.Undef:
return this.get<SPIRUndef>(SPIRUndef, id).basetype;
case Types.CombinedImageSampler:
return this.get<SPIRCombinedImageSampler>(SPIRCombinedImageSampler, id).combined_type;
case Types.AccessChain:
return this.get<SPIRAccessChain>(SPIRAccessChain, id).basetype;
default:
throw new Error("Cannot resolve expression type.");
}
}
expression_type(id: number): SPIRType
{
return this.get<SPIRType>(SPIRType, this.expression_type_id(id));
}
protected expression_is_lvalue(id: number): boolean
{
const type = this.expression_type(id);
switch (type.basetype) {
case SPIRBaseType.SampledImage:
case SPIRBaseType.Image:
case SPIRBaseType.Sampler:
return false;
default:
return true;
}
}
register_read(expr: number, chain: number, forwarded: boolean)
{
const e = this.get<SPIRExpression>(SPIRExpression, expr);
const var_ = this.maybe_get_backing_variable(chain);
if (var_) {
e.loaded_from = var_.self;
// If the backing variable is immutable, we do not need to depend on the variable.
if (forwarded && !this.is_immutable(var_.self))
var_.dependees.push(e.self);
// If we load from a parameter, make sure we create "inout" if we also write to the parameter.
// The default is "in" however, so we never invalidate our compilation by reading.
if (var_ && var_.parameter)
var_.parameter.read_count++;
}
}
protected register_write(chain: number)
{
let var_ = this.maybe_get<SPIRVariable>(SPIRVariable, chain);
if (!var_) {
// If we're storing through an access chain, invalidate the backing variable instead.
const expr = this.maybe_get<SPIRExpression>(SPIRExpression, chain);
if (expr && expr.loaded_from)
var_ = this.maybe_get<SPIRVariable>(SPIRVariable, expr.loaded_from);
const access_chain = this.maybe_get<SPIRAccessChain>(SPIRAccessChain, chain);
if (access_chain && access_chain.loaded_from)
var_ = this.maybe_get<SPIRVariable>(SPIRVariable, access_chain.loaded_from);
}
const chain_type = this.expression_type(chain);
if (var_) {
let check_argument_storage_qualifier = true;
const type = this.expression_type(chain);
// If our variable is in a storage class which can alias with other buffers,
// invalidate all variables which depend on aliased variables. And if this is a
// variable pointer, then invalidate all variables regardless.
if (this.get_variable_data_type(var_).pointer) {
this.flush_all_active_variables();
if (type.pointer_depth === 1) {
// We have a backing variable which is a pointer-to-pointer type.
// We are storing some data through a pointer acquired through that variable,
// but we are not writing to the value of the variable itself,
// i.e., we are not modifying the pointer directly.
// If we are storing a non-pointer type (pointer_depth === 1),
// we know that we are storing some unrelated data.
// A case here would be
// void foo(Foo * const *arg) {
// Foo *bar = *arg;
// bar->unrelated = 42;
// }
// arg, the argument is constant.
check_argument_storage_qualifier = false;
}
}
if (type.storage === StorageClass.PhysicalStorageBufferEXT || this.variable_storage_is_aliased(var_))
this.flush_all_aliased_variables();
else if (var_)
this.flush_dependees(var_);
// We tried to write to a parameter which is not marked with out qualifier, force a recompile.
if (check_argument_storage_qualifier && var_.parameter && var_.parameter.write_count === 0) {
var_.parameter.write_count++;
this.force_recompile();
}
}
else if (chain_type.pointer) {
// If we stored through a variable pointer, then we don't know which
// variable we stored to. So *all* expressions after this point need to
// be invalidated.
// FIXME: If we can prove that the variable pointer will point to
// only certain variables, we can invalidate only those.
this.flush_all_active_variables();
}
// If chain_type.pointer is false, we're not writing to memory backed variables, but temporaries instead.
// This can happen in copy_logical_type where we unroll complex reads and writes to temporaries.
}
protected is_continue(next: number): boolean
{
this.ir.block_meta[next] = this.ir.block_meta[next] || 0;
return (this.ir.block_meta[next] & BlockMetaFlagBits.CONTINUE_BIT) !== 0;
}
protected is_single_block_loop(next: number): boolean
{
const block = this.get<SPIRBlock>(SPIRBlock, next);
return block.merge === SPIRBlockMerge.Loop && block.continue_block === <ID>(next);
}
protected traverse_all_reachable_opcodes(block: SPIRBlock, handler: OpcodeHandler): boolean;
protected traverse_all_reachable_opcodes(block: SPIRFunction, handler: OpcodeHandler): boolean;
protected traverse_all_reachable_opcodes(param0: SPIRBlock | SPIRFunction, handler: OpcodeHandler): boolean
{
if (param0 instanceof SPIRFunction) {
for (let block of param0.blocks)
if (!this.traverse_all_reachable_opcodes(this.get<SPIRBlock>(SPIRBlock, block), handler))
return false;
return true;
}
const block = param0;
handler.set_current_block(block);
handler.rearm_current_block(block);
// Ideally, perhaps traverse the CFG instead of all blocks in order to eliminate dead blocks,
// but this shouldn't be a problem in practice unless the SPIR-V is doing insane things like recursing
// inside dead blocks ...
for (let i of block.ops) {
const ops = this.stream(i);
const op = <Op>(i.op);
if (!handler.handle(op, ops, i.length))
return false;
if (op === Op.FunctionCall) {
const func = this.get<SPIRFunction>(SPIRFunction, ops[2]);
if (handler.follow_function_call(func)) {
if (!handler.begin_function_scope(ops, i.length))
return false;
if (!this.traverse_all_reachable_opcodes(this.get<SPIRFunction>(SPIRFunction, ops[2]), handler))
return false;
if (!handler.end_function_scope(ops, i.length))
return false;
handler.rearm_current_block(block);
}
}
}
if (!handler.handle_terminator(block))
return false;
return true;
}
analyze_image_and_sampler_usage()
{
const ir = this.ir;
const dref_handler = new CombinedImageSamplerDrefHandler(this);
this.traverse_all_reachable_opcodes(this.get<SPIRFunction>(SPIRFunction, ir.default_entry_point), dref_handler);
const handler = new CombinedImageSamplerUsageHandler(this, dref_handler.dref_combined_samplers);
this.traverse_all_reachable_opcodes(this.get<SPIRFunction>(SPIRFunction, ir.default_entry_point), handler);
// Need to run this traversal twice. First time, we propagate any comparison sampler usage from leaf functions
// down to main().
// In the second pass, we can propagate up forced depth state coming from main() up into leaf functions.
handler.dependency_hierarchy = [];
this.traverse_all_reachable_opcodes(this.get<SPIRFunction>(SPIRFunction, ir.default_entry_point), handler);
this.comparison_ids = handler.comparison_ids;
this.need_subpass_input = handler.need_subpass_input;
// Forward information from separate images and samplers into combined image samplers.
for (let combined of this.combined_image_samplers)
if (this.comparison_ids.has(combined.sampler_id))
this.comparison_ids.add(combined.combined_id);
}
protected build_function_control_flow_graphs_and_analyze()
{
const ir = this.ir;
const handler = new CFGBuilder(this);
handler.function_cfgs[ir.default_entry_point] = new CFG(this, this.get<SPIRFunction>(SPIRFunction, ir.default_entry_point));
this.traverse_all_reachable_opcodes(this.get<SPIRFunction>(SPIRFunction, ir.default_entry_point), handler);
this.function_cfgs = handler.function_cfgs;
const single_function = count(this.function_cfgs) <= 1;
this.function_cfgs.forEach((f_second, f_first) =>
{
const func = this.get<SPIRFunction>(SPIRFunction, f_first);
const scope_handler = new AnalyzeVariableScopeAccessHandler(this, func);
this.analyze_variable_scope(func, scope_handler);
this.find_function_local_luts(func, scope_handler, single_function);
// Check if we can actually use the loop variables we found in analyze_variable_scope.
// To use multiple initializers, we need the same type and qualifiers.
for (let block of func.blocks) {
const b = this.get<SPIRBlock>(SPIRBlock, block);
if (b.loop_variables.length < 2)
continue;
const flags = this.get_decoration_bitset(b.loop_variables[0]);
const type = this.get<SPIRVariable>(SPIRVariable, b.loop_variables[0]).basetype;
let invalid_initializers = false;
for (let loop_variable of b.loop_variables) {
if (flags !== this.get_decoration_bitset(loop_variable) ||
type !== this.get<SPIRVariable>(SPIRVariable, b.loop_variables[0]).basetype) {
invalid_initializers = true;
break;
}
}
if (invalid_initializers) {
for (let loop_variable of b.loop_variables)
this.get<SPIRVariable>(SPIRVariable, loop_variable).loop_variable = false;
b.loop_variables = [];
}
}
});
}
get_cfg_for_current_function()
{
console.assert(this.current_function);
return this.get_cfg_for_function(this.current_function.self);
}
get_cfg_for_function(id: number): CFG
{
const cfg = this.function_cfgs[id];
console.assert(cfg);
return cfg;
}
// variable_to_blocks = map<uint32_t, set<uint32_t>>
// complete_write_blocks = map<uint32_t, set<uint32_t>>
analyze_parameter_preservation(entry: SPIRFunction, cfg: CFG, variable_to_blocks: Set<number>[], complete_write_blocks: Set<number>[])
{
for (let arg of entry.arguments) {
// Non-pointers are always inputs.
const type = this.get<SPIRType>(SPIRType, arg.type);
if (!type.pointer)
continue;
// Opaque argument types are always in
let potential_preserve: boolean;
switch (type.basetype) {
case SPIRBaseType.Sampler:
case SPIRBaseType.Image:
case SPIRBaseType.SampledImage:
case SPIRBaseType.AtomicCounter:
potential_preserve = false;
break;
default:
potential_preserve = true;
break;
}
if (!potential_preserve)
continue;
if (!variable_to_blocks.hasOwnProperty(arg.id)) {
// Variable is never accessed.
continue;
}
// We have accessed a variable, but there was no complete writes to that variable.
// We deduce that we must preserve the argument.
if (!complete_write_blocks.hasOwnProperty(arg.id)) {
arg.read_count++;
continue;
}
const itrSecond = complete_write_blocks[arg.id];
// If there is a path through the CFG where no block completely writes to the variable, the variable will be in an undefined state
// when the function returns. We therefore need to implicitly preserve the variable in case there are writers in the function.
// Major case here is if a function is
// void foo(int &var) { if (cond) var = 10; }
// Using read/write counts, we will think it's just an out variable, but it really needs to be inout,
// because if we don't write anything whatever we put into the function must return back to the caller.
const visit_cache: Set<number> = new Set();
if (exists_unaccessed_path_to_return(cfg, entry.entry_block, itrSecond, visit_cache))
arg.read_count++;
}
}
protected analyze_non_block_pointer_types()
{
const ir = this.ir;
const handler = new PhysicalStorageBufferPointerHandler(this);
this.traverse_all_reachable_opcodes(this.get<SPIRFunction>(SPIRFunction, ir.default_entry_point), handler);
// Analyze any block declaration we have to make. It might contain
// physical pointers to POD types which we never used, and thus never added to the list.
// We'll need to add those pointer types to the set of types we declare.
ir.for_each_typed_id<SPIRType>(SPIRType, (_, type) =>
{
if (this.has_decoration(type.self, Decoration.Block) || this.has_decoration(type.self, Decoration.BufferBlock))
handler.analyze_non_block_types_from_block(type);
});
handler.non_block_types.forEach(type =>
this.physical_storage_non_block_pointer_types.push(type)
);
this.physical_storage_non_block_pointer_types.sort();
this.physical_storage_type_to_alignment = handler.physical_block_type_meta;
}
protected analyze_variable_scope(entry: SPIRFunction, handler: AnalyzeVariableScopeAccessHandler)
{
// First, we map out all variable access within a function.
// Essentially a map of block -> { variables accessed in the basic block }
this.traverse_all_reachable_opcodes(entry, handler);
const ir = this.ir;
const cfg = maplike_get(CFG, this.function_cfgs, entry.self);
// Analyze if there are parameters which need to be implicitly preserved with an "in" qualifier.
this.analyze_parameter_preservation(entry, cfg, handler.accessed_variables_to_block, handler.complete_write_variables_to_block);
// unordered_map<uint32_t, uint32_t>
const potential_loop_variables: number[] = [];
// Find the loop dominator block for each block.
for (const block_id of entry.blocks) {
const block = this.get<SPIRBlock>(SPIRBlock, block_id);
const itrSecond = ir.continue_block_to_loop_header[block_id];
if (!!itrSecond && itrSecond !== block_id) {
// Continue block might be unreachable in the CFG, but we still like to know the loop dominator.
// Edge case is when continue block is also the loop header, don't set the dominator in this case.
block.loop_dominator = itrSecond;
}
else {
const loop_dominator = cfg.find_loop_dominator(block_id);
if (loop_dominator !== block_id)
block.loop_dominator = loop_dominator;
else
block.loop_dominator = SPIRBlock.NoDominator;
}
}
// For each variable which is statically accessed.
handler.accessed_variables_to_block.forEach((var_second, var_first) =>
{
// Only deal with variables which are considered local variables in this function.
if (entry.local_variables.indexOf(var_first) < 0)
return;
const builder = new DominatorBuilder(cfg);
const blocks = var_second;
const type = this.expression_type(var_first);
// Figure out which block is dominating all accesses of those variables.
blocks.forEach(block =>
{
// If we're accessing a variable inside a continue block, this variable might be a loop variable.
// We can only use loop variables with scalars, as we cannot track static expressions for vectors.
if (this.is_continue(block)) {
// Potentially awkward case to check for.
// We might have a variable inside a loop, which is touched by the continue block,
// but is not actually a loop variable.
// The continue block is dominated by the inner part of the loop, which does not make sense in high-level
// language output because it will be declared before the body,
// so we will have to lift the dominator up to the relevant loop header instead.
builder.add_block(maplike_get(0, ir.continue_block_to_loop_header, block));
// Arrays or structs cannot be loop variables.
if (type.vecsize === 1 && type.columns === 1 && type.basetype !== SPIRBaseType.Struct && type.array.length === 0) {
// The variable is used in multiple continue blocks, this is not a loop
// candidate, signal that by setting block to -1u.
const potential: number = maplike_get(0, potential_loop_variables, var_first);
if (potential === 0)
potential_loop_variables[var_first] = block;
else
potential_loop_variables[var_first] = 0xffffffff;
}
}
builder.add_block(block);
});
builder.lift_continue_block_dominator();
// Add it to a per-block list of variables.
let dominating_block = builder.get_dominator();
// For variables whose dominating block is inside a loop, there is a risk that these variables
// actually need to be preserved across loop iterations. We can express this by adding
// a "read" access to the loop header.
// In the dominating block, we must see an OpStore or equivalent as the first access of an OpVariable.
// Should that fail, we look for the outermost loop header and tack on an access there.
// Phi nodes cannot have this problem.
if (dominating_block) {
const variable = this.get<SPIRVariable>(SPIRVariable, var_first);
if (!variable.phi_variable) {
let block = this.get<SPIRBlock>(SPIRBlock, dominating_block);
const preserve = this.may_read_undefined_variable_in_block(block, var_first);
if (preserve) {
// Find the outermost loop scope.
while (block.loop_dominator !== <BlockID>(SPIRBlock.NoDominator))
block = this.get<SPIRBlock>(SPIRBlock, block.loop_dominator);
if (block.self !== dominating_block) {
builder.add_block(block.self);
dominating_block = builder.get_dominator();
}
}
}
}
// If all blocks here are dead code, this will be 0, so the variable in question
// will be completely eliminated.
if (dominating_block) {
const block = this.get<SPIRBlock>(SPIRBlock, dominating_block);
block.dominated_variables.push(var_first);
this.get<SPIRVariable>(SPIRVariable, var_first).dominator = dominating_block;
}
});
handler.accessed_temporaries_to_block.forEach((var_second, var_first) =>
{
if (!handler.result_id_to_type.hasOwnProperty(var_first)) {
// We found a false positive ID being used, ignore.
// This should probably be an assert.
return;
}
const itrSecond = handler.result_id_to_type[var_first];
// There is no point in doing domination analysis for opaque types.
const type = this.get<SPIRType>(SPIRType, itrSecond);
if (this.type_is_opaque_value(type))
return;
const builder = new DominatorBuilder(cfg);
let force_temporary = false;
let used_in_header_hoisted_continue_block = false;
// Figure out which block is dominating all accesses of those temporaries.
const blocks = var_second;
blocks.forEach(block =>
{
builder.add_block(block);
if (blocks.size !== 1 && this.is_continue(block)) {
// The risk here is that inner loop can dominate the continue block.
// Any temporary we access in the continue block must be declared before the loop.
// This is moot for complex loops however.
const loop_header_block = this.get<SPIRBlock>(SPIRBlock, maplike_get(0, ir.continue_block_to_loop_header, block));
console.assert(loop_header_block.merge === SPIRBlockMerge.Loop);
builder.add_block(loop_header_block.self);
used_in_header_hoisted_continue_block = true;
}
});
const dominating_block = builder.get_dominator();
if (blocks.size !== 1 && this.is_single_block_loop(dominating_block)) {
// Awkward case, because the loop header is also the continue block,
// so hoisting to loop header does not help.
force_temporary = true;
}
if (dominating_block) {
// If we touch a variable in the dominating block, this is the expected setup.
// SPIR-V normally mandates this, but we have extra cases for temporary use inside loops.
const first_use_is_dominator = blocks.has(dominating_block);
if (!first_use_is_dominator || force_temporary) {
if (handler.access_chain_expressions.has(var_first)) {
// Exceptionally rare case.
// We cannot declare temporaries of access chains (except on MSL perhaps with pointers).
// Rather than do that, we force the indexing expressions to be declared in the right scope by
// tracking their usage to that end. There is no temporary to hoist.
// However, we still need to observe declaration order of the access chain.
if (used_in_header_hoisted_continue_block) {
// For this scenario, we used an access chain inside a continue block where we also registered an access to header block.
// This is a problem as we need to declare an access chain properly first with full definition.
// We cannot use temporaries for these expressions,
// so we must make sure the access chain is declared ahead of time.
// Force a complex for loop to deal with this.
// TODO: Out-of-order declaring for loops where continue blocks are emitted last might be another option.
const loop_header_block = this.get<SPIRBlock>(SPIRBlock, dominating_block);
console.assert(loop_header_block.merge === SPIRBlockMerge.Loop);
loop_header_block.complex_continue = true;
}
}
else {
// This should be very rare, but if we try to declare a temporary inside a loop,
// and that temporary is used outside the loop as well (spirv-opt inliner likes this)
// we should actually emit the temporary outside the loop.
this.hoisted_temporaries.add(var_first);
this.forced_temporaries.add(var_first);
const block_temporaries = this.get<SPIRBlock>(SPIRBlock, dominating_block).declare_temporary;
block_temporaries.push(new Pair(maplike_get(0, handler.result_id_to_type, var_first), var_first));
}
}
else if (blocks.size > 1) {
// Keep track of the temporary as we might have to declare this temporary.
// This can happen if the loop header dominates a temporary, but we have a complex fallback loop.
// In this case, the header is actually inside the for (;;) {} block, and we have problems.
// What we need to do is hoist the temporaries outside the for (;;) {} block in case the header block
// declares the temporary.
const block_temporaries = this.get<SPIRBlock>(SPIRBlock, dominating_block).potential_declare_temporary;
block_temporaries.push(new Pair(maplike_get(0, handler.result_id_to_type, var_first), var_first));
}
}
});
const seen_blocks: Set<number> = new Set();
// Now, try to analyze whether or not these variables are actually loop variables.
potential_loop_variables.forEach((loop_variable_second, loop_variable_first) =>
{
const var_ = this.get<SPIRVariable>(SPIRVariable, loop_variable_first);
let dominator = var_.dominator;
const block = loop_variable_second;
// The variable was accessed in multiple continue blocks, ignore.
if (block === 0xffffffff || block === 0)
return;
// Dead code.
if (dominator === 0)
return;
let header: BlockID = 0;
// Find the loop header for this block if we are a continue block.
{
if (ir.continue_block_to_loop_header.hasOwnProperty(block)) {
header = ir.continue_block_to_loop_header[block];
}
else if (this.get<SPIRBlock>(SPIRBlock, block).continue_block === block) {
// Also check for self-referential continue block.
header = block;
}
}
console.assert(header);
const header_block = this.get<SPIRBlock>(SPIRBlock, header);
const blocks = maplike_get<Set<number>>(Set, handler.accessed_variables_to_block, loop_variable_first);
// If a loop variable is not used before the loop, it's probably not a loop variable.
let has_accessed_variable = blocks.has(header);
// Now, there are two conditions we need to meet for the variable to be a loop variable.
// 1. The dominating block must have a branch-free path to the loop header,
// this way we statically know which expression should be part of the loop variable initializer.
// Walk from the dominator, if there is one straight edge connecting
// dominator and loop header, we statically know the loop initializer.
let static_loop_init = true;
while (dominator !== header) {
if (blocks.has(dominator))
has_accessed_variable = true;
const succ = cfg.get_succeeding_edges(dominator);
if (succ.length !== 1) {
static_loop_init = false;
break;
}
const pred = cfg.get_preceding_edges(succ[0]);
if (pred.length !== 1 || pred[0] !== dominator) {
static_loop_init = false;
break;
}
dominator = succ[0];
}
if (!static_loop_init || !has_accessed_variable)
return;
// The second condition we need to meet is that no access after the loop
// merge can occur. Walk the CFG to see if we find anything.
seen_blocks.clear();
cfg.walk_from(seen_blocks, header_block.merge_block, walk_block =>
{
// We found a block which accesses the variable outside the loop.
if (blocks.has(walk_block))
static_loop_init = false;
return true;
});
if (!static_loop_init)
return;
// We have a loop variable.
header_block.loop_variables.push(loop_variable_first);
// Need to sort here as variables come from an unordered container, and pushing stuff in wrong order
// will break reproducability in regression runs.
header_block.loop_variables.sort();
this.get<SPIRVariable>(SPIRVariable, loop_variable_first).loop_variable = true;
});
}
find_function_local_luts(entry: SPIRFunction, handler: AnalyzeVariableScopeAccessHandler, single_function: boolean)
{
const cfg = maplike_get(CFG, this.function_cfgs, entry.self);
const ir = this.ir;
// For each variable which is statically accessed.
handler.accessed_variables_to_block.forEach((accessed_var_second, accessed_var_first) =>
{
const blocks = accessed_var_second;
const var_ = this.get<SPIRVariable>(SPIRVariable, accessed_var_first);
const type = this.expression_type(accessed_var_first);
// Only consider function local variables here.
// If we only have a single function in our CFG, private storage is also fine,
// since it behaves like a function local variable.
const allow_lut = var_.storage === StorageClass.Function || (single_function && var_.storage === StorageClass.Private);
if (!allow_lut)
return;
// We cannot be a phi variable.
if (var_.phi_variable)
return;
// Only consider arrays here.
if (type.array.length === 0)
return;
// If the variable has an initializer, make sure it is a constant expression.
let static_constant_expression = 0;
if (var_.initializer) {
if (ir.ids[var_.initializer].get_type() !== Types.Constant)
return;
static_constant_expression = var_.initializer;
// There can be no stores to this variable, we have now proved we have a LUT.
if (handler.complete_write_variables_to_block.hasOwnProperty(var_.self) ||
handler.partial_write_variables_to_block.hasOwnProperty(var_.self))
return;
}
else {
// We can have one, and only one write to the variable, and that write needs to be a constant.
// No partial writes allowed.
if (handler.partial_write_variables_to_block.hasOwnProperty(var_.self))
return;
// No writes?
if (!handler.complete_write_variables_to_block.hasOwnProperty(var_.self))
return;
const itr_second = handler.complete_write_variables_to_block[var_.self];
// We write to the variable in more than one block.
const write_blocks = itr_second;
if (write_blocks.size !== 1)
return;
// The write needs to happen in the dominating block.
const builder = new DominatorBuilder(cfg);
blocks.forEach(block => builder.add_block(block));
const dominator = builder.get_dominator();
// The complete write happened in a branch or similar, cannot deduce static expression.
if (write_blocks.has(dominator))
return;
// Find the static expression for this variable.
const static_expression_handler = new StaticExpressionAccessHandler(this, var_.self);
this.traverse_all_reachable_opcodes(this.get<SPIRBlock>(SPIRBlock, dominator), static_expression_handler);
// We want one, and exactly one write
if (static_expression_handler.write_count !== 1 || static_expression_handler.static_expression === 0)
return;
// Is it a constant expression?
if (ir.ids[static_expression_handler.static_expression].get_type() !== Types.Constant)
return;
// We found a LUT!
static_constant_expression = static_expression_handler.static_expression;
}
this.get<SPIRConstant>(SPIRConstant, static_constant_expression).is_used_as_lut = true;
var_.static_expression = static_constant_expression;
var_.statically_assigned = true;
var_.remapped_variable = true;
});
}
protected may_read_undefined_variable_in_block(block: SPIRBlock, var_: number): boolean
{
for (let op of block.ops) {
const ops = this.stream(op);
switch (op.op) {
case Op.Store:
case Op.CopyMemory:
if (ops[0] === var_)
return false;
break;
case Op.AccessChain:
case Op.InBoundsAccessChain:
case Op.PtrAccessChain:
// Access chains are generally used to partially read and write. It's too hard to analyze
// if all constituents are written fully before continuing, so just assume it's preserved.
// This is the same as the parameter preservation analysis.
if (ops[2] === var_)
return true;
break;
case Op.Select:
// Variable pointers.
// We might read before writing.
if (ops[3] === var_ || ops[4] === var_)
return true;
break;
case Op.Phi: {
// Variable pointers.
// We might read before writing.
if (op.length < 2)
break;
const count = op.length - 2;
for (let i = 0; i < count; i += 2)
if (ops[i + 2] === var_)
return true;
break;
}
case Op.CopyObject:
case Op.Load:
if (ops[2] === var_)
return true;
break;
case Op.FunctionCall: {
if (op.length < 3)
break;
// May read before writing.
const count = op.length - 3;
for (let i = 0; i < count; i++)
if (ops[i + 3] === var_)
return true;
break;
}
default:
break;
}
}
// Not accessed somehow, at least not in a usual fashion.
// It's likely accessed in a branch, so assume we must preserve.
return true;
}
protected analyze_interlocked_resource_usage()
{
if (this.get_execution_model() === ExecutionModel.Fragment &&
(this.get_entry_point().flags.get(ExecutionMode.PixelInterlockOrderedEXT) ||
this.get_entry_point().flags.get(ExecutionMode.PixelInterlockUnorderedEXT) ||
this.get_entry_point().flags.get(ExecutionMode.SampleInterlockOrderedEXT) ||
this.get_entry_point().flags.get(ExecutionMode.SampleInterlockUnorderedEXT))) {
const ir = this.ir;
const prepass_handler = new InterlockedResourceAccessPrepassHandler(this, ir.default_entry_point);
this.traverse_all_reachable_opcodes(this.get<SPIRFunction>(SPIRFunction, ir.default_entry_point), prepass_handler);
const handler = new InterlockedResourceAccessHandler(this, ir.default_entry_point);
handler.interlock_function_id = prepass_handler.interlock_function_id;
handler.split_function_case = prepass_handler.split_function_case;
handler.control_flow_interlock = prepass_handler.control_flow_interlock;
handler.use_critical_section = !handler.split_function_case && !handler.control_flow_interlock;
this.traverse_all_reachable_opcodes(this.get<SPIRFunction>(SPIRFunction, ir.default_entry_point), handler);
// For GLSL. If we hit any of these cases, we have to fall back to conservative approach.
this.interlocked_is_complex =
!handler.use_critical_section || handler.interlock_function_id !== ir.default_entry_point;
}
}
instruction_to_result_type(op: Op, args: Uint32Array, length: number): { result_type: number, result_id: number }
{
// Most instructions follow the pattern of <result-type> <result-id> <arguments>.
// There are some exceptions.
switch (op) {
case Op.Store:
case Op.CopyMemory:
case Op.CopyMemorySized:
case Op.ImageWrite:
case Op.AtomicStore:
case Op.AtomicFlagClear:
case Op.EmitStreamVertex:
case Op.EndStreamPrimitive:
case Op.ControlBarrier:
case Op.MemoryBarrier:
case Op.GroupWaitEvents:
case Op.RetainEvent:
case Op.ReleaseEvent:
case Op.SetUserEventStatus:
case Op.CaptureEventProfilingInfo:
case Op.CommitReadPipe:
case Op.CommitWritePipe:
case Op.GroupCommitReadPipe:
case Op.GroupCommitWritePipe:
case Op.Line:
case Op.NoLine:
return null;
default:
if (length > 1 && this.maybe_get<SPIRType>(SPIRType, args[0]) !== null) {
return { result_type: args[0], result_id: args[1] };
}
else
return null;
}
}
combined_decoration_for_member(type: SPIRType, index: number): Bitset
{
const flags = new Bitset();
const type_meta = this.ir.find_meta(type.self);
if (type_meta) {
const members = type_meta.members;
if (index >= members.length)
return flags;
const dec = members[index];
flags.merge_or(dec.decoration_flags);
const member_type = this.get<SPIRType>(SPIRType, type.member_types[index]);
// If our member type is a struct, traverse all the child members as well recursively.
const member_childs = member_type.member_types;
for (let i = 0; i < member_childs.length; i++) {
const child_member_type = this.get<SPIRType>(SPIRType, member_childs[i]);
if (!child_member_type.pointer)
flags.merge_or(this.combined_decoration_for_member(member_type, i));
}
}
return flags;
}
is_desktop_only_format(format: ImageFormat): boolean
{
switch (format) {
// Desktop-only formats
case ImageFormat.R11fG11fB10f:
case ImageFormat.R16f:
case ImageFormat.Rgb10A2:
case ImageFormat.R8:
case ImageFormat.Rg8:
case ImageFormat.R16:
case ImageFormat.Rg16:
case ImageFormat.Rgba16:
case ImageFormat.R16Snorm:
case ImageFormat.Rg16Snorm:
case ImageFormat.Rgba16Snorm:
case ImageFormat.R8Snorm:
case ImageFormat.Rg8Snorm:
case ImageFormat.R8ui:
case ImageFormat.Rg8ui:
case ImageFormat.R16ui:
case ImageFormat.Rgb10a2ui:
case ImageFormat.R8i:
case ImageFormat.Rg8i:
case ImageFormat.R16i:
return true;
default:
break;
}
return false;
}
protected set_extended_decoration(id: number, decoration: ExtendedDecorations, value: number = 0)
{
const dec = maplike_get(Meta, this.ir.meta, id).decoration;
dec.extended.flags.set(decoration);
dec.extended.values[decoration] = value;
}
protected get_extended_decoration(id: number, decoration: ExtendedDecorations): number
{
const m = this.ir.find_meta(id);
if (!m)
return 0;
const dec = m.decoration;
if (!dec.extended.flags.get(decoration))
return get_default_extended_decoration(decoration);
return dec.extended.values[decoration];
}
protected has_extended_decoration(id: number, decoration: ExtendedDecorations): boolean
{
const m = this.ir.find_meta(id);
if (!m)
return false;
const dec = m.decoration;
return dec.extended.flags.get(decoration);
}
protected unset_extended_decoration(id: number, decoration: ExtendedDecorations)
{
const dec = maplike_get(Meta, this.ir.meta, id).decoration;
dec.extended.flags.clear(decoration);
dec.extended.values[decoration] = 0;
}
protected set_extended_member_decoration(type: number, index: number, decoration: ExtendedDecorations, value: number = 0)
{
const members = maplike_get(Meta, this.ir.meta, type).members;
if (index === members.length) {
members.push(new MetaDecoration());
}
const dec = members[index];
dec.extended.flags.set(decoration);
dec.extended.values[decoration] = value;
}
protected get_extended_member_decoration(type: number, index: number, decoration: ExtendedDecorations): number
{
const m = this.ir.find_meta(type);
if (!m)
return 0;
if (index >= m.members.length)
return 0;
const dec = m.members[index];
if (!dec.extended.flags.get(decoration))
return get_default_extended_decoration(decoration);
return dec.extended.values[decoration];
}
protected has_extended_member_decoration(type: number, index: number, decoration: ExtendedDecorations): boolean
{
const m = this.ir.find_meta(type);
if (!m)
return false;
if (index >= m.members.length)
return false;
const dec = m.members[index];
return dec.extended.flags.get(decoration);
}
protected unset_extended_member_decoration(type: number, index: number, decoration: ExtendedDecorations)
{
const members = maplike_get(Meta, this.ir.meta, type).members;
if (index === members.length) {
members.push(new MetaDecoration());
}
const dec = members[index];
dec.extended.flags.clear(decoration);
dec.extended.values[decoration] = 0;
}
type_is_array_of_pointers(type: SPIRType): boolean
{
if (!type.pointer)
return false;
// If parent type has same pointer depth, we must have an array of pointers.
return type.pointer_depth === this.get<SPIRType>(SPIRType, type.parent_type).pointer_depth;
}
protected type_is_opaque_value(type: SPIRType): boolean
{
return !type.pointer && (type.basetype === SPIRBaseType.SampledImage || type.basetype === SPIRBaseType.Image ||
type.basetype === SPIRBaseType.Sampler);
}
protected is_depth_image(type: SPIRType, id: number): boolean
{
return (type.image.depth && type.image.format === ImageFormat.Unknown) || this.comparison_ids.has(id);
}
protected reflection_ssbo_instance_name_is_significant(): boolean
{
const ir = this.ir;
if (ir.source.known) {
// UAVs from HLSL source tend to be declared in a way where the type is reused
// but the instance name is significant, and that's the name we should report.
// For GLSL, SSBOs each have their own block type as that's how GLSL is written.
return ir.source.hlsl;
}
const ssbo_type_ids: Set<number> = new Set();
let aliased_ssbo_types = false;
// If we don't have any OpSource information, we need to perform some shaky heuristics.
ir.for_each_typed_id<SPIRVariable>(SPIRVariable, (_, var_) =>
{
const type = this.get<SPIRType>(SPIRType, var_.basetype);
if (!type.pointer || var_.storage === StorageClass.Function)
return;
const ssbo = var_.storage === StorageClass.StorageBuffer ||
(var_.storage === StorageClass.Uniform && this.has_decoration(type.self, Decoration.BufferBlock));
if (ssbo) {
if (ssbo_type_ids.has(type.self))
aliased_ssbo_types = true;
else
ssbo_type_ids.add(type.self);
}
});
// If the block name is aliased, assume we have HLSL-style UAV declarations.
return aliased_ssbo_types;
}
// API for querying buffer objects.
// The type passed in here should be the base type of a resource, i.e.
// get_type(resource.base_type_id)
// as decorations are set in the basic Block type.
// The type passed in here must have these decorations set, or an exception is raised.
// Only UBOs and SSBOs or sub-structs which are part of these buffer types will have these decorations set.
protected type_struct_member_offset(type: SPIRType, index: number): number
{
const type_meta = this.ir.find_meta(type.self);
if (type_meta) {
// Decoration must be set in valid SPIR-V, otherwise throw.
const dec = type_meta.members[index];
if (dec.decoration_flags.get(Decoration.Offset))
return dec.offset;
else
throw new Error("Struct member does not have Offset set.");
}
else
throw new Error("Struct member does not have Offset set.");
}
protected type_struct_member_array_stride(type: SPIRType, index: number): number
{
const type_meta = this.ir.find_meta(type.member_types[index]);
if (type_meta) {
// Decoration must be set in valid SPIR-V, otherwise throw.
// ArrayStride is part of the array type not OpMemberDecorate.
const dec = type_meta.decoration;
if (dec.decoration_flags.get(Decoration.ArrayStride))
return dec.array_stride;
else
throw new Error("Struct member does not have ArrayStride set.");
}
else
throw new Error("Struct member does not have ArrayStride set.");
}
protected type_struct_member_matrix_stride(type: SPIRType, index: number): number
{
const type_meta = this.ir.find_meta(type.self);
if (type_meta) {
// Decoration must be set in valid SPIR-V, otherwise throw.
// MatrixStride is part of OpMemberDecorate.
const dec = type_meta.members[index];
if (dec.decoration_flags.get(Decoration.MatrixStride))
return dec.matrix_stride;
else
throw new Error("Struct member does not have MatrixStride set.");
}
else
throw new Error("Struct member does not have MatrixStride set.");
}
protected get_remapped_declared_block_name(id: number, fallback_prefer_instance_name: boolean): string
{
const itr = this.declared_block_names[id];
if (itr) {
return itr;
}
else {
const var_ = this.get<SPIRVariable>(SPIRVariable, id);
if (fallback_prefer_instance_name) {
return this.to_name(var_.self);
}
else {
const type = this.get<SPIRType>(SPIRType, var_.basetype);
const type_meta = this.ir.find_meta(type.self);
const block_name = type_meta ? type_meta.decoration.alias : null;
return (!block_name || block_name === "") ? this.get_block_fallback_name(id) : block_name;
}
}
}
protected type_is_block_like(type: SPIRType): boolean
{
if (type.basetype !== SPIRBaseType.Struct)
return false;
if (this.has_decoration(type.self, Decoration.Block) || this.has_decoration(type.self, Decoration.BufferBlock)) {
return true;
}
// Block-like types may have Offset decorations.
for (let i = 0; i < type.member_types.length; i++)
if (this.has_member_decoration(type.self, i, Decoration.Offset))
return true;
return false;
}
protected flush_phi_required(from: BlockID, to: BlockID): boolean
{
const child = this.get<SPIRBlock>(SPIRBlock, to);
for (let phi of child.phi_variables)
if (phi.parent === from)
return true;
return false;
}
protected evaluate_spec_constant_u32(spec: SPIRConstantOp): number
{
const result_type = this.get<SPIRType>(SPIRType, spec.basetype);
if (result_type.basetype !== SPIRBaseType.UInt && result_type.basetype !== SPIRBaseType.Int &&
result_type.basetype !== SPIRBaseType.Boolean) {
throw new Error("Only 32-bit integers and booleans are currently supported when evaluating specialization constants.");
}
if (!this.is_scalar(result_type))
throw new Error("Spec constant evaluation must be a scalar.\n");
let value = 0;
const eval_u32 = (id: number): number =>
{
const type = this.expression_type(id);
if (type.basetype !== SPIRBaseType.UInt && type.basetype !== SPIRBaseType.Int && type.basetype !== SPIRBaseType.Boolean) {
throw new Error("Only 32-bit integers and booleans are currently supported when evaluating specialization constants.");
}
if (!this.is_scalar(type))
throw new Error("Spec constant evaluation must be a scalar.");
const c = this.maybe_get<SPIRConstant>(SPIRConstant, id);
if (c)
return c.scalar();
else
return this.evaluate_spec_constant_u32(this.get<SPIRConstantOp>(SPIRConstantOp, id));
};
// Support the basic opcodes which are typically used when computing array sizes.
switch (spec.opcode) {
case Op.IAdd:
value = eval_u32(spec.arguments[0]) + eval_u32(spec.arguments[1]);
break;
case Op.ISub:
value = eval_u32(spec.arguments[0]) - eval_u32(spec.arguments[1]);
break;
case Op.IMul:
value = eval_u32(spec.arguments[0]) * eval_u32(spec.arguments[1]);
break;
case Op.BitwiseAnd:
value = eval_u32(spec.arguments[0]) & eval_u32(spec.arguments[1]);
break;
case Op.BitwiseOr:
value = eval_u32(spec.arguments[0]) | eval_u32(spec.arguments[1]);
break;
case Op.BitwiseXor:
value = eval_u32(spec.arguments[0]) ^ eval_u32(spec.arguments[1]);
break;
case Op.LogicalAnd:
value = eval_u32(spec.arguments[0]) & eval_u32(spec.arguments[1]);
break;
case Op.LogicalOr:
value = eval_u32(spec.arguments[0]) | eval_u32(spec.arguments[1]);
break;
case Op.ShiftLeftLogical:
value = eval_u32(spec.arguments[0]) << eval_u32(spec.arguments[1]);
break;
case Op.ShiftRightLogical:
case Op.ShiftRightArithmetic:
value = eval_u32(spec.arguments[0]) >> eval_u32(spec.arguments[1]);
break;
case Op.LogicalEqual:
case Op.IEqual:
value = eval_u32(spec.arguments[0]) === eval_u32(spec.arguments[1]) ? 1 : 0;
break;
case Op.LogicalNotEqual:
case Op.INotEqual:
value = eval_u32(spec.arguments[0]) !== eval_u32(spec.arguments[1]) ? 1 : 0;
break;
case Op.ULessThan:
case Op.SLessThan:
value = eval_u32(spec.arguments[0]) < eval_u32(spec.arguments[1]) ? 1 : 0;
break;
case Op.ULessThanEqual:
case Op.SLessThanEqual:
value = eval_u32(spec.arguments[0]) <= eval_u32(spec.arguments[1]) ? 1 : 0;
break;
case Op.UGreaterThan:
case Op.SGreaterThan:
value = eval_u32(spec.arguments[0]) > eval_u32(spec.arguments[1]) ? 1 : 0;
break;
case Op.UGreaterThanEqual:
case Op.SGreaterThanEqual:
value = eval_u32(spec.arguments[0]) >= eval_u32(spec.arguments[1]) ? 1 : 0;
break;
case Op.LogicalNot:
value = eval_u32(spec.arguments[0]) ? 0 : 1;
break;
case Op.Not:
value = ~eval_u32(spec.arguments[0]);
break;
case Op.SNegate:
value = -eval_u32(spec.arguments[0]);
break;
case Op.Select:
value = eval_u32(spec.arguments[0]) ? eval_u32(spec.arguments[1]) : eval_u32(spec.arguments[2]);
break;
case Op.UMod:
case Op.SMod:
case Op.SRem: {
const a = eval_u32(spec.arguments[0]);
const b = eval_u32(spec.arguments[1]);
if (b === 0)
throw new Error("Undefined behavior in Mod, b === 0.\n");
value = a % b;
break;
}
case Op.UDiv:
case Op.SDiv: {
const a = eval_u32(spec.arguments[0]);
const b = eval_u32(spec.arguments[1]);
if (b === 0)
throw new Error("Undefined behavior in Div, b === 0.\n");
value = a / b;
break;
}
default:
throw new Error("Unsupported spec constant opcode for evaluation.\n");
}
return value;
}
protected evaluate_constant_u32(id: number): number
{
const c = this.maybe_get<SPIRConstant>(SPIRConstant, id);
if (c)
return c.scalar();
else
return this.evaluate_spec_constant_u32(this.get<SPIRConstantOp>(SPIRConstantOp, id));
}
is_vertex_like_shader(): boolean
{
const model = this.get_execution_model();
return model === ExecutionModel.Vertex || model === ExecutionModel.Geometry ||
model === ExecutionModel.TessellationControl || model === ExecutionModel.TessellationEvaluation;
}
get_case_list(block: SPIRBlock): SPIRBlockCase[]
{
const ir = this.ir;
let width = 0;
let constant: SPIRConstant;
let var_: SPIRVariable;
// First we check if we can get the type directly from the block.condition
// since it can be a SPIRConstant or a SPIRVariable.
if ((constant = this.maybe_get<SPIRConstant>(SPIRConstant, block.condition))) {
const type = this.get<SPIRType>(SPIRType, constant.constant_type);
width = type.width;
}
else if ((var_ = this.maybe_get<SPIRVariable>(SPIRVariable, block.condition))) {
const type = this.get<SPIRType>(SPIRType, var_.basetype);
width = type.width;
}
else {
const search = ir.load_type_width[block.condition];
if (search) {
throw new Error("Use of undeclared variable on a switch statement.");
}
width = search;
}
if (width > 32)
return block.cases_64bit;
return block.cases_32bit;
}
}
function exists_unaccessed_path_to_return(cfg: CFG, block: number, blocks: Set<number>, visit_cache: Set<number>): boolean
{
// This block accesses the variable.
if (blocks.has(block))
return false;
// We are at the end of the CFG.
if (cfg.get_succeeding_edges(block).length === 0)
return true;
// If any of our successors have a path to the end, there exists a path from block.
for (let succ of cfg.get_succeeding_edges(block)) {
if (!visit_cache.has(succ)) {
if (exists_unaccessed_path_to_return(cfg, succ, blocks, visit_cache))
return true;
visit_cache.add(succ);
}
}
return false;
}
function get_default_extended_decoration(decoration: ExtendedDecorations): number
{
switch (decoration) {
case ExtendedDecorations.SPIRVCrossDecorationResourceIndexPrimary:
case ExtendedDecorations.SPIRVCrossDecorationResourceIndexSecondary:
case ExtendedDecorations.SPIRVCrossDecorationResourceIndexTertiary:
case ExtendedDecorations.SPIRVCrossDecorationResourceIndexQuaternary:
case ExtendedDecorations.SPIRVCrossDecorationInterfaceMemberIndex:
return 0xffffffff;
default:
return 0;
}
}
function storage_class_is_interface(storage: StorageClass): boolean
{
switch (storage) {
case StorageClass.Input:
case StorageClass.Output:
case StorageClass.Uniform:
case StorageClass.UniformConstant:
case StorageClass.AtomicCounter:
case StorageClass.PushConstant:
case StorageClass.StorageBuffer:
return true;
default:
return false;
}
}
|
DerSchmale/spirv4web
|
build/types/utils/string.d.ts
|
export declare function replaceCharAt(str: string, index: number, char: string): string;
export declare function convert_to_string(value: any): any;
export declare function convert_to_string(value: bigint, int64_type: string, long_long_literal_suffix: boolean): any;
|
DerSchmale/spirv4web
|
build/types/ParsedIR.d.ts
|
export declare class ParsedIR {
spirv: Uint32Array;
constructor();
}
|
DerSchmale/spirv4web
|
build/types/containers/ObjectPoolBase.d.ts
|
export declare abstract class ObjectPoolBase {
abstract deallocate_opaque(ptr: any): any;
}
|
DerSchmale/spirv4web
|
src/utils/StringStream.ts
|
export class StringStream
{
_str: string = "";
str()
{
return this._str;
}
append(...args)
{
this._str = this._str.concat(...args);
}
reset()
{
this._str = "";
}
}
|
DerSchmale/spirv4web
|
src/spirv/RayQueryIntersection.ts
|
export enum RayQueryIntersection {
CandidateKHR = 0,
CommittedKHR = 1,
Max = 0x7fffffff,
}
|
DerSchmale/spirv4web
|
src/compiler/BufferPackingStandard.ts
|
export enum BufferPackingStandard
{
Std140,
Std430,
Std140EnhancedLayout,
Std430EnhancedLayout,
_HLSLCbuffer,
_HLSLCbufferPackOffset,
PackingScalar,
PackingScalarEnhancedLayout
}
|
DerSchmale/spirv4web
|
build/types/common/SPIRExpression.d.ts
|
import { IVariant } from "./IVariant";
import { Types } from "./Types";
export declare class SPIRExpression extends IVariant {
static type: Types;
base_expression: ID;
expression: string;
expression_type: TypeID;
loaded_from: ID;
immutable: boolean;
need_transpose: boolean;
access_chain: boolean;
expression_dependencies: ID[];
implied_read_expressions: ID[];
emitted_loop_level: number;
constructor(other: SPIRExpression);
constructor(expr: string, expression_type: TypeID, immutable: boolean);
}
|
DerSchmale/spirv4web
|
build/types/utils/StringStream.d.ts
|
export declare class StringStream {
_str: string;
str(): string;
append(...args: any[]): void;
reset(): void;
}
|
DerSchmale/spirv4web
|
src/common/SPIRConstantOp.ts
|
<filename>src/common/SPIRConstantOp.ts
import { IVariant } from "./IVariant";
import { Types } from "./Types";
import { defaultCopy } from "../utils/defaultCopy";
import { Op } from "../spirv/Op";
export class SPIRConstantOp extends IVariant
{
static type = Types.ConstantOp;
opcode: Op;
arguments: number[] = [];
basetype: TypeID;
constructor(other: SPIRConstantOp);
constructor(result_type: TypeID, op: Op, args: number[]);
constructor(param0: TypeID | SPIRConstantOp, op?: Op, args?: number[])
{
super();
if (param0 instanceof SPIRConstantOp) {
defaultCopy(param0, this);
}
else {
this.basetype = param0;
this.opcode = op;
this.arguments = args.slice();
}
}
}
|
DerSchmale/spirv4web
|
build/types/compiler/AnalyzeVariableScopeAccessHandler.d.ts
|
import { OpcodeHandler } from "./OpcodeHandler";
import { SPIRFunction } from "../common/SPIRFunction";
import { Compiler } from "./Compiler";
import { SPIRBlock } from "../common/SPIRBlock";
import { Op } from "../spirv/Op";
export declare class AnalyzeVariableScopeAccessHandler extends OpcodeHandler {
compiler: Compiler;
entry: SPIRFunction;
accessed_variables_to_block: Set<number>[];
accessed_temporaries_to_block: Set<number>[];
result_id_to_type: number[];
complete_write_variables_to_block: Set<number>[];
partial_write_variables_to_block: Set<number>[];
access_chain_expressions: Set<number>;
access_chain_children: Set<number>[];
current_block: SPIRBlock;
constructor(compiler: Compiler, entry: SPIRFunction);
follow_function_call(_: SPIRFunction): boolean;
set_current_block(block: SPIRBlock): void;
notify_variable_access(id: number, block: number): void;
id_is_phi_variable(id: number): boolean;
id_is_potential_temporary(id: number): boolean;
handle(op: Op, args: Uint32Array, length: number): boolean;
handle_terminator(block: SPIRBlock): boolean;
}
|
DerSchmale/spirv4web
|
build/types/common/ConstructorTypes.d.ts
|
export declare type FromConstructor<T> = {
from(...params: any[]): T;
};
export declare type DefaultConstructor<T> = {
new (): T;
};
export declare type AnyConstructor<T> = {
new (...args: any[]): T;
};
|
DerSchmale/spirv4web
|
build/types/spirv/RayQueryCandidateIntersectionType.d.ts
|
export declare enum RayQueryCandidateIntersectionType {
RayQueryCandidateIntersectionTriangleKHR = 0,
RayQueryCandidateIntersectionAABBKHR = 1,
Max = 2147483647
}
|
DerSchmale/spirv4web
|
src/spirv/MemoryAccessMask.ts
|
<filename>src/spirv/MemoryAccessMask.ts
export enum MemoryAccessMask {
None = 0,
Volatile = 0x00000001,
Aligned = 0x00000002,
Nontemporal = 0x00000004,
MakePointerAvailable = 0x00000008,
MakePointerAvailableKHR = 0x00000008,
MakePointerVisible = 0x00000010,
MakePointerVisibleKHR = 0x00000010,
NonPrivatePointer = 0x00000020,
NonPrivatePointerKHR = 0x00000020,
}
|
DerSchmale/spirv4web
|
src/spirv/FragmentShadingRateMask.ts
|
export enum FragmentShadingRateMask
{
None = 0,
Vertical2Pixels = 0x00000001,
Vertical4Pixels = 0x00000002,
Horizontal2Pixels = 0x00000004,
Horizontal4Pixels = 0x00000008,
}
|
DerSchmale/spirv4web
|
src/compiler/CombinedImageSamplerHandler.ts
|
import { OpcodeHandler } from "./OpcodeHandler";
import { Compiler } from "./Compiler";
import {
SPIRFunction,
SPIRFunctionCombinedImageSamplerParameter,
SPIRFunctionParameter
} from "../common/SPIRFunction";
import { SPIRType, SPIRBaseType } from "../common/SPIRType";
import { SPIRExpression } from "../common/SPIRExpression";
import { defaultCopy } from "../utils/defaultCopy";
import { SPIRVariable } from "../common/SPIRVariable";
import { CombinedImageSampler } from "./CombinedImageSampler";
import { Op } from "../spirv/Op";
import { Dim } from "../spirv/Dim";
import { StorageClass } from "../spirv/StorageClass";
import { Decoration } from "../spirv/Decoration";
export class CombinedImageSamplerHandler extends OpcodeHandler
{
compiler: Compiler;
// Each function in the call stack needs its own remapping for parameters so we can deduce which global variable each texture/sampler the parameter is statically bound to.
// this is a stack of a map (Sparse array)
parameter_remapping: number[][] = [];
functions: SPIRFunction[] = [];
constructor(compiler: Compiler)
{
super();
this.compiler = compiler
}
handle(opcode: Op, args: Uint32Array, length: number): boolean
{
const compiler = this.compiler;
// We need to figure out where samplers and images are loaded from, so do only the bare bones compilation we need.
let is_fetch = false;
switch (opcode) {
case Op.Load: {
if (length < 3)
return false;
const result_type = args[0];
const type = compiler.get<SPIRType>(SPIRType, result_type);
const separate_image = type.basetype === SPIRBaseType.Image && type.image.sampled === 1;
const separate_sampler = type.basetype === SPIRBaseType.Sampler;
// If not separate image or sampler, don't bother.
if (!separate_image && !separate_sampler)
return true;
const id = args[1];
const ptr = args[2];
compiler.set<SPIRExpression>(SPIRExpression, id, "", result_type, true);
compiler.register_read(id, ptr, true);
return true;
}
case Op.InBoundsAccessChain:
case Op.AccessChain:
case Op.PtrAccessChain: {
if (length < 3)
return false;
// Technically, it is possible to have arrays of textures and arrays of samplers and combine them, but this becomes essentially
// impossible to implement, since we don't know which concrete sampler we are accessing.
// One potential way is to create a combinatorial explosion where N textures and M samplers are combined into N * M sampler2Ds,
// but this seems ridiculously complicated for a problem which is easy to work around.
// Checking access chains like this assumes we don't have samplers or textures inside uniform structs, but this makes no sense.
const result_type = args[0];
const type = compiler.get<SPIRType>(SPIRType, result_type);
const separate_image = type.basetype === SPIRBaseType.Image && type.image.sampled === 1;
const separate_sampler = type.basetype === SPIRBaseType.Sampler;
if (separate_sampler)
throw new Error("Attempting to use arrays or structs of separate samplers. This is not possible" +
" to statically remap to plain GLSL.");
if (separate_image) {
const id = args[1];
const ptr = args[2];
compiler.set<SPIRExpression>(SPIRExpression, id, "", result_type, true);
compiler.register_read(id, ptr, true);
}
return true;
}
case Op.ImageFetch:
case Op.ImageQuerySizeLod:
case Op.ImageQuerySize:
case Op.ImageQueryLevels:
case Op.ImageQuerySamples: {
// If we are fetching from a plain OpTypeImage or querying LOD, we must pre-combine with our dummy sampler.
const var_ = compiler.maybe_get_backing_variable(args[2]);
if (!var_)
return true;
const type = compiler.get<SPIRType>(SPIRType, var_.basetype);
if (type.basetype === SPIRBaseType.Image && type.image.sampled === 1 && type.image.dim !== Dim.Buffer) {
if (compiler.dummy_sampler_id === 0)
throw new Error("texelFetch without sampler was found, but no dummy sampler has been created" +
" with build_dummy_sampler_for_combined_images().");
// Do it outside.
is_fetch = true;
break;
}
return true;
}
case Op.SampledImage:
// Do it outside.
break;
default:
return true;
}
// Registers sampler2D calls used in case they are parameters so
// that their callees know which combined image samplers to propagate down the call stack.
if (this.functions.length !== 0) {
const callee = this.functions[this.functions.length - 1];
if (callee.do_combined_parameters) {
let image_id = args[2];
const image = compiler.maybe_get_backing_variable(image_id);
if (image)
image_id = image.self;
let sampler_id = is_fetch ? compiler.dummy_sampler_id : args[3];
const sampler = compiler.maybe_get_backing_variable(sampler_id);
if (sampler)
sampler_id = sampler.self;
const combined_id = args[1];
const combined_type = compiler.get<SPIRType>(SPIRType, args[0]);
this.register_combined_image_sampler(callee, combined_id, image_id, sampler_id, combined_type.image.depth);
}
}
// For function calls, we need to remap IDs which are function parameters into global variables.
// This information is statically known from the current place in the call stack.
// Function parameters are not necessarily pointers, so if we don't have a backing variable, remapping will know
// which backing variable the image/sample came from.
const image_id: VariableID = this.remap_parameter(args[2]);
const sampler_id: VariableID = is_fetch ? compiler.dummy_sampler_id : this.remap_parameter(args[3]);
const element = compiler.combined_image_samplers.find(combined => {
return combined.image_id === image_id && combined.sampler_id === sampler_id;
});
if (!element)
{
let sampled_type: number;
let combined_module_id: number;
if (is_fetch)
{
// Have to invent the sampled image type.
sampled_type = compiler.ir.increase_bound_by(1);
const type = compiler.set<SPIRType>(SPIRType, sampled_type);
defaultCopy(compiler.expression_type(args[2]), type);
type.self = sampled_type;
type.basetype = SPIRBaseType.SampledImage;
type.image.depth = false;
combined_module_id = 0;
}
else
{
sampled_type = args[0];
combined_module_id = args[1];
}
const id = compiler.ir.increase_bound_by(2);
const type_id = id + 0;
const combined_id = id + 1;
// Make a new type, pointer to OpTypeSampledImage, so we can make a variable of this type.
// We will probably have this type lying around, but it doesn't hurt to make duplicates for internal purposes.
const type = compiler.set<SPIRType>(SPIRType, type_id);
const base = compiler.get<SPIRType>(SPIRType, sampled_type);
defaultCopy(base, type);
type.pointer = true;
type.storage = StorageClass.UniformConstant;
type.parent_type = type_id;
// Build new variable.
compiler.set<SPIRVariable>(SPIRVariable, combined_id, type_id, StorageClass.UniformConstant, 0);
// Inherit RelaxedPrecision (and potentially other useful flags if deemed relevant).
// If any of OpSampledImage, underlying image or sampler are marked, inherit the decoration.
const relaxed_precision =
(sampler_id && compiler.has_decoration(sampler_id, Decoration.RelaxedPrecision)) ||
(image_id && compiler.has_decoration(image_id, Decoration.RelaxedPrecision)) ||
(combined_module_id && compiler.has_decoration(combined_module_id, Decoration.RelaxedPrecision));
if (relaxed_precision)
compiler.set_decoration(combined_id, Decoration.RelaxedPrecision);
// Propagate the array type for the original image as well.
const var_ = compiler.maybe_get_backing_variable(image_id);
if (var_)
{
const parent_type = compiler.get<SPIRType>(SPIRType, var_.basetype);
type.array = parent_type.array;
type.array_size_literal = parent_type.array_size_literal;
}
compiler.combined_image_samplers.push(new CombinedImageSampler(combined_id, image_id, sampler_id));
}
return true;
}
begin_function_scope(args: Uint32Array, length: number): boolean
{
if (length < 3)
return false;
const callee = this.compiler.get<SPIRFunction>(SPIRFunction, args[2]);
args = args.slice(3)
length -= 3;
this.push_remap_parameters(callee, args, length);
this.functions.push(callee);
return true;
}
end_function_scope(args: Uint32Array, length: number): boolean
{
if (length < 3)
return false;
const functions = this.functions;
const compiler = this.compiler;
const callee = compiler.get<SPIRFunction>(SPIRFunction, args[2]);
args = args.slice(3);
// There are two types of cases we have to handle,
// a callee might call sampler2D(texture2D, sampler) directly where
// one or more parameters originate from parameters.
// Alternatively, we need to provide combined image samplers to our callees,
// and in this case we need to add those as well.
this.pop_remap_parameters();
// Our callee has now been processed at least once.
// No point in doing it again.
callee.do_combined_parameters = false;
const params = functions.pop().combined_parameters;
if (functions.length === 0)
return true;
const caller = functions[functions.length - 1];
if (caller.do_combined_parameters)
{
for (let param of params)
{
let image_id: VariableID = param.global_image ? param.image_id : <VariableID>(args[param.image_id]);
let sampler_id: VariableID = param.global_sampler ? param.sampler_id : <VariableID>(args[param.sampler_id]);
const i = compiler.maybe_get_backing_variable(image_id);
const s = compiler.maybe_get_backing_variable(sampler_id);
if (i)
image_id = i.self;
if (s)
sampler_id = s.self;
this.register_combined_image_sampler(caller, 0, image_id, sampler_id, param.depth);
}
}
return true;
}
remap_parameter(id: number): number
{
const var_ = this.compiler.maybe_get_backing_variable(id);
if (var_)
id = var_.self;
const parameter_remapping = this.parameter_remapping;
if (parameter_remapping.length === 0)
return id;
const remapping = parameter_remapping[parameter_remapping.length - 1];
const elm = remapping[id];
if (elm !== undefined)
return elm;
else
return id;
}
push_remap_parameters(func: SPIRFunction, args: Uint32Array, length: number)
{
// If possible, pipe through a remapping table so that parameters know
// which variables they actually bind to in this scope.
// original is map<uint, uint>
const remapping: number[] = [];
for (let i = 0; i < length; i++)
remapping[func.arguments[i].id] = this.remap_parameter(args[i]);
this.parameter_remapping.push(remapping);
}
pop_remap_parameters()
{
this.parameter_remapping.pop();
}
register_combined_image_sampler(caller: SPIRFunction, combined_module_id: VariableID, image_id: VariableID, sampler_id: VariableID, depth: boolean)
{
// We now have a texture ID and a sampler ID which will either be found as a global
// or a parameter in our own function. If both are global, they will not need a parameter,
// otherwise, add it to our list.
const param = new SPIRFunctionCombinedImageSamplerParameter(0, image_id, sampler_id, true, true, depth);
const texture_itr = caller.arguments.find(p => p.id === image_id);
const sampler_itr = caller.arguments.find(p => p.id === sampler_id);
if (texture_itr)
{
param.global_image = false;
param.image_id = caller.arguments.indexOf(texture_itr);
}
if (sampler_itr)
{
param.global_sampler = false;
param.sampler_id = caller.arguments.indexOf(sampler_itr);
}
if (param.global_image && param.global_sampler)
return;
const itr = caller.combined_parameters.find(p => {
return param.image_id === p.image_id && param.sampler_id === p.sampler_id &&
param.global_image === p.global_image && param.global_sampler === p.global_sampler;
});
const compiler = this.compiler;
if (!itr)
{
const id = compiler.ir.increase_bound_by(3);
const type_id = id;
const ptr_type_id = id + 1;
const combined_id = id + 2;
const base = compiler.expression_type(image_id);
const type = compiler.set<SPIRType>(SPIRType, type_id);
const ptr_type = compiler.set<SPIRType>(SPIRType, ptr_type_id);
defaultCopy(base, type);
type.self = type_id;
type.basetype = SPIRBaseType.SampledImage;
type.pointer = false;
type.storage = StorageClass.Generic;
type.image.depth = depth;
defaultCopy(type, ptr_type);
ptr_type.pointer = true;
ptr_type.storage = StorageClass.UniformConstant;
ptr_type.parent_type = type_id;
// Build new variable.
compiler.set<SPIRVariable>(SPIRVariable, combined_id, ptr_type_id, StorageClass.Function, 0);
// Inherit RelaxedPrecision.
// If any of OpSampledImage, underlying image or sampler are marked, inherit the decoration.
const relaxed_precision =
compiler.has_decoration(sampler_id, Decoration.RelaxedPrecision) ||
compiler.has_decoration(image_id, Decoration.RelaxedPrecision) ||
(combined_module_id && compiler.has_decoration(combined_module_id, Decoration.RelaxedPrecision));
if (relaxed_precision)
compiler.set_decoration(combined_id, Decoration.RelaxedPrecision);
param.id = combined_id;
compiler.set_name(combined_id, "SPIRV_Cross_Combined" + compiler.to_name(image_id) + compiler.to_name(sampler_id));
caller.combined_parameters.push(param);
caller.shadow_arguments.push(new SPIRFunctionParameter(ptr_type_id, combined_id, 0, 0, true));
}
}
}
|
DerSchmale/spirv4web
|
build/types/parser/Parser.d.ts
|
import { ParsedIR } from "./ParsedIR";
import { SPIRType } from "../common/SPIRType";
import { IVariant, IVariantType } from "../common/IVariant";
export declare class Parser {
private ir;
private current_function;
private current_block;
private global_struct_cache;
private forward_pointer_fixups;
constructor(spirv: Uint32Array);
get_parsed_ir(): ParsedIR;
parse(): void;
private parseInstruction;
private stream;
private set;
get<T extends IVariant>(classRef: IVariantType<T>, id: number): T;
maybe_get<T extends IVariant>(classRef: IVariantType<T>, id: number): T;
types_are_logically_equivalent(a: SPIRType, b: SPIRType): boolean;
}
|
DerSchmale/spirv4web
|
build/types/Parser.d.ts
|
<reponame>DerSchmale/spirv4web
import { ParsedIR } from "./ParsedIR";
export declare class Parser {
ir: ParsedIR;
constructor(spirv: Uint32Array);
parse(): void;
}
|
DerSchmale/spirv4web
|
src/compiler/DebugHandler.ts
|
import { OpcodeHandler } from "./OpcodeHandler";
import { Compiler } from "./Compiler";
import { Op } from "../spirv/Op";
export class DebugHandler extends OpcodeHandler
{
private compiler: Compiler;
constructor(compiler)
{
super();
this.compiler = compiler;
}
handle(opcode: Op, args: Uint32Array, length: number): boolean
{
let str = ``;
switch (opcode) {
case Op.Load:
str = "load " + this.get_name(args[1]) + " " + this.get_name(args[2]);
break;
case Op.Store:
str = "store " + this.get_name(args[0]) + " " + this.get_name(args[1]);
break;
case Op.AccessChain:
str = "access chain " + this.get_name(args[1]) + " " + this.get_name(args[2]);
break;
default:
str = `UNKNOWN (${opcode})`
}
console.log(str);
return true;
}
get_name(id: number)
{
return this.compiler.get_name(id) || id;
}
}
|
DerSchmale/spirv4web
|
build/types/common/SPIRType.d.ts
|
import { IVariant } from "./IVariant";
import { Types } from "./Types";
import { Dim } from "../spirv/Dim";
import { ImageFormat } from "../spirv/ImageFormat";
import { AccessQualifier } from "../spirv/AccessQualifier";
import { StorageClass } from "../spirv/StorageClass";
export declare enum SPIRBaseType {
Unknown = 0,
Void = 1,
Boolean = 2,
SByte = 3,
UByte = 4,
Short = 5,
UShort = 6,
Int = 7,
UInt = 8,
Int64 = 9,
UInt64 = 10,
AtomicCounter = 11,
Half = 12,
Float = 13,
Double = 14,
Struct = 15,
Image = 16,
SampledImage = 17,
Sampler = 18,
AccelerationStructure = 19,
RayQuery = 20,
ControlPointArray = 21,
Interpolant = 22,
Char = 23
}
export declare class SPIRTypeImageType {
type: TypeID;
dim: Dim;
depth: boolean;
arrayed: boolean;
ms: boolean;
sampled: number;
format: ImageFormat;
access: AccessQualifier;
clone(): SPIRTypeImageType;
equals(b: SPIRTypeImageType): boolean;
}
export declare class SPIRType extends IVariant {
static type: Types;
basetype: SPIRBaseType;
width: number;
vecsize: number;
columns: number;
array: number[];
array_size_literal: boolean[];
pointer_depth: number;
pointer: boolean;
forward_pointer: boolean;
storage: StorageClass;
member_types: TypeID[];
member_type_index_redirection: number[];
image: SPIRTypeImageType;
type_alias: TypeID;
parent_type: TypeID;
member_name_cache: Set<string>;
constructor(other?: SPIRType);
}
|
DerSchmale/spirv4web
|
src/compiler/AnalyzeVariableScopeAccessHandler.ts
|
<reponame>DerSchmale/spirv4web
import { OpcodeHandler } from "./OpcodeHandler";
import { SPIRFunction } from "../common/SPIRFunction";
import { Compiler } from "./Compiler";
import { SPIRBlock, SPIRBlockTerminator } from "../common/SPIRBlock";
import { maplike_get } from "../utils/maplike_get";
import { SPIRVariable } from "../common/SPIRVariable";
import { Types } from "../common/Types";
import { SPIRExpression } from "../common/SPIRExpression";
import { SPIRBaseType } from "../common/SPIRType";
import { SPIRExtension, SPIRExtensionExtension } from "../common/SPIRExtension";
import { GLSLstd450 } from "./glsl/glsl";
import { Op } from "../spirv/Op";
export class AnalyzeVariableScopeAccessHandler extends OpcodeHandler
{
compiler: Compiler;
entry: SPIRFunction;
accessed_variables_to_block: Set<number>[] = []; // std::unordered_map<uint32_t, std::unordered_set<uint32_t>>
accessed_temporaries_to_block: Set<number>[] = []; // std::unordered_map<uint32_t, std::unordered_set<uint32_t>>
result_id_to_type: number[] = []; // std::unordered_map<uint32_t, uint32_t>;
complete_write_variables_to_block: Set<number>[] = []; // std::unordered_map<uint32_t, std::unordered_set<uint32_t>>
partial_write_variables_to_block: Set<number>[] = []; // std::unordered_map<uint32_t, std::unordered_set<uint32_t>>
access_chain_expressions: Set<number> = new Set(); // std::unordered_set<uint32_t>
// Access chains used in multiple blocks mean hoisting all the variables used to construct the access chain as not all backends can use pointers.
access_chain_children: Set<number>[] = []; // std::unordered_map<uint32_t, std::unordered_set<uint32_t>>
current_block: SPIRBlock = null;
constructor(compiler: Compiler, entry: SPIRFunction)
{
super();
this.compiler = compiler;
this.entry = entry;
}
follow_function_call(_: SPIRFunction): boolean
{
return false;
}
set_current_block(block: SPIRBlock): void
{
const compiler = this.compiler;
this.current_block = block;
// If we're branching to a block which uses OpPhi, in GLSL
// this will be a variable write when we branch,
// so we need to track access to these variables as well to
// have a complete picture.
const test_phi = (to: number) =>
{
const next = compiler.get<SPIRBlock>(SPIRBlock, to);
for (const phi of next.phi_variables) {
if (phi.parent === block.self) {
maplike_get<Set<number>>(Set, this.accessed_variables_to_block, phi.function_variable).add(block.self);
maplike_get<Set<number>>(Set, this.accessed_variables_to_block, phi.function_variable).add(next.self);
this.notify_variable_access(phi.local_variable, block.self);
}
}
};
switch (block.terminator) {
case SPIRBlockTerminator.Direct:
this.notify_variable_access(block.condition, block.self);
test_phi(block.next_block);
break;
case SPIRBlockTerminator.Select:
this.notify_variable_access(block.condition, block.self);
test_phi(block.true_block);
test_phi(block.false_block);
break;
case SPIRBlockTerminator.MultiSelect: {
this.notify_variable_access(block.condition, block.self);
const cases = compiler.get_case_list(block);
for (let target of cases)
test_phi(target.block);
if (block.default_block)
test_phi(block.default_block);
break;
}
default:
break;
}
}
notify_variable_access(id: number, block: number)
{
if (id === 0)
return;
// Access chains used in multiple blocks mean hoisting all the variables used to construct the access chain as not all backends can use pointers.
if (this.access_chain_children.hasOwnProperty(id)) {
const itr_second = this.access_chain_children[id];
itr_second.forEach(child_id => this.notify_variable_access(child_id, block));
}
if (this.id_is_phi_variable(id))
maplike_get(Set, this.accessed_variables_to_block, id).add(block);
else if (this.id_is_potential_temporary(id))
maplike_get(Set, this.accessed_temporaries_to_block, id).add(block);
}
id_is_phi_variable(id: number): boolean
{
if (id >= this.compiler.get_current_id_bound())
return false;
const var_ = this.compiler.maybe_get<SPIRVariable>(SPIRVariable, id);
return !!var_ && var_.phi_variable;
}
id_is_potential_temporary(id: number): boolean
{
if (id >= this.compiler.get_current_id_bound())
return false;
// Temporaries are not created before we start emitting code.
return this.compiler.ir.ids[id].empty() || (this.compiler.ir.ids[id].get_type() === Types.Expression);
}
handle(op: Op, args: Uint32Array, length: number): boolean
{
const compiler = this.compiler;
// Keep track of the types of temporaries, so we can hoist them out as necessary.
const result = compiler.instruction_to_result_type(op, args, length);
if (result)
this.result_id_to_type[result.result_id] = result.result_type;
switch (op) {
case Op.Store: {
if (length < 2)
return false;
const ptr = args[0];
const var_ = compiler.maybe_get_backing_variable(ptr);
// If we store through an access chain, we have a partial write.
if (var_) {
maplike_get(Set, this.accessed_variables_to_block, var_.self).add(this.current_block.self);
if (var_.self === ptr)
maplike_get(Set, this.complete_write_variables_to_block, var_.self).add(this.current_block.self);
else
maplike_get(Set, this.partial_write_variables_to_block, var_.self).add(this.current_block.self);
}
// args[0] might be an access chain we have to track use of.
this.notify_variable_access(args[0], this.current_block.self);
// Might try to store a Phi variable here.
this.notify_variable_access(args[1], this.current_block.self);
break;
}
case Op.AccessChain:
case Op.InBoundsAccessChain:
case Op.PtrAccessChain: {
if (length < 3)
return false;
// Access chains used in multiple blocks mean hoisting all the variables used to construct the access chain as not all backends can use pointers.
const ptr = args[2];
const var_ = this.compiler.maybe_get<SPIRVariable>(SPIRVariable, ptr);
if (var_) {
maplike_get(Set, this.accessed_variables_to_block, var_.self).add(this.current_block.self);
maplike_get(Set, this.access_chain_children, args[1]).add(var_.self);
}
// args[2] might be another access chain we have to track use of.
for (let i = 2; i < length; i++) {
this.notify_variable_access(args[i], this.current_block.self);
maplike_get(Set, this.access_chain_children, args[1]).add(args[i]);
}
// Also keep track of the access chain pointer itself.
// In exceptionally rare cases, we can end up with a case where
// the access chain is generated in the loop body, but is consumed in continue block.
// This means we need complex loop workarounds, and we must detect this via CFG analysis.
this.notify_variable_access(args[1], this.current_block.self);
// The result of an access chain is a fixed expression and is not really considered a temporary.
const e = compiler.set<SPIRExpression>(SPIRExpression, args[1], "", args[0], true);
const backing_variable = compiler.maybe_get_backing_variable(ptr);
e.loaded_from = backing_variable ? <VariableID>(backing_variable.self) : <VariableID>(0);
// Other backends might use SPIRAccessChain for this later.
compiler.ir.ids[args[1]].set_allow_type_rewrite();
this.access_chain_expressions.add(args[1]);
break;
}
case Op.CopyMemory: {
if (length < 2)
return false;
const lhs: ID = args[0];
const rhs: ID = args[1];
let var_ = compiler.maybe_get_backing_variable(lhs);
// If we store through an access chain, we have a partial write.
if (var_) {
maplike_get(Set, this.accessed_variables_to_block, var_.self).add(this.current_block.self);
if (var_.self === lhs)
maplike_get(Set, this.complete_write_variables_to_block, var_.self).add(this.current_block.self);
else
maplike_get(Set, this.partial_write_variables_to_block, var_.self).add(this.current_block.self);
}
// args[0:1] might be access chains we have to track use of.
for (let i = 0; i < 2; i++)
this.notify_variable_access(args[i], this.current_block.self);
var_ = compiler.maybe_get_backing_variable(rhs);
if (var_)
maplike_get(Set, this.accessed_variables_to_block, var_.self).add(this.current_block.self);
break;
}
case Op.CopyObject: {
if (length < 3)
return false;
const var_ = compiler.maybe_get_backing_variable(args[2]);
if (var_)
maplike_get(Set, this.accessed_variables_to_block, var_.self).add(this.current_block.self);
// Might be an access chain which we have to keep track of.
this.notify_variable_access(args[1], this.current_block.self);
if (this.access_chain_expressions.has(args[2]))
this.access_chain_expressions.add(args[1]);
// Might try to copy a Phi variable here.
this.notify_variable_access(args[2], this.current_block.self);
break;
}
case Op.Load: {
if (length < 3)
return false;
const ptr = args[2];
const var_ = compiler.maybe_get_backing_variable(ptr);
if (var_)
maplike_get(Set, this.accessed_variables_to_block, var_.self).add(this.current_block.self);
// Loaded value is a temporary.
this.notify_variable_access(args[1], this.current_block.self);
// Might be an access chain we have to track use of.
this.notify_variable_access(args[2], this.current_block.self);
break;
}
case Op.FunctionCall: {
if (length < 3)
return false;
// Return value may be a temporary.
if (compiler.get_type(args[0]).basetype !== SPIRBaseType.Void)
this.notify_variable_access(args[1], this.current_block.self);
length -= 3;
args = args.slice(3);
for (let i = 0; i < length; i++) {
const var_ = compiler.maybe_get_backing_variable(args[i]);
if (var_) {
maplike_get(Set, this.accessed_variables_to_block, var_.self).add(this.current_block.self);
// Assume we can get partial writes to this variable.
maplike_get(Set, this.partial_write_variables_to_block, var_.self).add(this.current_block.self);
}
// Cannot easily prove if argument we pass to a function is completely written.
// Usually, functions write to a dummy variable,
// which is then copied to in full to the real argument.
// Might try to copy a Phi variable here.
this.notify_variable_access(args[i], this.current_block.self);
}
break;
}
case Op.Select: {
// In case of variable pointers, we might access a variable here.
// We cannot prove anything about these accesses however.
for (let i = 1; i < length; i++) {
if (i >= 3) {
const var_ = compiler.maybe_get_backing_variable(args[i]);
if (var_) {
maplike_get(Set, this.accessed_variables_to_block, var_.self).add(this.current_block.self);
// Assume we can get partial writes to this variable.
maplike_get(Set, this.partial_write_variables_to_block, var_.self).add(this.current_block.self);
}
}
// Might try to copy a Phi variable here.
this.notify_variable_access(args[i], this.current_block.self);
}
break;
}
case Op.ExtInst: {
for (let i = 4; i < length; i++)
this.notify_variable_access(args[i], this.current_block.self);
this.notify_variable_access(args[1], this.current_block.self);
const extension_set = args[2];
if (compiler.get<SPIRExtension>(SPIRExtension, extension_set).ext === SPIRExtensionExtension.GLSL) {
const op_450 = <GLSLstd450>(args[3]);
switch (op_450) {
case GLSLstd450.Modf:
case GLSLstd450.Frexp: {
const ptr = args[5];
const var_ = compiler.maybe_get_backing_variable(ptr);
if (var_) {
maplike_get(Set, this.accessed_variables_to_block, var_.self).add(this.current_block.self);
if (var_.self === ptr)
maplike_get(Set, this.complete_write_variables_to_block, var_.self).add(this.current_block.self);
else
maplike_get(Set, this.partial_write_variables_to_block, var_.self).add(this.current_block.self);
}
break;
}
default:
break;
}
}
break;
}
case Op.ArrayLength:
// Only result is a temporary.
this.notify_variable_access(args[1], this.current_block.self);
break;
case Op.Line:
case Op.NoLine:
// Uses literals, but cannot be a phi variable or temporary, so ignore.
break;
// Atomics shouldn't be able to access function-local variables.
// Some GLSL builtins access a pointer.
case Op.CompositeInsert:
case Op.VectorShuffle:
// Specialize for opcode which contains literals.
for (let i = 1; i < 4; i++)
this.notify_variable_access(args[i], this.current_block.self);
break;
case Op.CompositeExtract:
// Specialize for opcode which contains literals.
for (let i = 1; i < 3; i++)
this.notify_variable_access(args[i], this.current_block.self);
break;
case Op.ImageWrite:
for (let i = 0; i < length; i++) {
// Argument 3 is a literal.
if (i !== 3)
this.notify_variable_access(args[i], this.current_block.self);
}
break;
case Op.ImageSampleImplicitLod:
case Op.ImageSampleExplicitLod:
case Op.ImageSparseSampleImplicitLod:
case Op.ImageSparseSampleExplicitLod:
case Op.ImageSampleProjImplicitLod:
case Op.ImageSampleProjExplicitLod:
case Op.ImageSparseSampleProjImplicitLod:
case Op.ImageSparseSampleProjExplicitLod:
case Op.ImageFetch:
case Op.ImageSparseFetch:
case Op.ImageRead:
case Op.ImageSparseRead:
for (let i = 1; i < length; i++) {
// Argument 4 is a literal.
if (i !== 4)
this.notify_variable_access(args[i], this.current_block.self);
}
break;
case Op.ImageSampleDrefImplicitLod:
case Op.ImageSampleDrefExplicitLod:
case Op.ImageSparseSampleDrefImplicitLod:
case Op.ImageSparseSampleDrefExplicitLod:
case Op.ImageSampleProjDrefImplicitLod:
case Op.ImageSampleProjDrefExplicitLod:
case Op.ImageSparseSampleProjDrefImplicitLod:
case Op.ImageSparseSampleProjDrefExplicitLod:
case Op.ImageGather:
case Op.ImageSparseGather:
case Op.ImageDrefGather:
case Op.ImageSparseDrefGather:
for (let i = 1; i < length; i++) {
// Argument 5 is a literal.
if (i !== 5)
this.notify_variable_access(args[i], this.current_block.self);
}
break;
default: {
// Rather dirty way of figuring out where Phi variables are used.
// As long as only IDs are used, we can scan through instructions and try to find any evidence that
// the ID of a variable has been used.
// There are potential false positives here where a literal is used in-place of an ID,
// but worst case, it does not affect the correctness of the compile.
// Exhaustive analysis would be better here, but it's not worth it for now.
for (let i = 0; i < length; i++)
this.notify_variable_access(args[i], this.current_block.self);
break;
}
}
return true;
}
handle_terminator(block: SPIRBlock): boolean
{
switch (block.terminator) {
case SPIRBlockTerminator.Return:
if (block.return_value)
this.notify_variable_access(block.return_value, block.self);
break;
case SPIRBlockTerminator.Select:
case SPIRBlockTerminator.MultiSelect:
this.notify_variable_access(block.condition, block.self);
break;
default:
break;
}
return true;
}
}
|
DerSchmale/spirv4web
|
src/common/SPIRConstant.ts
|
<reponame>DerSchmale/spirv4web
// @ts-ignore
import { createWith } from "@derschmale/array-utils";
import { IVariant } from "./IVariant";
import { Types } from "./Types";
import { defaultClone, defaultCopy } from "../utils/defaultCopy";
import { SPIRType } from "./SPIRType";
import { uint32 } from "../utils/ensure_types";
const u = new DataView(new ArrayBuffer(4));
// like a union
export class SPIRConstantConstant
{
value: ArrayBuffer = new ArrayBuffer(16);
private _dataView: DataView = new DataView(this.value);
get u32(): number
{
return this._dataView.getUint32(0);
}
set u32(value: number)
{
this._dataView.setUint32(0, value);
}
get i32(): number
{
return this._dataView.getInt32(0);
}
set i32(value: number)
{
this._dataView.setInt32(0, value);
}
get f32(): number
{
return this._dataView.getFloat32(0);
}
set f32(value: number)
{
this._dataView.setFloat32(0, value);
}
get u64(): bigint
{
return this._dataView.getBigUint64(0);
}
set u64(value: bigint)
{
this._dataView.setBigUint64(0, value);
}
get i64(): bigint
{
return this._dataView.getBigInt64(0);
}
set i64(value: bigint)
{
this._dataView.setBigInt64(0, value);
}
get f64(): number
{
return this._dataView.getFloat64(0);
}
set f64(value: number)
{
this._dataView.setFloat64(0, value);
}
clone()
{
return defaultClone(SPIRConstantConstant, this);
}
}
export class SPIRConstantConstantVector
{
r: SPIRConstantConstant[];
// If !== 0, this element is a specialization constant, and we should keep track of it as such.
id: ID[];
vecsize: number = 1;
constructor()
{
this.r = createWith(4, () => new SPIRConstantConstant());
this.id = createWith(4, () => 0);
}
clone()
{
return defaultClone(SPIRConstantConstantVector, this);
}
}
export class SPIRConstantConstantMatrix
{
c: SPIRConstantConstantVector[];
// If !== 0, this column is a specialization constant, and we should keep track of it as such.
id: ID[];
columns: number = 1;
constructor()
{
this.c = createWith(4, () => new SPIRConstantConstantVector());
this.id = createWith(4, () => 0);
}
clone()
{
return defaultClone(SPIRConstantConstantMatrix, this);
}
}
export class SPIRConstant extends IVariant
{
static type = Types.Constant;
constant_type: TypeID = 0;
m: SPIRConstantConstantMatrix = new SPIRConstantConstantMatrix();
// If this constant is a specialization constant (i.e. created with OpSpecConstant*).
specialization: boolean = false;
// If this constant is used as an array length which creates specialization restrictions on some backends.
is_used_as_array_length: boolean = false;
// If true, this is a LUT, and should always be declared in the outer scope.
is_used_as_lut: boolean = false;
// For composites which are constant arrays, etc.
// should be ConstantID[]
subconstants: Uint32Array = new Uint32Array();
// Non-Vulkan GLSL, HLSL and sometimes MSL emits defines for each specialization constant,
// and uses them to initialize the constant. This allows the user
// to still be able to specialize the value by supplying corresponding
// preprocessor directives before compiling the shader.
specialization_constant_macro_name: string = "";
f16_to_f32(u16_value: number): number
{
// Based on the GLM implementation.
let s = (u16_value >> 15) & 0x1;
let e = (u16_value >> 10) & 0x1f;
let m = (u16_value >> 0) & 0x3ff;
if (e === 0) {
if (m === 0) {
u.setUint32(0, s << 31);
return u.getFloat32(0);
}
else {
while ((m & 0x400) === 0) {
m <<= 1;
e--;
}
e++;
m = uint32(m & uint32(~0x400));
}
}
else if (e === 31) {
if (m === 0) {
u.setUint32(0, (s << 31) | 0x7f800000);
return u.getFloat32(0);
}
else {
u.setUint32(0, (s << 31) | 0x7f800000 | (m << 13));
return u.getFloat32(0);
}
}
e += 127 - 15;
m <<= 13;
u.setUint32(0, (s << 31) | (e << 23) | m);
return u.getFloat32(0);
}
specialization_constant_id(col: number, row?: number): number
{
if (row === undefined)
return this.m.id[col];
else
return this.m.c[col].id[row];
}
scalar(col: number = 0, row: number = 0): number
{
return this.m.c[col].r[row].u32;
}
scalar_i16(col: number = 0, row: number = 0): number
{
return this.m.c[col].r[row].u32 & 0xffff;
}
scalar_u16(col: number = 0, row: number = 0): number
{
return this.m.c[col].r[row].u32 & 0xffff;
}
scalar_i8(col: number = 0, row: number = 0): number
{
return this.m.c[col].r[row].u32 & 0xff;
}
scalar_u8(col: number = 0, row: number = 0): number
{
return this.m.c[col].r[row].u32 & 0xff;
}
scalar_f16(col: number = 0, row: number = 0): number
{
return this.f16_to_f32(this.scalar_u16(col, row));
}
scalar_f32(col: number = 0, row: number = 0): number
{
return this.m.c[col].r[row].f32;
}
scalar_i32(col: number = 0, row: number = 0): number
{
return this.m.c[col].r[row].i32;
}
scalar_f64(col: number = 0, row: number = 0): number
{
return this.m.c[col].r[row].f64;
}
scalar_i64(col: number = 0, row: number = 0): bigint
{
return this.m.c[col].r[row].i64;
}
scalar_u64(col: number = 0, row: number = 0): bigint
{
return this.m.c[col].r[row].u64;
}
vector(): SPIRConstantConstantVector
{
return this.m.c[0];
}
vector_size(): number
{
return this.m.c[0].vecsize;
}
columns(): number
{
return this.m.columns;
}
make_null(constant_type: SPIRType)
{
this.m = new SPIRConstantConstantMatrix();
this.m.columns = constant_type.columns;
for (let c of this.m.c)
c.vecsize = constant_type.vecsize;
}
constant_is_null(): boolean
{
if (this.specialization)
return false;
if (this.subconstants.length !== 0)
return false;
for (let col = 0; col < this.columns(); col++)
for (let row = 0; row < this.vector_size(); row++)
if (this.scalar_u64(col, row) !== BigInt(0))
return false;
return true;
}
constructor();
constructor(other: SPIRConstant);
constructor(constant_type: TypeID);
constructor(constant_type: TypeID, elements: number[], num_elements: number, specialized: boolean);
constructor(constant_type: TypeID, v0: number, specialized: boolean);
constructor(constant_type: TypeID, v0: bigint, specialized: boolean);
constructor(constant_type: TypeID, vector_elements: SPIRConstant[], num_elements: number, specialized: boolean);
constructor(...args)
{
super();
// default constructor
if (args.length === 0)
return;
if (args.length === 1) {
if (args[0] instanceof SPIRConstant)
defaultCopy(args[0], this);
else
this._construct(args[0]);
}
else if (typeof args[1] === "bigint")
this._constructScalar64(args[0], args[1], args[2]);
else if (typeof args[1] === "number")
this._constructScalar32(args[0], args[1], args[2]);
else if (typeof args[1][0] === "number")
this._constructArray(args[0], args[1], args[2], args[3]);
else
this._constructVecMat(args[0], args[1], args[2], args[3]);
}
_construct(constant_type: TypeID)
{
this.constant_type = constant_type;
}
_constructArray(constant_type: TypeID, elements: Uint32Array, num_elements: number, specialized: boolean)
{
this.constant_type = constant_type;
this.specialization = specialized;
this.subconstants = elements.slice();
}
// Construct scalar (32-bit).
_constructScalar32(constant_type: TypeID, v0: number, specialized: boolean)
{
this.constant_type = constant_type;
this.specialization = specialized;
this.m.c[0].r[0].u32 = v0;
this.m.c[0].vecsize = 1;
this.m.columns = 1;
}
// Construct scalar (64-bit).
_constructScalar64(constant_type: TypeID, v0: bigint, specialized: boolean)
{
this.constant_type = constant_type;
this.specialization = specialized;
this.m.c[0].r[0].u64 = v0;
this.m.c[0].vecsize = 1;
this.m.columns = 1;
}
// Construct vectors and matrices.
_constructVecMat(constant_type: TypeID, vector_elements: SPIRConstant[], num_elements: number, specialized: boolean)
{
this.constant_type = constant_type;
this.specialization = specialized;
const matrix = vector_elements[0].m.c[0].vecsize > 1;
if (matrix) {
this.m.columns = num_elements;
for (let i = 0; i < num_elements; i++) {
this.m.c[i] = vector_elements[i].m.c[0];
if (vector_elements[i].specialization)
this.m.id[i] = vector_elements[i].self;
}
}
else {
this.m.c[0].vecsize = num_elements;
this.m.columns = 1;
for (let i = 0; i < num_elements; i++) {
this.m.c[0].r[i] = vector_elements[i].m.c[0].r[0];
if (vector_elements[i].specialization)
this.m.c[0].id[i] = vector_elements[i].self;
}
}
}
}
|
DerSchmale/spirv4web
|
build/types/spirv/KernelEnqueueFlags.d.ts
|
<filename>build/types/spirv/KernelEnqueueFlags.d.ts<gh_stars>0
export declare enum KernelEnqueueFlags {
NoWait = 0,
WaitKernel = 1,
WaitWorkGroup = 2,
Max = 2147483647
}
|
DerSchmale/spirv4web
|
build/types/spirv/FPRoundingMode.d.ts
|
export declare enum FPRoundingMode {
RTE = 0,
RTZ = 1,
RTP = 2,
RTN = 3,
Max = 2147483647
}
|
DerSchmale/spirv4web
|
src/utils/maplike_get.ts
|
import { DefaultConstructor } from "../common/ConstructorTypes";
import { Dict } from "./Dict";
export function maplike_get<T>(classRef: DefaultConstructor<T>, map: T[] | Dict<T>, id: number | string): T;
export function maplike_get(classRef: number, map: number[] | Dict<number>, id: number | string): number;
export function maplike_get(classRef: string, map: string[] | Dict<string>, id: number | string): string;
// creates an element if it does not exist, similar to a C++ map
// pass in 0 for number map
export function maplike_get<T>(classRef: DefaultConstructor<T> | number | string, map: T[] | Dict<T>, id: number | string): T
{
if (!map[id]) {
map[id] = typeof classRef === "number" || typeof classRef === "string"? classRef : new classRef();
}
return map[id];
}
|
DerSchmale/spirv4web
|
build/types/cfg/CFG.d.ts
|
import { Compiler } from "../compiler/Compiler";
import { SPIRFunction } from "../common/SPIRFunction";
export declare class CFG {
private compiler;
private func;
private preceding_edges;
private succeeding_edges;
private immediate_dominators;
private visit_order;
private post_order;
private empty_vector;
private visit_count;
constructor(compiler?: Compiler, func?: SPIRFunction);
get_compiler(): Compiler;
get_function(): SPIRFunction;
get_immediate_dominator(block: number): number;
get_visit_order(block: number): number;
find_common_dominator(a: number, b: number): number;
get_preceding_edges(block: number): number[];
get_succeeding_edges(block: number): number[];
walk_from(seen_blocks: Set<number>, block: number, op: (block: number) => boolean): void;
find_loop_dominator(block_id: number): number;
node_terminates_control_flow_in_sub_graph(from: BlockID, to: BlockID): boolean;
private add_branch;
private build_post_order_visit_order;
private build_immediate_dominators;
private post_order_visit;
private is_back_edge;
private has_visited_forward_edge;
}
|
DerSchmale/spirv4web
|
src/compiler/CombinedImageSamplerDrefHandler.ts
|
import { OpcodeHandler } from "./OpcodeHandler";
import { Compiler } from "./Compiler";
import { Op } from "../spirv/Op";
export class CombinedImageSamplerDrefHandler extends OpcodeHandler
{
compiler: Compiler;
dref_combined_samplers: Set<number> = new Set<number>();
constructor(compiler: Compiler)
{
super();
this.compiler = compiler;
}
handle(opcode: Op, args: Uint32Array, length: number): boolean
{
// Mark all sampled images which are used with Dref.
switch (opcode)
{
case Op.ImageSampleDrefExplicitLod:
case Op.ImageSampleDrefImplicitLod:
case Op.ImageSampleProjDrefExplicitLod:
case Op.ImageSampleProjDrefImplicitLod:
case Op.ImageSparseSampleProjDrefImplicitLod:
case Op.ImageSparseSampleDrefImplicitLod:
case Op.ImageSparseSampleProjDrefExplicitLod:
case Op.ImageSparseSampleDrefExplicitLod:
case Op.ImageDrefGather:
case Op.ImageSparseDrefGather:
this.dref_combined_samplers.add(args[2]);
return true;
default:
break;
}
return true;
}
}
|
DerSchmale/spirv4web
|
src/spirv/ImageChannelDataType.ts
|
export enum ImageChannelDataType {
SnormInt8 = 0,
SnormInt16 = 1,
UnormInt8 = 2,
UnormInt16 = 3,
UnormShort565 = 4,
UnormShort555 = 5,
UnormInt101010 = 6,
SignedInt8 = 7,
SignedInt16 = 8,
SignedInt32 = 9,
UnsignedInt8 = 10,
UnsignedInt16 = 11,
UnsignedInt32 = 12,
HalfFloat = 13,
Float = 14,
UnormInt24 = 15,
UnormInt101010_2 = 16,
Max = 0x7fffffff,
}
|
DerSchmale/spirv4web
|
build/types/spirv/FunctionControlMask.d.ts
|
export declare enum FunctionControlMask {
None = 0,
Inline = 1,
DontInline = 2,
Pure = 4,
Const = 8
}
|
DerSchmale/spirv4web
|
build/types/common/TypedID.d.ts
|
<gh_stars>0
declare type VariableID = number;
declare type TypeID = number;
declare type ConstantID = number;
declare type FunctionID = number;
declare type BlockID = number;
declare type ID = number;
|
DerSchmale/spirv4web
|
src/compiler/glsl/GLSLPrecision.ts
|
export enum GLSLPrecision
{
DontCare,
Lowp,
Mediump,
Highp
}
|
DerSchmale/spirv4web
|
src/compiler/glsl/GLSLFragmentOptions.ts
|
<reponame>DerSchmale/spirv4web<filename>src/compiler/glsl/GLSLFragmentOptions.ts
import { GLSLPrecision } from "./GLSLPrecision";
export class GLSLFragmentOptions
{
// Add precision mediump float in ES targets when emitting GLES source.
// Add precision highp int in ES targets when emitting GLES source.
default_float_precision: GLSLPrecision = GLSLPrecision.Mediump;
default_int_precision: GLSLPrecision = GLSLPrecision.Highp;
}
|
DerSchmale/spirv4web
|
build/types/spirv/RayQueryCommittedIntersectionType.d.ts
|
export declare enum RayQueryCommittedIntersectionType {
NoneKHR = 0,
TriangleKHR = 1,
GeneratedKHR = 2,
Max = 2147483647
}
|
DerSchmale/spirv4web
|
build/types/common/Meta.d.ts
|
import { Bitset } from "./Bitset";
import { BuiltIn } from "../spirv/BuiltIn";
import { FPRoundingMode } from "../spirv/FPRoundingMode";
export declare class MetaDecorationExtended {
flags: Bitset;
values: Uint32Array;
clone(): MetaDecorationExtended;
}
export declare class MetaDecoration {
alias: string;
qualified_alias: string;
hlsl_semantic: string;
decoration_flags: Bitset;
builtin_type: BuiltIn;
location: number;
component: number;
set: number;
binding: number;
offset: number;
xfb_buffer: number;
xfb_stride: number;
stream: number;
array_stride: number;
matrix_stride: number;
input_attachment: number;
spec_id: number;
index: number;
fp_rounding_mode: FPRoundingMode;
builtin: boolean;
extended: MetaDecorationExtended;
clone(): MetaDecoration;
}
export declare class Meta {
decoration: MetaDecoration;
members: MetaDecoration[];
decoration_word_offset: number[];
hlsl_is_magic_counter_buffer: boolean;
hlsl_magic_counter_buffer: number;
}
|
DerSchmale/spirv4web
|
build/types/spirv/ExecutionModel.d.ts
|
export declare enum ExecutionModel {
Vertex = 0,
TessellationControl = 1,
TessellationEvaluation = 2,
Geometry = 3,
Fragment = 4,
GLCompute = 5,
Kernel = 6,
TaskNV = 5267,
MeshNV = 5268,
RayGenerationKHR = 5313,
RayGenerationNV = 5313,
IntersectionKHR = 5314,
IntersectionNV = 5314,
AnyHitKHR = 5315,
AnyHitNV = 5315,
ClosestHitKHR = 5316,
ClosestHitNV = 5316,
MissKHR = 5317,
MissNV = 5317,
CallableKHR = 5318,
CallableNV = 5318,
Max = 2147483647
}
|
DerSchmale/spirv4web
|
build/types/spirv/Decoration.d.ts
|
export declare enum Decoration {
RelaxedPrecision = 0,
SpecId = 1,
Block = 2,
BufferBlock = 3,
RowMajor = 4,
ColMajor = 5,
ArrayStride = 6,
MatrixStride = 7,
GLSLShared = 8,
GLSLPacked = 9,
CPacked = 10,
BuiltIn = 11,
NoPerspective = 13,
Flat = 14,
Patch = 15,
Centroid = 16,
Sample = 17,
Invariant = 18,
Restrict = 19,
Aliased = 20,
Volatile = 21,
Constant = 22,
Coherent = 23,
NonWritable = 24,
NonReadable = 25,
Uniform = 26,
UniformId = 27,
SaturatedConversion = 28,
Stream = 29,
Location = 30,
Component = 31,
Index = 32,
Binding = 33,
DescriptorSet = 34,
Offset = 35,
XfbBuffer = 36,
XfbStride = 37,
FuncParamAttr = 38,
FPRoundingMode = 39,
FPFastMathMode = 40,
LinkageAttributes = 41,
NoContraction = 42,
InputAttachmentIndex = 43,
Alignment = 44,
MaxByteOffset = 45,
AlignmentId = 46,
MaxByteOffsetId = 47,
NoSignedWrap = 4469,
NoUnsignedWrap = 4470,
ExplicitInterpAMD = 4999,
OverrideCoverageNV = 5248,
PassthroughNV = 5250,
ViewportRelativeNV = 5252,
SecondaryViewportRelativeNV = 5256,
PerPrimitiveNV = 5271,
PerViewNV = 5272,
PerTaskNV = 5273,
PerVertexNV = 5285,
NonUniform = 5300,
NonUniformEXT = 5300,
RestrictPointer = 5355,
RestrictPointerEXT = 5355,
AliasedPointer = 5356,
AliasedPointerEXT = 5356,
ReferencedIndirectlyINTEL = 5602,
CounterBuffer = 5634,
HlslCounterBufferGOOGLE = 5634,
HlslSemanticGOOGLE = 5635,
UserSemantic = 5635,
UserTypeGOOGLE = 5636,
RegisterINTEL = 5825,
MemoryINTEL = 5826,
NumbanksINTEL = 5827,
BankwidthINTEL = 5828,
MaxPrivateCopiesINTEL = 5829,
SinglepumpINTEL = 5830,
DoublepumpINTEL = 5831,
MaxReplicatesINTEL = 5832,
SimpleDualPortINTEL = 5833,
MergeINTEL = 5834,
BankBitsINTEL = 5835,
ForcePow2DepthINTEL = 5836,
Max = 2147483647
}
|
DerSchmale/spirv4web
|
build/types/spirv/LinkageType.d.ts
|
export declare enum LinkageType {
Export = 0,
Import = 1,
Max = 2147483647
}
|
DerSchmale/spirv4web
|
build/types/common/SPIRAccessChain.d.ts
|
<reponame>DerSchmale/spirv4web<gh_stars>0
import { IVariant } from "./IVariant";
import { Types } from "./Types";
import { StorageClass } from "../spirv/StorageClass";
export declare class SPIRAccessChain extends IVariant {
static type: Types;
basetype: TypeID;
storage: StorageClass;
base: string;
dynamic_index: string;
static_index: number;
loaded_from: VariableID;
matrix_stride: number;
array_stride: number;
row_major_matrix: boolean;
immutable: boolean;
implied_read_expressions: ID[];
constructor(other: SPIRAccessChain);
constructor(basetype: TypeID, storage: StorageClass, base: string, dynamic_index: string, static_index: number);
}
|
DerSchmale/spirv4web
|
src/spirv/SamplerFilterMode.ts
|
export enum SamplerFilterMode
{
Nearest = 0,
Linear = 1,
Max = 0x7fffffff
}
|
DerSchmale/spirv4web
|
src/common/IVariant.ts
|
<reponame>DerSchmale/spirv4web<gh_stars>0
import { defaultCopy } from "../utils/defaultCopy";
import { ObjectPoolBase } from "../containers/ObjectPoolBase";
import { ObjectPool } from "../containers/ObjectPool";
export type IVariantType<T> = {
type: TypeID,
new(other: T): T
}
export abstract class IVariant
{
self: ID = 0;
clone(pool: ObjectPoolBase): this
{
const p = <ObjectPool<this>>(pool);
const c = p.allocate(this);
defaultCopy(this, c);
return c;
}
}
|
DerSchmale/spirv4web
|
build/types/spirv/KernelProfilingInfoMask.d.ts
|
export declare enum KernelProfilingInfoMask {
None = 0,
CmdExecTime = 1
}
|
DerSchmale/spirv4web
|
src/spirv/FragmentShadingRateShift.ts
|
export enum FragmentShadingRateShift
{
Vertical2Pixels = 0,
Vertical4Pixels = 1,
Horizontal2Pixels = 2,
Horizontal4Pixels = 3,
Max = 0x7fffffff,
}
|
DerSchmale/spirv4web
|
src/utils/Pointer.ts
|
<filename>src/utils/Pointer.ts
// this just wraps a value that we can share. Only useful for primitives.
export class Pointer<T>
{
private value: T;
constructor(value?: T)
{
this.value = value;
}
get(): T {
return this.value;
}
set(value: T) {
this.value = value;
}
}
// this allows us to alias an object property. Only useful for primitives.
export class MemberPointer<A, B>
{
private owner: A;
private propName: any;
constructor(owner: A, propName: string)
{
this.owner = owner;
this.propName = propName;
}
get(): B
{
return this.owner[this.propName];
}
set(value: B)
{
this.owner[this.propName] = value;
}
}
|
DerSchmale/spirv4web
|
src/spirv/KernelProfilingInfoShift.ts
|
<filename>src/spirv/KernelProfilingInfoShift.ts
export enum KernelProfilingInfoShift {
CmdExecTime = 0,
Max = 0x7fffffff,
}
|
DerSchmale/spirv4web
|
src/compiler/glsl/GLSLOptions.ts
|
<reponame>DerSchmale/spirv4web
import { GLSLVertexOptions } from "./GLSLVertexOptions";
import { GLSLFragmentOptions } from "./GLSLFragmentOptions";
// TODO: Remove options and code referring to it that isn't relevant for WebGL
export class GLSLOptions
{
// The shading language version. Corresponds to #version $VALUE.
version: number = 450;
specialization_constant_prefix: string = "SPIRV_CROSS_CONSTANT_ID_";
// Emit the OpenGL ES shading language instead of desktop OpenGL.
// for WebGL: always true
// es: boolean = false;
// Debug option to always emit temporary variables for all expressions.
force_temporary: boolean = false;
// If true, gl_PerVertex is explicitly redeclared in vertex, geometry and tessellation shaders.
// The members of gl_PerVertex is determined by which built-ins are declared by the shader.
// This option is ignored in ES versions, as redeclaration in ES is not required, and it depends on a different extension
// (EXT_shader_io_blocks) which makes things a bit more fuzzy.
separate_shader_objects: boolean = false;
// Flattens multidimensional arrays, e.g. float foo[a][b][c] into single-dimensional arrays,
// e.g. float foo[a * b * c].
// This function does not change the actual SPIRType of any object.
// Only the generated code, including declarations of interface variables are changed to be single array dimension.
flatten_multidimensional_arrays: boolean = false;
// For older desktop GLSL targets than version 420, the
// GL_ARB_shading_language_420pack extensions is used to be able to support
// layout(binding) on UBOs and samplers.
// If disabled on older targets, binding decorations will be stripped.
enable_420pack_extension: boolean = true;
// In non-Vulkan GLSL, emit push constant blocks as UBOs rather than plain uniforms.
emit_push_constant_as_uniform_buffer: boolean = false;
// Always emit uniform blocks as plain uniforms, regardless of the GLSL version, even when UBOs are supported.
// Does not apply to shader storage or push constant blocks.
emit_uniform_buffer_as_plain_uniforms: boolean = false;
// Emit OpLine directives if present in the module.
// May not correspond exactly to original source, but should be a good approximation.
emit_line_directives: boolean = false;
// In cases where readonly/writeonly decoration are not used at all,
// we try to deduce which qualifier(s) we should actually used, since actually emitting
// read-write decoration is very rare, and older glslang/HLSL compilers tend to just emit readwrite as a matter of fact.
// The default (true) is to enable automatic deduction for these cases, but if you trust the decorations set
// by the SPIR-V, it's recommended to set this to false.
enable_storage_image_qualifier_deduction: boolean = true;
// On some targets (WebGPU), uninitialized variables are banned.
// If this is enabled, all variables (temporaries, Private, Function)
// which would otherwise be uninitialized will now be initialized to 0 instead.
force_zero_initialized_variables: boolean = false;
// In GLSL, force use of I/O block flattening, similar to
// what happens on legacy GLSL targets for blocks and structs.
force_flattened_io_blocks: boolean = false;
// In WebGL 1, when we have unnamed uniform blocks, emit them as global uniforms.
keep_unnamed_ubos: boolean = false;
// If non-zero, controls layout(num_views = N) in; in GL_OVR_multiview2.
ovr_multiview_view_count: number = 0;
vertex: GLSLVertexOptions = new GLSLVertexOptions();
fragment: GLSLFragmentOptions = new GLSLFragmentOptions();
remove_attribute_layouts: boolean = false;
// tries to wrap code using spec constants with preprocessor directives wherever possible
preprocess_spec_const: boolean = false;
}
|
DerSchmale/spirv4web
|
build/types/compiler/glsl/PlsRemap.d.ts
|
<filename>build/types/compiler/glsl/PlsRemap.d.ts
import { PlsFormat } from "./glsl";
export declare class PlsRemap {
id: number;
format: PlsFormat;
constructor(id: number, format: PlsFormat);
}
|
joscha/fast-glob
|
src/providers/filters/deep.spec.ts
|
<filename>src/providers/filters/deep.spec.ts
import * as assert from 'assert';
import Settings, { Options } from '../../settings';
import * as tests from '../../tests';
import { EntryFilterFunction, Pattern } from '../../types';
import DeepFilter from './deep';
function getDeepFilterInstance(options?: Options): DeepFilter {
const settings = new Settings(options);
return new DeepFilter(settings, {
dot: settings.dot
});
}
function getFilter(base: string, positive: Pattern[], negative: Pattern[], options?: Options): EntryFilterFunction {
return getDeepFilterInstance(options).getFilter(base, positive, negative);
}
describe('Providers → Filters → Deep', () => {
describe('Constructor', () => {
it('should create instance of class', () => {
const filter = getDeepFilterInstance();
assert.ok(filter instanceof DeepFilter);
});
});
describe('.getFilter', () => {
describe('options.deep', () => {
it('should return `false` when option has 0 as value', () => {
const filter = getFilter('.', ['**/*'], [], { deep: 0 });
const entry = tests.entry.builder().path('root/directory').directory().build();
const actual = filter(entry);
assert.ok(!actual);
});
it('should return `false` when the depth of entry is greater than the allowable (without base)', () => {
const filter = getFilter('', ['**/*'], [], { deep: 1 });
const entry = tests.entry.builder().path('root/one/two').directory().build();
const actual = filter(entry);
assert.ok(!actual);
});
it('should return `false` when the depth of entry is greater than the allowable (with base as current level)', () => {
const filter = getFilter('.', ['**/*'], [], { deep: 1 });
const entry = tests.entry.builder().path('root/one/two').directory().build();
const actual = filter(entry);
assert.ok(!actual);
});
it('should return `false` when the depth of entry is greater than the allowable (with nested base)', () => {
const filter = getFilter('root/one', ['root/one/**/*'], [], { deep: 1 });
const entry = tests.entry.builder().path('root/one/two').directory().build();
const actual = filter(entry);
assert.ok(!actual);
});
});
describe('Max pattern depth', () => {
it('should return `false` when the depth of entry is greater that the pattern depth', () => {
const filter = getFilter('root', ['root/*'], []);
const entry = tests.entry.builder().path('root/directory').directory().build();
const actual = filter(entry);
assert.ok(!actual);
});
});
describe('options.followSymbolicLinks', () => {
it('should return `false` when an entry is symbolic link and option is disabled', () => {
const filter = getFilter('.', ['**/*'], [], { followSymbolicLinks: false });
const entry = tests.entry.builder().path('root/directory').directory().symlink().build();
const actual = filter(entry);
assert.ok(!actual);
});
});
describe('Pattern', () => {
it('should return `false` when an entry match to the negative pattern', () => {
const filter = getFilter('.', ['**/*'], ['root/**']);
const entry = tests.entry.builder().path('root/directory').directory().build();
const actual = filter(entry);
assert.ok(!actual);
});
it('should return `true` when the positive pattern has no affect to depth reading, but the `baseNameMatch` is enabled', () => {
const filter = getFilter('.', ['*'], [], { baseNameMatch: true });
const entry = tests.entry.builder().path('root/directory').directory().build();
const actual = filter(entry);
assert.ok(actual);
});
it('should return `true` when the negative pattern has no effect to depth reading', () => {
const filter = getFilter('.', ['**/*'], ['**/*']);
const entry = tests.entry.builder().path('root/directory').directory().build();
const actual = filter(entry);
assert.ok(actual);
});
it('should return `true`', () => {
const filter = getFilter('.', ['**/*'], []);
const entry = tests.entry.builder().path('root/directory').directory().build();
const actual = filter(entry);
assert.ok(actual);
});
});
});
describe('Immutability', () => {
it('should return the data without changes', () => {
const filter = getFilter('.', ['**/*'], []);
const reference = tests.entry.builder().path('root/directory').directory().build();
const entry = tests.entry.builder().path('root/directory').directory().build();
filter(entry);
assert.deepStrictEqual(entry, reference);
});
});
});
|
joscha/fast-glob
|
src/utils/path.ts
|
import * as path from 'path';
import { Pattern } from '../types';
const UNESCAPED_GLOB_SYMBOLS_RE = /(\\?)([*?|(){}[\]]|^!|[@+!](?=\())/g;
/**
* Designed to work only with simple paths: `dir\\file`.
*/
export function unixify(filepath: string): string {
return filepath.replace(/\\/g, '/');
}
export function makeAbsolute(cwd: string, filepath: string): string {
return path.resolve(cwd, filepath);
}
export function escape(pattern: Pattern): Pattern {
return pattern.replace(UNESCAPED_GLOB_SYMBOLS_RE, '\\$2');
}
|
joscha/fast-glob
|
src/benchmark/runner.spec.ts
|
import * as assert from 'assert';
import Runner, { RunnerOptions, SuiteMeasures, SuitePackResult } from './runner';
class RunnerFakeProcess extends Runner {
public execNodeProcess(): string {
return '{"matches":1,"time":1,"memory":1}';
}
}
class RunnerFakeProcessError extends Runner {
public execNodeProcess(): string {
return 'error';
}
}
class RunnerFakeReport extends RunnerFakeProcess {
public results: SuitePackResult[] = [];
public report(results: SuitePackResult): void {
this.results.push(results);
}
public getSuites(): string[] {
return ['suite.js'];
}
}
describe('Benchmark → Runner', () => {
const runnerOptions: RunnerOptions = {
type: 'product',
mode: 'async',
pattern: '*',
launches: 3,
maxStdev: 3,
retries: 5,
options: {}
};
describe('.suite', () => {
it('should returns measures', () => {
const runner = new RunnerFakeProcess('basedir', runnerOptions);
const expected: SuiteMeasures = {
matches: 1,
time: 1,
memory: 1
};
const actual = runner.suite('suitePath');
assert.deepStrictEqual(actual, expected);
});
it('should throw error', () => {
const runner = new RunnerFakeProcessError('basedir', runnerOptions);
assert.throws(() => runner.suite('suitePath'), /Ops! Broken suite run\./);
});
});
describe('.suitePack', () => {
it('should returns pack measures', () => {
const runner = new RunnerFakeProcess('basedir', runnerOptions);
const expected: SuitePackResult = {
name: 'suitePath',
errors: 0,
retries: 1,
entries: 1,
measures: {
time: { raw: [1, 1, 1], average: 1, stdev: 0, units: 'ms' },
memory: { raw: [1, 1, 1], average: 1, stdev: 0, units: 'MB' }
}
};
const actual = runner.suitePack('suitePath', 0);
assert.deepStrictEqual(actual, expected);
});
it('should returns pack measures with errors', () => {
const runner = new RunnerFakeProcessError('basedir', runnerOptions);
const expected: SuitePackResult = {
name: 'suitePath',
errors: 3,
retries: 1,
entries: 0,
measures: {
time: { raw: [0, 0, 0], average: 0, stdev: 0, units: 'ms' },
memory: { raw: [0, 0, 0], average: 0, stdev: 0, units: 'MB' }
}
};
const actual = runner.suitePack('suitePath', 0);
assert.deepStrictEqual(actual, expected);
});
});
describe('.packs', () => {
it('should run pack of suites', () => {
const runner = new RunnerFakeReport('basedir', runnerOptions);
const expected = [{
name: 'suite.js',
errors: 0,
entries: 1,
retries: 1,
measures: {
time: { raw: [1, 1, 1], average: 1, stdev: 0, units: 'ms' },
memory: { raw: [1, 1, 1], average: 1, stdev: 0, units: 'MB' }
}
}];
runner.packs();
assert.deepStrictEqual(runner.results, expected);
});
});
});
|
joscha/fast-glob
|
src/providers/filters/entry.ts
|
<reponame>joscha/fast-glob
import Settings from '../../settings';
import { Entry, EntryFilterFunction, MicromatchOptions, Pattern, PatternRe } from '../../types';
import * as utils from '../../utils';
export default class EntryFilter {
public readonly index: Map<string, undefined> = new Map();
constructor(private readonly _settings: Settings, private readonly _micromatchOptions: MicromatchOptions) { }
public getFilter(positive: Pattern[], negative: Pattern[]): EntryFilterFunction {
const positiveRe = utils.pattern.convertPatternsToRe(positive, this._micromatchOptions);
const negativeRe = utils.pattern.convertPatternsToRe(negative, this._micromatchOptions);
return (entry) => this._filter(entry, positiveRe, negativeRe);
}
private _filter(entry: Entry, positiveRe: PatternRe[], negativeRe: PatternRe[]): boolean {
if (this._settings.unique) {
if (this._isDuplicateEntry(entry)) {
return false;
}
this._createIndexRecord(entry);
}
if (this._onlyFileFilter(entry) || this._onlyDirectoryFilter(entry)) {
return false;
}
if (this._isSkippedByAbsoluteNegativePatterns(entry, negativeRe)) {
return false;
}
const filepath = this._settings.baseNameMatch ? entry.name : entry.path;
return this._isMatchToPatterns(filepath, positiveRe) && !this._isMatchToPatterns(entry.path, negativeRe);
}
private _isDuplicateEntry(entry: Entry): boolean {
return this.index.has(entry.path);
}
private _createIndexRecord(entry: Entry): void {
this.index.set(entry.path, undefined);
}
private _onlyFileFilter(entry: Entry): boolean {
return this._settings.onlyFiles && !entry.dirent.isFile();
}
private _onlyDirectoryFilter(entry: Entry): boolean {
return this._settings.onlyDirectories && !entry.dirent.isDirectory();
}
private _isSkippedByAbsoluteNegativePatterns(entry: Entry, negativeRe: PatternRe[]): boolean {
if (!this._settings.absolute) {
return false;
}
const fullpath = utils.path.makeAbsolute(this._settings.cwd, entry.path);
return this._isMatchToPatterns(fullpath, negativeRe);
}
private _isMatchToPatterns(filepath: string, patternsRe: PatternRe[]): boolean {
return utils.pattern.matchAny(filepath, patternsRe);
}
}
|
joscha/fast-glob
|
src/providers/filters/deep.ts
|
import Settings from '../../settings';
import { Entry, EntryFilterFunction, MicromatchOptions, Pattern, PatternRe } from '../../types';
import * as utils from '../../utils';
export default class DeepFilter {
constructor(private readonly _settings: Settings, private readonly _micromatchOptions: MicromatchOptions) { }
public getFilter(basePath: string, positive: Pattern[], negative: Pattern[]): EntryFilterFunction {
const maxPatternDepth = this._getMaxPatternDepth(positive);
const negativeRe = this._getNegativePatternsRe(negative);
return (entry) => this._filter(basePath, entry, negativeRe, maxPatternDepth);
}
private _getMaxPatternDepth(patterns: Pattern[]): number {
const globstar = patterns.some(utils.pattern.hasGlobStar);
return globstar ? Infinity : utils.pattern.getMaxNaivePatternsDepth(patterns);
}
private _getNegativePatternsRe(patterns: Pattern[]): PatternRe[] {
const affectDepthOfReadingPatterns = patterns.filter(utils.pattern.isAffectDepthOfReadingPattern);
return utils.pattern.convertPatternsToRe(affectDepthOfReadingPatterns, this._micromatchOptions);
}
private _filter(basePath: string, entry: Entry, negativeRe: PatternRe[], maxPatternDepth: number): boolean {
const depth = this._getEntryDepth(basePath, entry.path);
if (this._isSkippedByDeep(depth)) {
return false;
}
if (this._isSkippedByMaxPatternDepth(depth, maxPatternDepth)) {
return false;
}
if (this._isSkippedSymbolicLink(entry)) {
return false;
}
return this._isSkippedByNegativePatterns(entry, negativeRe);
}
private _getEntryDepth(basePath: string, entryPath: string): number {
const basePathDepth = basePath.split('/').length;
const entryPathDepth = entryPath.split('/').length;
return entryPathDepth - (basePath === '' ? 0 : basePathDepth);
}
private _isSkippedByDeep(entryDepth: number): boolean {
return entryDepth >= this._settings.deep;
}
private _isSkippedByMaxPatternDepth(entryDepth: number, maxPatternDepth: number): boolean {
return !this._settings.baseNameMatch && maxPatternDepth !== Infinity && entryDepth > maxPatternDepth;
}
private _isSkippedSymbolicLink(entry: Entry): boolean {
return !this._settings.followSymbolicLinks && entry.dirent.isSymbolicLink();
}
private _isSkippedByNegativePatterns(entry: Entry, negativeRe: PatternRe[]): boolean {
return !utils.pattern.matchAny(entry.path, negativeRe);
}
}
|
joscha/fast-glob
|
src/utils/array.ts
|
export function flatten<T>(items: T[][]): T[] {
return items.reduce((collection, item) => ([] as T[]).concat(collection, item), [] as T[]);
}
|
joscha/fast-glob
|
src/benchmark/runner.ts
|
<filename>src/benchmark/runner.ts
import * as fs from 'fs';
import * as path from 'path';
import { Options } from '../settings';
import Reporter from './reporter';
import * as utils from './utils';
import execa = require('execa'); // eslint-disable-line @typescript-eslint/no-require-imports
export type RunnerOptions = {
type: string;
mode: string;
pattern: string;
launches: number;
maxStdev: number;
retries: number;
options: Options;
};
export type SuiteMeasures = {
matches: number;
time: number;
memory: number;
};
export type Measure = {
units: string;
raw: number[];
average: number;
stdev: number;
};
export type SuitePackMeasures = {
time: Measure;
memory: Measure;
};
export type SuitePackResult = {
name: string;
errors: number;
entries: number;
retries: number;
measures: SuitePackMeasures;
};
export default class Runner {
constructor(private readonly _basedir: string, private readonly _options: RunnerOptions) { }
public execNodeProcess(args: string[], options: Partial<execa.SyncOptions>): string {
return execa.sync('node', args, options).stdout;
}
/**
* Runs a single suite in the child process and returns the measurements of his work.
*/
public suite(suitePath: string): SuiteMeasures {
const environment: NodeJS.ProcessEnv = {
NODE_ENV: 'production',
BENCHMARK_BASE_DIR: this._basedir,
BENCHMARK_PATTERN: this._options.pattern,
BENCHMARK_OPTIONS: JSON.stringify(this._options.options)
};
// eslint-disable-next-line unicorn/prevent-abbreviations
const execaOptions: execa.SyncOptions = { env: environment, extendEnv: true };
const stdout = this.execNodeProcess([suitePath], execaOptions);
try {
return JSON.parse(stdout) as SuiteMeasures;
} catch {
throw new TypeError('Ops! Broken suite run.');
}
}
public suitePack(suitePath: string, retries: number): SuitePackResult {
const results: SuitePackResult = {
name: path.basename(suitePath),
errors: 0,
entries: 0,
retries: retries + 1,
measures: this._getSuitePackMeasures()
};
for (let i = 0; i < this._options.launches; i++) {
try {
const { matches, time, memory } = this.suite(suitePath);
results.entries = matches;
results.measures.time.raw.push(time);
results.measures.memory.raw.push(memory);
} catch {
results.errors++;
results.measures.time.raw.push(0);
results.measures.memory.raw.push(0);
}
}
results.measures = {
time: this._getMeasures(results.measures.time.raw, 'ms'),
memory: this._getMeasures(results.measures.memory.raw, 'MB')
};
return results;
}
public report(result: SuitePackResult): void {
const reporter = new Reporter(result);
const report = reporter.toString();
console.log(report);
}
public packs(): void {
const suitesPath = path.join(__dirname, 'suites', this._options.type, this._options.mode);
const suites = this.getSuites(suitesPath);
for (const filepath of suites) {
const suitePath = path.join(suitesPath, filepath);
let result = this.suitePack(suitePath, 0);
while (result.measures.time.stdev > this._options.maxStdev && result.retries < this._options.retries) {
result = this.suitePack(suitePath, result.retries);
}
this.report(result);
}
}
public getSuites(suitesPath: string): string[] {
return fs.readdirSync(suitesPath).filter((suite) => suite.endsWith('.js'));
}
private _getMeasures(raw: number[], units: string): Measure {
return {
units,
raw,
average: utils.getAverageValue(raw),
stdev: utils.getStdev(raw)
};
}
private _getSuitePackMeasures(): SuitePackMeasures {
return {
time: this._getMeasures([], 'ms'),
memory: this._getMeasures([], 'MB')
};
}
}
|
joscha/fast-glob
|
src/tests/index.ts
|
import * as entry from './utils/entry';
import * as errno from './utils/errno';
import * as task from './utils/task';
export {
entry,
errno,
task
};
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.