The Metal Shading Language

This content was generated with the assistance of AI and should be verified against the official documentation before being relied on in production.

The Metal Shading Language is the language of every function that runs on an Apple GPU: vertex, fragment, kernel, mesh, object, intersection and tile functions are all written in it. It is C++17 with the parts a GPU cannot support removed (exceptions, virtual functions, most of the standard library, new and delete before 4.1) and the parts a GPU needs added (vector and matrix types, address spaces, attributes that bind a variable to a resource or to a hardware input, and a standard library of math, texture and synchronisation functions). Because the language is close to C++, most of the learning is in four places: the address spaces, the attributes, how data is laid out in memory so that Swift and the shader agree, and function constants that let one function compile into many specialised pipelines. This page covers those four, plus the compiler options that change how arithmetic behaves.

The facts were checked in November 2026. The version documented is MSL 4.1 (specification dated 4 June 2026, -std=metal4.1, MTLLanguageVersion.version4_1 on the 27 operating systems) and MSL 4.0 (-std=metal4.0, MTLLanguageVersion.version4_0, the 26 operating systems). Metal 4 and later is based on C++17; earlier language versions are based on C++14. Shaders compile with Xcode 26 or later (the Metal Toolchain is a separate Xcode component, see Setting Up Xcode and a Metal Project); targeting the 27 systems with MSL 4.1 needs Xcode 27 on an Apple-silicon Mac. Everything on this page runs on iOS, iPadOS, macOS, tvOS and visionOS; the Metal 4 API types referenced here need an A14 or M1 and later.

In the Bookshelf running example this page defines the shared header that every later shader includes, extends the book’s fragment function with function constants (an optional wear mask and a variable number of lamps), and explains why the structs are declared once and shared. The pipeline that consumes the shaders is described in The Metal Render Pipeline; how other languages compare is in Shading Languages Landscape, and the OpenGL equivalent is The GLSL Language.

Language versions and compiler options

Language version Compiler option MTLLanguageVersion Operating systems Notable additions

MSL 3.0

-std=metal3.0

.version3_0

iOS 16, macOS 13

Mesh and object functions (the object_data address space).

MSL 3.2

-std=metal3.2

.version3_2

iOS 18, macOS 15

Lambda expressions, logging from shaders on Apple silicon.

MSL 4.0

-std=metal4.0

.version4_0

iOS 26, macOS 26

C++17 base, tensors and Metal Performance Primitives; shader parameters are still bound with the same buffer, texture and sampler attributes.

MSL 4.1

-std=metal4.1

.version4_1

iOS 27, macOS 27

Placement new, round-toward-zero default for float conversions, packed numeric types for block-scaling formats, multiplane and blockwise tensors, memory orders (acquire and release) on barriers and atomics, new texture reads (clamp-to-edge, integer coordinates with offsets, multi-pixel), function_id in the intersection result.

Xcode selects the version with the Metal Language Revision build setting; at run time the version of an online-compiled library comes from MTLCompileOptions.languageVersion. The same options object exposes mathMode, mathFloatingPointFunctions, fastMathEnabled, preprocessorMacros, enableLogging, preserveInvariance, optimizationLevel, libraryType and maxTotalThreadsPerThreadgroup. Useful predefined macros are __METAL_VERSION__ (the language revision as an integer) and __METAL_MACOS__, __METAL_IOS__ and __METAL__, so a shader can adapt to the language level or platform it is compiled for. The offline compiler additionally accepts -D and -I for macros and header search paths.

What is not available, so you do not look for it: no standard C++ library (use the Metal standard library instead), no exceptions, no dynamic_cast or RTTI, no goto, no thread_local, no virtual functions or derived classes, and new and delete only as placement new from 4.1. Function pointers exist from MSL 2.3, recursion only in compute functions from MSL 2.4, and lambdas from MSL 3.2.

Types

Scalars, vectors and matrices

Scalars are bool, char, short, int, long (and unsigned forms), half (16-bit float), bfloat (16-bit brain float) and float. Vectors are float2, float3, float4 and so on for every scalar type. Components are accessed with .xyzw or .rgba and may be swizzled (v.zyx, c.rrr). Matrices are written columns by rows: float4x4 has four columns of four rows; float3x2 has three columns of two rows. They are column-major: m[1] is the second column, and m * v multiplies a column vector. This matches the simd types in Swift (see Math for 3D with simd).

Type Size (bytes) Alignment (bytes) Comment

float2

8

8

float3

16

16

Occupies a four-component slot: the fourth component is padding.

float4

16

16

half3

8

8

half4 is also 8 bytes.

int3, uint3

16

16

packed_float3

12

4

Tightly packed storage type, no padding. Converts to and from float3 on load and store.

float3x3

48

16

Three columns, each a padded float3.

float4x4

64

16

half4x4

32

8

The packed_ types (packed_float3, packed_half4, packed_uchar4, …​) are storage formats for arrays of vertices and similar data: they have the alignment of their scalar, so a buffer of 12-byte positions is a device const packed_float3 *. Do computation on the unpacked types.

Three rows of byte-boxes showing a struct with float3 and float taking 32 bytes with padding, the same struct with packed_float3 taking 16 bytes, and a struct with float4x4 and float3 taking 80 bytes
Figure 1. The padding that float3 adds, with the packed alternative

Textures, samplers and other resources

texture2d<float, access::sample> tex (the access defaults to sample), texturecube<float>, texture2d_array<float>, depth2d<float> and texture3d<float> are types you receive as arguments; the template argument is the type that sampling returns, not the storage format. A sampler is either an argument bound at [[sampler(n)]] or a constexpr sampler declared in the shader, which needs no binding:

constexpr sampler bookSampler(coord::normalized, address::clamp_to_edge,
                              filter::linear, mip_filter::linear);
float4 color = cover.sample(bookSampler, in.uv);

Other resource-like types: atomic_int and atomic_uint (and wider ones), array<T, N>, device T * pointers, constant references, ray, intersector, acceleration_structure, mesh<...>, visible_function_table and, in Metal 4, tensor<...>. Textures and samplers are covered in Textures and Samplers.

Function qualifiers

Qualifier Meaning Where it is used

vertex or [[vertex]]

Runs per vertex; returns the per-vertex outputs

The Metal Render Pipeline

fragment or [[fragment]]

Runs per fragment; returns the colour (and optionally depth)

The same page

kernel or [[kernel]]

A compute function; returns void

Compute Kernels

[[object]], [[mesh]]

Mesh pipeline functions

Mesh Shaders

[[intersection(...)]]

Custom ray intersection functions

Ray Tracing

[[visible]], [[stitchable]]

Functions that can be linked, called through function tables, or stitched at run time

Shader Compilation and Pipeline Caching

[[early_fragment_tests]]

Run the depth and stencil tests before the fragment function

The render pipeline page

A function without one of these qualifiers is an ordinary helper that can be called from the others. Graphics and kernel functions cannot be overloaded.

Address spaces

Nested boxes: the GPU with device and constant memory, a threadgroup containing threadgroup memory and imageblock memory, and four threads with private memory; below, the specialised ray_data and object_data spaces and the rules
Figure 2. The address spaces and the memory they describe

An address space says which memory a pointer or reference points into and what you may do with it. Every pointer or reference declared as a parameter of a graphics or kernel function must name one, and a declaration without one is a compile error.

Address space Access Lifetime and visibility Typical use

device

read and write

Buffer memory from the device’s memory pool; visible to all threads

Vertex arrays, output buffers, particle state, any large or writable data. Textures live here implicitly and need no qualifier.

constant

read only

Buffer memory read uniformly by all threads, or program-scope constants initialised in the declaration (they must be core constant expressions)

Uniforms and small tables. Buffers in this space have a minimum offset alignment per GPU (Feature Set Tables). Writing to it is a compile error.

thread

read and write

Per-thread; the default for variables declared inside a function

Local variables, arrays, and pointers to them.

threadgroup

read and write

Shared by the threads of one threadgroup; exists for the threadgroup’s lifetime (and across mid-render and fragment tile kernels over a tile)

Compute reductions, tiles of data, mesh and object functions. Declared in the kernel body, or as a pointer argument sized from the API with setThreadgroupMemoryLength.

threadgroup_imageblock

read and write

Tile (imageblock) memory of a render pass

Tile shaders and programmable blending, see Deferred and Tile Shading.

ray_data

read and write

Payload shared across ray tracing functions

Intersection functions.

object_data

read and write

Payload from an object function to its mesh function

Mesh shading.

For graphics functions a pointer or reference argument must be in device or constant. For kernel functions device, threadgroup, threadgroup_imageblock and constant are allowed. Marking read-only buffers constant (or device const) lets the compiler and hardware use faster paths.

flowchart TD A{"Does the shader write to the buffer?"} -- yes --> B["device"] A -- no --> C{"Is the data small and read the same by all threads?"} C -- yes --> D["constant"] C -- no --> E["device const"] B --> F{"Is it shared only inside one threadgroup?"} F -- yes --> G["threadgroup, declared in the kernel or sized by the API"] F -- no --> H["stay with device"]
Figure 3. Choosing the address space of a buffer parameter

A kernel that touches every space in one place, a threadgroup sum reduction:

#include <metal_stdlib>
using namespace metal;

kernel void sumReduce(device const float *input        [[buffer(0)]],   // read-only device data
                      device float *partialSums        [[buffer(1)]],   // writable device data
                      constant uint &count             [[buffer(2)]],   // uniform value
                      threadgroup float *scratch       [[threadgroup(0)]],
                      uint globalIndex                 [[thread_position_in_grid]],
                      uint localIndex                  [[thread_position_in_threadgroup]],
                      uint groupSize                   [[threads_per_threadgroup]],
                      uint groupIndex                  [[threadgroup_position_in_grid]])
{
    float value = globalIndex < count ? input[globalIndex] : 0.0f;   // a thread-space local
    scratch[localIndex] = value;
    threadgroup_barrier(mem_flags::mem_threadgroup);

    for (uint stride = groupSize / 2; stride > 0; stride >>= 1) {
        if (localIndex < stride) {
            scratch[localIndex] += scratch[localIndex + stride];
        }
        threadgroup_barrier(mem_flags::mem_threadgroup);
    }
    if (localIndex == 0) {
        partialSums[groupIndex] = scratch[0];
    }
}

On the Swift side the threadgroup argument gets its size from encoder.setThreadgroupMemoryLength(threadsPerGroup * MemoryLayout<Float>.stride, index: 0). The threadgroup size, dispatch rules and the SIMD-group functions that replace most of this loop are in Compute Kernels.

Attributes: binding a variable to the outside world

Attributes are written in double square brackets after a declaration. They are how the shader says "this parameter is buffer 1", "this field is the clip-space position", or "this value is the thread’s index in the grid".

Diagram connecting Swift vertex descriptors and argument table bindings to attribute, buffer, texture and sampler attributes in the vertex and fragment functions, with built-in inputs, interpolation and fragment outputs
Figure 4. How the attributes tie shader parameters to the API and to the pipeline stages
Attribute Used on Meaning

[[buffer(n)]], [[texture(n)]], [[sampler(n)]]

Function parameters

Bind to slot n of the corresponding binding table. Buffers, textures and samplers are numbered independently. In Metal 4 the buffer slot is the index in the MTL4ArgumentTable.

[[threadgroup(n)]]

Pointer parameters in threadgroup

Threadgroup memory block n, sized with setThreadgroupMemoryLength.

[[stage_in]]

One struct parameter of a vertex or fragment function

The struct’s members come from the vertex descriptor (vertex) or from the rasteriser (fragment).

[[attribute(n)]]

Members of the vertex stage_in struct

Vertex attribute n of the MTLVertexDescriptor.

[[position]]

Vertex output; fragment input

Clip-space position out; window position in (in pixels, with depth in z).

[[color(m)]]

Fragment output members; also input in programmable blending

Colour attachment m.

[[depth(any)]], [[sample_mask]]

Fragment output members

Write depth or coverage from the shader (disables the early depth test).

[[flat]], [[center_perspective]], [[center_no_perspective]], [[centroid_perspective]], [[sample_perspective]]

Varyings

Interpolation and sampling mode.

[[user(name)]]

Varyings

Matches vertex outputs to fragment inputs by name when the structs differ.

[[function_constant(name)]]

Variables and parameters

Makes the declaration conditional on a function constant (below).

[[id(n)]]

Members of an argument buffer struct

Position inside an argument buffer, see Argument Buffers and Bindless Resources.

Built-in inputs

Function type Attribute Type Value

Vertex

[[vertex_id]], [[instance_id]]

uint

Index of the vertex in the draw and of the instance; [[base_vertex]] and [[base_instance]] give the offsets.

Fragment

[[front_facing]], [[sample_id]], [[primitive_id]], [[barycentric_coord]]

bool, uint, uint, float3

Winding of the primitive, MSAA sample, primitive number and barycentric coordinates.

Kernel

[[thread_position_in_grid]]

uint, uint2, uint3

Global index of the thread.

Kernel

[[thread_position_in_threadgroup]], [[thread_index_in_threadgroup]]

uint, uint2, uint3; uint

Position (or flat index) inside the threadgroup.

Kernel

[[threadgroup_position_in_grid]], [[threads_per_threadgroup]], [[threadgroups_per_grid]]

uint, uint2, uint3

Which threadgroup, and the sizes.

Kernel

[[thread_index_in_simdgroup]], [[simdgroup_index_in_threadgroup]], [[threads_per_simdgroup]]

uint

SIMD-group position, see the compute page.

Attribute names and their legal types are listed per function type in section 5 of the specification; using an attribute with the wrong type is a compile error naming the allowed ones.

Sharing structs with Swift

Every buffer the CPU fills and the GPU reads has a layout. Declaring that layout twice, once in Swift and once in MSL, is the most common source of garbage on screen. The robust approach is to declare it once, in a C header that both compile.

Diagram: a shared ShaderTypes.h feeds a bridging header for Swift and an include for the Metal shader, producing the same struct layout on both sides, with a layout assertion
Figure 5. One header seen by the Swift compiler and by the Metal compiler
// ShaderTypes.h: included by Swift (via the bridging header) and by MSL
#ifndef ShaderTypes_h
#define ShaderTypes_h

#ifdef __METAL_VERSION__
#define NS_ENUM(_type, _name) enum _name : _type _name; enum _name : _type
#define NSInteger metal::int32_t
#else
#import <Foundation/Foundation.h>
#endif

#include <simd/simd.h>

#if defined(__METAL_VERSION__) || defined(__cplusplus)
#define SHARED_ASSERT(cond, msg) static_assert(cond, msg)
#else
#define SHARED_ASSERT(cond, msg) _Static_assert(cond, msg)
#endif

typedef NS_ENUM(NSInteger, BookBufferIndex) {
    BookBufferIndexMeshVertices = 0,
    BookBufferIndexUniforms     = 1
};

typedef NS_ENUM(NSInteger, VertexAttribute) {
    VertexAttributePosition = 0,
    VertexAttributeNormal   = 1,
    VertexAttributeTexCoord = 2
};

typedef NS_ENUM(NSInteger, BookFunctionConstant) {
    BookFunctionConstantHasWear   = 0,
    BookFunctionConstantLampCount = 1
};

typedef struct {
    matrix_float4x4 viewProjection;   // offset 0,   64 bytes
    matrix_float4x4 model;            // offset 64,  64 bytes
    vector_float3   lightDirection;   // offset 128, 16 bytes (a float3 occupies a full slot)
} BookUniforms;

SHARED_ASSERT(sizeof(BookUniforms) == 144, "BookUniforms layout changed: update both sides");

#endif /* ShaderTypes_h */

Source: Apple: Drawing a triangle with Metal 4 (its ShaderTypes.h uses the same macro pattern)

Storyboard of four steps: create ShaderTypes.h in every target, create a bridging header that imports it and set the Objective-C Bridging Header build setting, include it in the .metal file, and use the generated Swift types
Figure 6. Adding the shared header to a project
  1. Create ShaderTypes.h. In Xcode, File, New, File, choose Header File. In the File Inspector tick every app target (iOS, macOS and visionOS share one source).

  2. Create the bridging header (for example Bookshelf-Bridging-Header.h) containing #import "ShaderTypes.h", and set the Objective-C Bridging Header build setting of each Swift target to its path. A Swift package target cannot use a bridging header: put the header in a C target (include/ShaderTypes.h plus a module map the package generates) and import that module from Swift.

  3. Include the header in the .metal file with #include "ShaderTypes.h" after <metal_stdlib>. A header in the same directory is found automatically; for others add a Metal header search path (the offline compiler’s -I).

  4. Use the types from Swift. C structs import with memberwise initialisers, matrix_float4x4 becomes simd_float4x4, vector_float3 becomes SIMD3<Float>, and an NS_ENUM becomes a Swift enum with the common prefix removed, so BookBufferIndexUniforms is BookBufferIndex.uniforms and its rawValue is the Int you pass as a binding index.

Rules that keep the two sides identical:

  • Use simd types in shared structs (vector_float4, matrix_float4x4, vector_uint2), which have the same size and alignment in C, in Swift and in MSL.

  • Never put NSInteger or int of unknown width in a struct: the macro above makes NSInteger 32 bits in MSL but 64 in Swift. Use int32_t, uint32_t and float in shared structs; keep NSInteger for enum backing only.

  • vector_float3 takes 16 bytes. If you need the 12-byte form, declare packed_float3 in MSL and three separate floats on the C side.

  • Keep a SHARED_ASSERT of sizeof for each struct that crosses the boundary. The check runs in the Metal compiler and the C compiler, so a change to one side breaks the build.

  • Resource handles such as textures are never in these structs; they go in argument buffers (see Argument Buffers and Bindless Resources).

Function constants

A function constant is a value that is fixed when a pipeline is created, not when the shader is compiled to the library and not when it runs. The shader is compiled once to an intermediate form; when you make the pipeline you supply the constant values, and the back-end compiler removes unused branches, can unroll loops whose bound is the constant, and drops unused parameters. The cost of a variant is paid at load time instead of per pixel.

A shader with two function constants is compiled once; at pipeline creation constant values select four variants with and without the wear mask, with unused branches removed
Figure 7. One shader source specialised into pipeline variants when pipelines are created
// Shaders.metal: the textured book fragment function with two function constants
#include <metal_stdlib>
#include "ShaderTypes.h"
using namespace metal;

constant bool hasWear  [[function_constant(BookFunctionConstantHasWear)]];
constant uint lampCount [[function_constant(BookFunctionConstantLampCount)]];

struct BookVertexOut {
    float4 position [[position]];
    float3 worldNormal;
    float2 uv;
};

fragment float4 bookFragment(BookVertexOut in [[stage_in]],
                             constant BookUniforms &uniforms [[buffer(BookBufferIndexUniforms)]],
                             texture2d<float> cover [[texture(0)]],
                             texture2d<float> wear  [[texture(1), function_constant(hasWear)]])
{
    constexpr sampler s(coord::normalized, address::clamp_to_edge, filter::linear, mip_filter::linear);
    float3 albedo = cover.sample(s, in.uv).rgb;
    if (hasWear) {                                   // removed from the binary when hasWear is false
        albedo *= 1.0 - 0.5 * wear.sample(s, in.uv).r;
    }

    float3 n = normalize(in.worldNormal);
    float lighting = 0.2;
    for (uint i = 0; i < lampCount; ++i) {           // a constant trip count: the compiler unrolls it
        float3 toLamp = normalize(float3(0.3 * float(i + 1), 1.0, 0.4));
        lighting += saturate(dot(n, toLamp)) / float(lampCount);
    }
    return float4(albedo * lighting, 1.0);
}

On the Swift side the values go in an MTLFunctionConstantValues. Metal 3 asks the library for the specialised function; Metal 4 wraps the function descriptor and the values in a specialised function descriptor so the compiler can do it as part of the pipeline build.

import Metal

struct BookVariant: Hashable {
    var hasWear: Bool
    var lampCount: UInt32
}

func makeConstantValues(for variant: BookVariant) -> MTLFunctionConstantValues {
    let values = MTLFunctionConstantValues()
    var hasWear = variant.hasWear
    var lampCount = variant.lampCount
    values.setConstantValue(&hasWear, type: .bool, index: BookFunctionConstant.hasWear.rawValue)
    values.setConstantValue(&lampCount, type: .uint, index: BookFunctionConstant.lampCount.rawValue)
    return values
}

// Metal 3: the specialised MTLFunction goes straight into the pipeline descriptor.
func fragmentFunctionMetal3(library: MTLLibrary, variant: BookVariant) throws -> MTLFunction {
    try library.makeFunction(name: "bookFragment", constantValues: makeConstantValues(for: variant))
}

// Metal 4: a specialised function descriptor wraps the library function descriptor.
@available(iOS 26.0, macOS 26.0, tvOS 26.0, visionOS 26.0, *)
func fragmentDescriptorMetal4(library: MTLLibrary, variant: BookVariant) -> MTL4SpecializedFunctionDescriptor {
    let base = MTL4LibraryFunctionDescriptor()
    base.library = library
    base.name = "bookFragment"
    let specialized = MTL4SpecializedFunctionDescriptor()
    specialized.functionDescriptor = base
    specialized.constantValues = makeConstantValues(for: variant)
    return specialized     // assign to MTL4RenderPipelineDescriptor.fragmentFunctionDescriptor
}

/// A cache so each variant is compiled once.
@MainActor
final class BookPipelineCache {
    private var pipelines: [BookVariant: MTLRenderPipelineState] = [:]
    func pipeline(for variant: BookVariant, make: (BookVariant) throws -> MTLRenderPipelineState) rethrows -> MTLRenderPipelineState {
        if let existing = pipelines[variant] { return existing }
        let created = try make(variant)
        pipelines[variant] = created
        return created
    }
}

Details that matter:

  • Types and indices. A function constant is a scalar or vector (a struct or an array is a compile error), and its index is between 0 and 65535. The MTLDataType passed to setConstantValue must match the declared type; a mismatch fails when the function is created.

  • What they can control. Code paths that get compiled, optional arguments of graphics, kernel and helper functions, and optional members of a [[stage_in]] struct.

  • Index or name. Constants are numbered with [[function_constant(n)]]. setConstantValue(_:type:index:) uses the number; setConstantValue(_:type:withName:) uses the variable’s name. Numbers in a shared header keep both sides in sync.

  • Defined or not. is_function_constant_defined(name) tells the shader whether the API supplied a value, which lets one source serve both "feature present" and "feature unknown" callers. The simplest rule is to define every constant the function uses.

  • Conditional parameters. Adding function_constant(name) inside a parameter’s attribute list removes that parameter from the signature when the constant is false or undefined, so the pipeline needs no binding for it.

  • Replace preprocessor variants. The traditional alternative is -D macros, which means one library per variant or runtime source compilation. Function constants keep one library and specialise lazily.

  • Count. Variants multiply: ten boolean constants allow 1,024 combinations. Create only the pipelines you use, cache them by key, and consider pre-compiling the likely ones with binary archives.

  • Relation to other mechanisms. Branching on a uniform costs a branch for every thread each draw; function constants cost nothing at run time but need a pipeline per variant; [[visible]] and [[stitchable]] functions let you link pieces at run time instead.

Math, precision and logging

  • Fast math by default. The compiler’s default -fmetal-math-mode is fast and -fmetal-math-fp32-functions is fast: the compiler may assume no NaNs or infinities, no signed zeros, allow reassociation and use fused multiply-add. A division by a value that can be zero is then undefined behaviour. relaxed keeps infinities and NaNs but still optimises aggressively, and safe disables unsafe transformations. In an MTLCompileOptions set mathMode and mathFloatingPointFunctions; the legacy -ffast-math and -fno-fast-math map to these settings. #pragma METAL fp math_mode(safe) scopes it to a block.

  • half versus float. half halves register and bandwidth cost and is enough for colours; use float for positions, matrix products and accumulation. Mixed arithmetic promotes to float, and a stray float literal (1.0) in a half expression promotes the whole expression, so write 1.0h where it matters.

  • Rounding. From MSL 4.1 the default rounding mode of float-to-float conversions can be set to round toward zero.

  • Logging. On Apple silicon, MSL 3.2 and later can log from a shader with <metal_logging> and an os_log object; compile with logging enabled (-fmetal-enable-logging, or MTLCompileOptions.enableLogging) and attach an MTLLogState to the command buffer (Metal 4: MTL4CommandBufferOptions.logState). See Debugging and Profiling Metal.

Compiling shaders

Xcode compiles every .metal file of the target to AIR (Apple’s intermediate representation) and links them into default.metallib in the app bundle; device.makeDefaultLibrary() loads it. The same steps on the command line are xcrun metal -c Shaders.metal -o Shaders.air followed by xcrun metallib Shaders.air -o default.metallib, with -std=metal4.0 (or 4.1) selecting the language. Compiling source at run time (device.makeLibrary(source:options:)) is useful for tools and experiments but is slower than a pre-built library and should not be on a shipping app’s critical path. The build setup, including the Metal Toolchain component, is in Setting Up Xcode and a Metal Project, and pipeline caching is in Shader Compilation and Pipeline Caching.

Common mistakes

Symptom Cause Fix

"missing address space qualifier" compile error

A pointer or reference parameter has no device, constant or threadgroup

Add the right address space; for read-only buffers prefer constant or device const.

Colours or positions garbled, normals wrong

float3 in a struct read from tightly packed floats, or padding mismatch with Swift

Share the struct through the header; use packed_float3 for packed arrays; add SHARED_ASSERT.

A uniform struct seems offset by a few bytes

NSInteger or int widths differ, or a Swift Float array stands in for a struct

Use int32_t or uint32_t in shared structs; declare the struct once.

Rotation or projection looks transposed

Matrix built row-major, or v * m instead of m * v

MSL matrices are column-major; with simd matrices on the Swift side write m * v.

NaN or infinity propagates into the image although the code guards for it

Fast math assumes no NaNs or infinities, so the guard can be removed

Set mathMode to relaxed or safe for the function or file, or restructure.

Function constant error when the pipeline is created

Wrong MTLDataType, an undefined constant used outside is_function_constant_defined, or a bad index

Match types, define every used constant and keep indices in the shared header.

Integer varying is garbage between stages

Integer outputs are interpolated unless marked

Mark integer members with [[flat]].

Shader works in Debug but not in Release

Uninitialised thread variables, or races on threadgroup memory without barriers

Initialise locals; add threadgroup_barrier between writes and reads; validate with Shader Validation.

Performance notes

  • Use the smallest type that is accurate enough; half arithmetic is cheaper on every Apple GPU.

  • Use constant for small, uniformly read data and device const for large read-only arrays; both beat writable device for the optimiser.

  • Prefer function constants over runtime branches for per-draw decisions, and select, mix, step and saturate over data-dependent if for per-pixel ones.

  • Keep per-thread state small: many live variables reduce the number of threads the GPU can keep in flight, which lowers latency hiding.

  • Move invariant work out of the fragment function into the vertex function or the CPU.

  • Barriers and atomics are expensive; prefer SIMD-group functions inside a SIMD group.

What changed recently

Version Change

MSL 3.0 (iOS 16, macOS 13)

Mesh and object functions.

MSL 3.2 (iOS 18, macOS 15)

Lambdas; shader logging on Apple silicon; math mode options with Xcode 16.

MSL 4.0 (26 systems, 2025)

C++17 base; tensors and Metal Performance Primitives; the Metal 4 binding model.

MSL 4.1 (27 systems, spec dated 2026-06-04)

Placement new, round-toward-zero conversion default, block-scaling packed types, multiplane and blockwise tensors, acquire and release memory orders, more texture read forms, function_id in intersection results.

Where the books are out of date

Source Statement Today

Metal by Tutorials, 4th edition (chapters 3, 4 and 7)

Targets Metal 3 with Xcode 15, macOS 14 and iOS 17. The 5th edition (November 2025) moved to Swift 6 and the 26 SDKs but still teaches Metal 3.

MSL 4.0 (26 systems) and 4.1 (27 systems) are the current language versions; Xcode 27 needs an Apple-silicon Mac on macOS 26.6 or later, and Metal 4 needs an A14 or M1.

Metal Programming Guide (Clayton), chapters 5 and 7

Written for Metal 2, Swift 4, Xcode 9 and iOS 11, with device.newDefaultLibrary().

device.makeDefaultLibrary(), Swift 6.4 and Xcode 27; Metal 4 needs an A14 or M1 and later instead of the A7 baseline of that era.