r/ProgrammingLanguages • • Jan 24 '26

Discussion Why don't any programming languages have vec3, mat4 or quaternions built in?

Shader languages always do, and they are just heaven to work with. And tasty tasty swizzles, vector.xz = color.rb it's just lovely. Not needing any libraries or operator overloading you know? Are there any big reasons?

110 Upvotes

132 comments sorted by

View all comments

141

u/pheristhoilynenysis Jan 24 '26 edited Jan 24 '26

Probably because their use cases are too niche to be built into most of the languages. The fact that a feature is nice to have doesn't mean that it should be there. That's exactly what we have libraries for - you choose what you want to use. Remember that each feature for language is another component for language author to maintain which might be relatively high cost in comparison to gains. Edit: typos

51

u/HaMMeReD Jan 24 '26

Vectors/Matrix math is low hanging fruit for low level optimizations at the compiler. I.e. SIMD instructions and vectorization.

The fact is that the language having the semantics means it can optimize more effectively at the hardware level to use those features.

If it's just an add-on to the language, the semantics are not there for the compiler that it can use the enhanced instructions available to operate on those types.

31

u/alphaglosined Jan 24 '26

Optimising backends do a lot of pattern matching to determine what optimisations to do.
And yes that also includes things like matrix multiplication.

You as a compiler developer working on a frontend, are unlikely to beat what backend developers can do here. They have target-specific information, and they are constantly changing the backend to improve codegen.

For mathematics like this, the context is in the expression/IR, you don't need to attribute anything to it for the backend to recognise it.

Library types that represent mathematics like linear algebra are very likely to optimise to pretty close to the maximum for the target these days. Auto vectorisation has improved a lot over the last 15 years and is no longer awful.

I have been able to in the past, match the codegen of handwritten assembly and intrinsics by simply writing D code more or less naively.

24

u/WittyStick Jan 24 '26

Auto-vec still has a lot of missed opportunities and some of these could be resolved if the programmer were explicit about using vectors rather than arrays of scalars. Obviously we can use intrinsics manually, but the APIs are typically awful and non-portable.

GCC & Clang have a nice approach where we can attach __attribute__((__vector_size__(N))) to the usual "primitives" and the arithmetic, logic and comparison operators are promoted to work element-wise on the vector, using SIMD instructions. It's more portable than using platform-specific intrinsics, but as you state, that's due to a huge effort by the compiler developers to make that possible.

IMO the main reason to include vectors as part of your standard library is to prevent a proliferation of (potentially incompatible) implementations, but having built-in language support opens up more opportunities to optimize.

12

u/dcpugalaxy Jan 24 '26

This is very limited. Compilers can't assume your float[4][4] is properly aligned for example. They often can't deal with arrays etc very well because of aliasing. Autovectorisation is very fickle and easy to break.

All serious mathematical libraries have handwritten SIMD. Often assembly but intrinsics are used too.

5

u/alphaglosined Jan 24 '26

Alignment of arrays is a big issue, since you can't really guarantee that at a language level.

But static arrays are different, those can be aligned correctly by the language, with the assumption that their container is also aligned correctly. At least in D this isn't really an issue.

There is restrict annotation that handles aliasing in terms of optimization but that isn't backed by any guarantees.

As for mathematical libraries, things like ffmpeg, they want to codegen out to be the best for a given target, regardless of compiler flags. They use cpuid to pick the function to call. They are a very different beast from something like linear algebra for general usage.

But yeah, if you care about exact codegen, I'd recommend intrinsics instead of writing assembly itself. Intrinsics inline as they don't conflict with other optimisations.

1

u/aerismio Feb 17 '26

OxCaml actually nails this by baking memory layout directly into the type system. You don’t manually handle alignment; if you use a type like float32x4#, the compiler and allocator automatically enforce the 16-byte alignment.

It handles aliasing through uniqueness modes, which is basically a verified, stronger version of C’srestrict forSIMD, it uses explicit intrinsics rather than fickle autovectorization. You write the blend, and you get that exact instruction using unboxed registers. The best part is that the type system checks everything, so it all composes safely without unsafe hacks.

12

u/HaMMeReD Jan 24 '26

While I'm in no way downplaying the amount of work that goes into backends, semantics is semantics. Having it up front, clearly defined, takes out most of the guess work from the equation.

1

u/flatfinger Jan 26 '26

Optimising backends do a lot of pattern matching to determine what optimisations to do.
And yes that also includes things like matrix multiplication.

Why is it somehow simpler to have an optimizer try to perform pattern matching than to have a language provide a means by which a programmer can specify what's needed?

If e.g. the C Standard had specified an macro that would map to an intrinsic or (possibly inline) function that accepts a pointer of arbitrary type that is aligned in a manner compatible with the platform's normal means of performing a 4-byte load or store, and interpret the bottom 8 bits of the four bytes starting at that address as a little-endian 32-bit two's-complement signed integer, converting such an intrinsic into a load instruction would be a lot simpler than trying to identify all of the ways that code might try to combine the results of four separate character-type reads to yield that same outcome.

1

u/alphaglosined Jan 26 '26

To confirm what your example is, is this correct?

int func(int* ptr) {
    return cast(int)*cast(byte*)ptr;
}

That produces the IR:

define i32 u/int onlineapp.func(int*)(ptr %ptr_arg) #1 {
  %ptr = alloca ptr, align 8                      ; [#uses = 2, size/byte = 8]
  store ptr %ptr_arg, ptr %ptr, align 8
  %1 = load ptr, ptr %ptr, align 8                ; [#uses = 1]
  %2 = load i8, ptr %1, align 1                   ; [#uses = 1]
  %3 = sext i8 %2 to i32                          ; [#uses = 1]
  ret i32 %3
}

That is a load + sext (sign extension).

Optimised assembly:

int onlineapp.func(int*):
  movsbl(%rdi), %eax
  retq

1

u/flatfinger Jan 26 '26

I think that's only loading one byte. The intrinsic I intended to describe should load the bottom 8 bits from each of four bytes, assembling them in little-endian fashion. On most machines, bytes would only hold 8 bits, but on e.g. a machine where `char` is 9 bits, the intrinsic would discard one bit from each byte. Such an operation would likely be somewhat slow on such a machine, but code which is supposed to extract data from an octet-based file would need to perform bit manipulations and shifts necessary to combine 8 bits from each byte.

1

u/alphaglosined Jan 27 '26

In this scenario, an intrinsic may be preferred, but that has nothing to do with the backend.

Bitwise operations are some of the first to have been pattern-matched on; they are not the problem.

Giving it a name, can be easier to write than writing out the bitwise operations to perform it, and it'll help with multi-platform support.

1

u/flatfinger Jan 27 '26

The amount of complexity required to figure out how code is combining the results of different reads may not be huge compared to the amount of complexity required to perform some of the other operations compilers perform, but exceeds that required to reap the low hanging fruit that represents the majority of most extant optimization opportunities.

11

u/shponglespore Jan 24 '26

This isn't really true. Compilers for languages like Rust and C++ give you access to things like SIMD instructions through intrinsic functions. Nothing stops library authors from using them to write high performance math operations the compiler can understand and optimize in context. This is a big part of why C++ is so popular for math-heavy code like game engines.

Also, in practical terms, most of the optimization that needs to happen is inside the individual operations, which is why Python and Julia—which basically can't optimize user code at all—are also popular choices for heavy math. Python in particular is a great example of a language that is good for high performance math even though it only offers advanced math operators through 3rd party libraries like numpy.

3

u/SwingOutStateMachine Jan 24 '26

I think you've misunderstood the other commentor. The point is that language semantics for vector/matrix maths gives compiler authors the ability to compile more code to vectorised or SIMD instructions.

3

u/ExplodingStrawHat Jan 24 '26

At least in my experience using rust, different libraries use different linear algebra dependencies, requiring additional runtime conversion. Not only this, but a library disabling the simd feature flag for the linear algebra dependency (macroquad did this last I checked in order to share a layout with the GPU) suddenly turns off simd for the rest of your codebase (at least, assuming it also relies on the same linear algebra dependency). This leads to even more confusion when hot reloading code where the types on the two sides are the same, yet only one side depends on the package that disables SIMD. 

Having rewritten said project in Odin (which has built in supports for vectors/matrices/complex numbers/quaternions, together with standard library modules for interacting with glsl/hlsl), I've encountered zero of the issues above.

1

u/AugustusLego Jan 24 '26

This is not true for all languages, some languages you can specify to use simd instructions (rust is one example)

Almosr all rust types are defined in core or std (excluding some special magic types like Box, are defined outside of the compiler)

1

u/koflerdavid Jan 25 '26

You don't need vector types in the frontend for this. You only need the compiler to look for data structures that look like they could benefit from SIMD. Specifically, those with lots of members of the same type.

18

u/Luroqa Jan 24 '26

Yeah lol now when I think of it, I'm just too focused on gamedev programming, where they are used constantly. It's not like web devs feel like they are missing. Very reasonable thank you

3

u/Tamschi_ Jan 24 '26

Vectors would be nice to have in JS sometimes, to be honest.

Probably would have to be constrained to 2 32-bit floats though, as you only get limited space for value types in dynamic languages.

4

u/shponglespore Jan 24 '26

I've used complex numbers in JS before for geometry calculations. For my purposes it didn't matter that the performance was garbage, but the lack of operator overloading made the code very ugly.