суббота, 21 ноября 2026 г.

why it's so hard to make SASS assembler?

Short answer: bcs paranoid nvidia don't disclose its ABI (and punishes you silently when you get them wrong)

Indeed, their ISA is known but I know only couple of nominally functional assemblers for modern SM (given that their nvasm_internal used for many RT kernels remains private and not available)

CuAssembler

  • last update was 3 years ago
  • new SM90+ are not supported
  • many of listed below problems just not solved (although you can mitigate some)

Unnamed asm from nvidia-sass-document

Chinese comrade invented its own syntax looking like
LDC.64 {R0,R1}, #param(data);[7:7:{{}}:5:1] 
It try to solve couple of problems with nvdisasm output:
  1. ambiguity for wide operands
  2. part after semicolon describes explicit scheduler settings like usched_info, req_bit_set etc (like in good old maxas)

I think that having own syntax is bad idea generally. Currently the only trusted source of SASS asm is official nvdisasm and so we should at least has capability to parse it and then automatically compare to assure that our encoder/decoder works

Let's classify what problems can arise if our generated CUBIN missed or malformed some data

  • CUBIN won't loading. Difficulty: easy, you can always compare with generated by ptxas and find out what is wrong
  • CUBIN loading but some tools (like cupti, nsight, memcheck/synccheck) refused to work with it. Difficulty: easy, see previous point
  • CUBIN loading but fails in some rare edge-cases. Difficulty: medium, but can be hard if we can't use cuda-gdb
  • CUBIN loading and successfully working, but due to some missed data (for example for scheduler) at not optimal performance. As usually nvidia doing this totally silently - no logs/messages from driver. Difficulty: nightmare, such cases extremely hard to detect 

And now lets list what must be generated to get good & wealthy CUBIN - keep in mind that this set is incomplete

пятница, 6 ноября 2026 г.

notes on PTX verification

I recently read article called "Formalizing PTX in Lean to Prove GPU Kernel Correctness". All you need for hype - gpu, ptx, lean for the Navier-Stokes equations

As is customary in such cases, there is no code, however paper contains remarkable phrase:

The interpreter implements 81 instruction forms

Just some numbers: ptxas from sdk 13.1 has has 270 unique instructions in 1420 forms, from sdk 13.4 - 291 instructions in 1669 forms. How do I know this? Well

So they covered in best case 81 / 270 = 30% of all PTX instructions, and now they’ll be shouting loudly all over the internet "software solved", "all your code belongs to us", "your entire career is now a $20/month subscription" and the rest of the obligatory misanthropic repertoire

Ok, let's examine some real projects in this field - I mean you even can check their source code

SentyWard

Parser is just blood from eyes and it is absolutely impossible to figure out which instructions and attributes it can recognize. Executor doesn't look even slightly better but from numerous

if (op == "shl"

if (In(op, {"shr", "div", "rem"})

at least we can estimate that its support of PTX is incomplete

volta

function parse_opcode looks terrible, but at least we can estimate number of supported PTX instructions: ~160 / 270 = 60%. Twice as much, but it's not enough for hype because there's no lean

cuKLEE

Strictly speaking, it can only parse PTX inline asm, and as you can see it also understands very limited number of instructions

Conclusion

There are no verification tools with full support of PTX - mainly bcs evil nvidia refuses to publish formal PTX spec (and instead of fixing bugs in official documentation prefers to release something with name "nsight-perf-sdk-for-ai")

среда, 4 ноября 2026 г.

ebnf & parser of PTX from sdk 13.4

Observing raw data from previous part we can conclude that many (17) new attributes were inserted in middle of indices table thereby shifting the indices. And even worse - they were inserted in many arbitrary places. So instead of patching long-suffering script iptx.pl I made its clone iptx3.pl (DRY, yeah)

After some brute-forcing & RE I was able to identify 130 attributes masks - so still unknown 8. Given that at least 6 of them describe semantics of instruction - actually only 2 indices currently unknown:
  • 13:5 for spdecompress
  • 17:0 for tensormap.replace

EBNF

5246 lines vs 4460 from old version

Intrinsics

I wrote script to compare them. No new instrinsics but 3 were removed:
  • __cuda_sm20_div_rn_ftz_f32
  • __cuda_sm20_div_rn_f32
  • __cuda_sm20_div_rn_noftz_f32_slowpath
See raw data in files ptx_intr.txt & ptx134_intr.txt

Expanded macros

Seems that all newly added PTX instructions actually implemented as macros and expanding to calls of __nv_ptx_builtin_ocg_XXX. Unfortunately I was unable to find those functions inside ptxas, and in RT kernels too. Some (like fabricXXX) described here
 
However we always can generate ptx and examine what it actually compiles into:
__HIR0X1C0.8.U2.2TO4.X4 R0, R8, R8, UR4 ;

It's funny that sample for spdecompress from official doc doesn't even compile. And for trace.marks too. I wonder — has even one of the many morons on Twitter, who keep posting this document as if it were the official nvidia assembler manual, actually tried verifying anything in it?

Parser

New data from iptx3.pl -C

понедельник, 26 октября 2026 г.

machineIR passes & mlir dialects from tileiras & cute dsl

Previous parts: 1, 2 & 3

Let's continue to dissect compilers from nvidia. This time, I decided to examine compilers that are guaranteed to contain their custom MLIR dialects - tileiras and CuTe DSL

tileiras

As usual, their official repository is completely useless - it does not contain code for conversions/lowering so you can't build your own version of this compiler. So I used exactly the same techniques and scripts for its analysis from previous part

Strings from constructors - contain nothing of value

Passes shows 5 custom missed in vanilla llvm:

  1. nvptx-set-global-array-alignment (Find good alignment for statically sized global/shared arrays)
  2. nvptx-set-local-array-alignment (Find good alignment for statically sized alloca arrays)
  3. nvvm-peephole-optimizer (NVVM Peephole Optimizer)
  4. lower-aggr-copies (Lower Aggregate Copies)
  5. mergereturn (Unify function exit nodes)

As you can see this list differs from cicc and prompts some philosophical musings: just how many LLVM forks do they have, and are those dev-teams even aware of each other’s existence?

enumerate registered MLIR dialects

There is very good doc about MLIR capabilities from NPU compiler, however it does not contains answer to our question - how we can extract from LLVM binary all registered MLIR dialects

So I spent several days poking around megabytes of MLIR sources. It seems that perfect solution does not exist (due of heavy using of template black magic), but we can get practically good one - method MLIRContext::getOrLoadDialect:

  • it can be identified by string "a dialect with namespace". Warning: there are another methods using this string like MLIRContext::getOrLoadDynamicDialect but fortunately they usually not linked with custom LLVM forks
  • it's called from BytecodeDialect::load method and so we can catch all dialects allowed in input .bc files

So I wrote yet another dirty IDC script to extract MLIR dialects - total 30 unique


CuTe DSL

Official repository claims that you can build your own compiler with vanilla LLVM (I never verified if that is true). What they didn't said - in their python packages compiler based on their closed-source LLVM fork, in my case I dissected _cutlass_ir.cpython-313-x86_64-linux-gnu.so

First remarkable thing is its size - 144Mb, for example size of cicc is 78Mb and size of tileiras 89Mb. Highly unlikely that python bindings have size of ~60Mb, so lets check  

strings from constructors

We could remark something very familiar - string like AddWaitForCCOrPOffDeck & co. Also section .rodata has huge blobs for "fermi macros", so we can conclude that it was linked with PTXAS

machineIR passes

+ 54 new passes, wow! Also it has 2767 nvvm intrinsics vs 1998 in plain LLVM

MLIR dialects 

As you can see it contains 32, including our beloved cute & cute_nvgpu

 

Conclusion

It appears that CuTe DSL compiler based on the same LLVM fork as cicc and so produces fastest code, also it supports 32 MLIR dialects and scripting from python - just combo

среда, 21 октября 2026 г.

new ptx instructions from cuda sdk 13.4

File with extracted instructions, attributes masks and operands - 1669 items (vs 1420 in version from 13.0). Being lazy person I also wrote script to compare them (in Perl, of course). 21 newly added instructions:

  • applypriority.async.bulk (1 forms)
  • applypriority.async.bulk.tensor (12 forms)
  • clmad.hi (2 forms)
  • clmad.lo (2 forms)
  • fabric.submit (1 forms)
  • fabric.try_atom.async (13 forms)
  • fabric.try_get.async (2 forms)
  • fabric.try_get.async.tensor (10 forms)
  • fabric.try_pullred.async (5 forms)
  • fabric.try_put.async (8 forms)
  • fabric.try_put.async.tensor (20 forms)
  • fabric.try_red.async (16 forms)
  • fabric.try_red.async.tensor (20 forms)
  • fabric.wait (1 forms)
  • mbarrier.check_layout (1 forms)
  • multimem.red.async (1 forms)
  • multimem.st.async (3 forms)
  • spcompress (1 forms)
  • spdecompress (1 forms)
  • tcgen05.ld.red.spcompress (1 forms)
  • tcgen05.ld.spcompress (1 forms)

It seems that attribute mask has the same size 20 bytes:
270 uniq ins
FD FF FF FF F1 FF FF 9F F9 FF E7 CF FF F3 DF FF FF 00 00 00
length of mask 121
291 uniq ins
FD FF FF FF FB FF FF FF E7 FF 9F 3F FF FF 7F FF FF FF 29 00
length of mask 138

As you can see they added 138 - 121 = 17 new attributes. But worst of all, the attribute indices have changed too. Lets compare for example first form for ld instruction:
old:
60 00 00 00 A0 EC 03 00 00 00 00 00 01 00 00 00 00 00 00 00
new
C0 00 00 00 A0 EC 03 00 00 00 00 00 04 00 00 80 00 00 00 00

Also I made option -f to compare new forms - 127 new forms, like
perl ip_cmp.pl -f ptx_ops3.txt
--- 249 lines
add: 11 old forms, 17 new
 line 751: add    ddd    Q32Q32
 line 752: add    dcd    Q32R16
 line 753: add    012    H64H32H64
 line 754: add    012    H64E32H64
 line 755: add    012    H32H64H64
 line 756: add    012    E32H64H64

etc

понедельник, 19 октября 2026 г.

inefficient uniform registers allocation in ptxas

While poking around RT kernels (extracted from libcuda.so) I stumbled upon very remarkable sample - sm159.elf. First let's check what tools were used to compile it - dump section .note.nv.tkinfo (here it has index 5):

readelf -x 5 sm159.elf

Hex dump of section '.note.nv.tkinfo':
  0x00000000 0c000000 9c000000 d0070000 4e564944 ............NVID
  0x00000010 49412043 6f727000 02000000 00000000 IA Corp.........
  0x00000020 01000000 07000000 35000000 54000000 ........5...T...
  0x00000030 00707478 61730043 75646120 636f6d70 .ptxas.Cuda comp
  0x00000040 696c6174 696f6e20 746f6f6c 732c2072 ilation tools, r
  0x00000050 656c6561 73652031 332e312c 20563133 elease 13.1, V13
  0x00000060 2e312e30 00427569 6c642063 7564615f .1.0.Build cuda_
  0x00000070 612e6375 64615f61 2e333630 34343438 a.cuda_a.3604448
  0x00000080 365f3000 2d6d6178 72726567 636f756e 6_0.-maxrregcoun
  0x00000090 74203332 202d6172 63682073 6d5f3132 t 32 -arch sm_12
  0x000000a0 31202d64 6c636d20 6367202d 6d203634 1 -dlcm cg -m 64
  0x000000b0 20000000                             ... 
As you can see it was compiled with regular ptxas from SDK 13.1 (and not with nvasm_internal). This file contains huge function _ZN6RefTMA12TMACommand_tC1ERKNS_19ptx_inst_parametersE - first branch happens at offset 0xc70 and first back-edge at 37c0. Let's take a look at this piece of code:
    /*01b0*/      LDC.64 R28, c[0x0][0x358] ; move base ptr into R28-29
    /*01c0*/      R2UR UR4, R28.reuse ; assign UR4
    /*01d0*/      R2UR UR5, R29.reuse ;
    /*01e0*/      R2UR UR6, R28 ;
    /*01f0*/      R2UR UR7, R29 ;
    /*0200*/      R2UR UR8, R28.reuse ; assign the same value from R28-29
    /*0210*/      R2UR UR9, R29.reuse ;
    /*0220*/      R2UR UR10, R28.reuse ;
    /*0230*/      R2UR UR11, R29.reuse ;
    /*0240*/      ST.E desc[UR4][R16.64+0x18], R3 ; use UR4 for desc operand
    /*0250*/      R2UR UR12, R28.reuse ;
    /*0260*/      R2UR UR13, R29 ;
    /*0270*/      ST.E desc[UR6][R16.64+0x38], R3 ;
    /*0280*/      R2UR UR70, R28 ;
    /*0290*/      R2UR UR71, R29.reuse ;
    /*02a0*/      ST.E desc[UR8][R16.64+0x58], R3 ;
    /*02b0*/      R2UR UR68, R28.reuse ;
    /*02c0*/      R2UR UR69, R29.reuse ;
    /*02d0*/      ST.E desc[UR10][R16.64+0x78], R3 ;
    /*02e0*/      R2UR UR66, R28.reuse ;
    /*02f0*/      R2UR UR67, R29 ;
    /*0300*/      ST.E desc[UR12][R16.64+0x118], R5 ;

What noteworthy things can we examine here?

четверг, 15 октября 2026 г.

comparison of nvcc vs clang nvptx backend, part 3

Parts 1 & 2

Little disclaimer: I am not llvm expert and never created my own backend - in best case I can write simple optimization pass, lower yet another senseless MLIR dialect or extract some info from IR (and prefer gcc bcs its code more clean & neat and not scattered on thousands of sub-dirs as if written by an orthodox Java devotee), so take everything described below with healthy dose of skepticism

Task of searching for modifications/patches in general is well known, the problem in our case is that binary files is just huge

  • cicc from SDK 13.1 has size 80mb
  • libLLVM.so.21.1 128mb
besides that cicc does not contain DWARF debug info, so using of tools like bindiff seems like a questionable idea. Let's check if can invent some dirty tricks to reduce volume of code for comparison

CL options

Let's start with something easy - as you could know in llvm all CL options represented as static vars of template class cl::opt<Type>, like

static cl::opt<bool>
NVVMReflectEnabled("nvvm-reflect-enable", cl::init(true), cl::Hidden,
                   cl::desc("NVVM reflection, enabled by default"));

We can guess that code to create them must be located in array of constructors - in section .ctors or .init_array (actually second can have any name - only section type INIT_ARRAY matters). What really important here is that constructor of these object must load some constant strings from .rodata section

So I wrote dirty hack to disasm array of constructors and dump all used string to file. Results:

I also wrote simple script for comparison, so just run

perl cstr.pl clang-cstr.txt cicc-cstr.txt

What interesting we can note in its output?

  • print-schedule - Print 'sched: [latency:throughput]' in .s output
  • wmma-memory-space-opt
  • dump-ir-before-memory-space-opt & dump-ir-after-memory-space-opt
  • enable-bfi64 - Enable generation of 64-bit BFI instructions
  • nvptx-add-scalar-move-for-vector-load, nvptx-lower-global-ctor-dtor & nvptx-use-max-local-array-alignment
This method retrieves all the strings used in constructors, and for this reason, it is not very reliable, so check every interesting string in disasm

Passes 

понедельник, 12 октября 2026 г.

comparison of nvcc vs clang nvptx backend, part 2

Part 1

First of all, I have to say that digging through LLVM source code is simply disgusting - its code tree is monstrously huge and parts from nvptx scattered across the most unexpected places. So to extract needed tables I just stuck libLLVM.so.21.1 (btw size 135Mb) into IDA Pro and reused the same IDC scripts for cicc, just removed strings decryption. Typical open-source, yeah

Mlir

cicc does not have MLIR at all. This fact probably deserves a larger font:
cicc does not have MLIR

The proof is left as an exercise for the reader very simple - just grep strings like mlir/linalg/affine etc in cicc binary. Let's assume that we have some way to load LLVM bc into cicc - even in this case, we wouldn't be able to force it to generate more efficient PTX for code containing MLIR

Btw this is not first case when serious amount of real code generation was done without mlir - for example vectorization for RISC-V too. And somewhere on the side, you’re bound to hear that argument from clueless managers: "if even Oprah Microsoft uses a monorepo, you must be happy using one too" 


Builtins

Notably, neither Nvidia nor LLVM documented the list of supported builtins. "doc is also quite good in my opinion", of course


Intrinsics

I think this is one of the secrets behind why Nvidia's code is faster - they just capable of generating 1.5 times as many PTX instructions. What happens when NVPTX backend can't compress group of operations into single PTX? Sure it generates several - like ld/cvt/something or something/cvt/st. And ptxas isn't enough smart to detect such patterns and apply more optimal instructions
 

Conclusion

Category cicc Clang (NVPTX)
Builtins 870 715
Intrinsics 3183 1998
If you use MLIR - then you cursed forever must use NVPTX backend only and your code will always be 15-20% slower

среда, 7 октября 2026 г.

comparison of code from nvcc vs clang

Lets continue our methodical dissection of PTX/SASS code generated by different compilers

Last week I implemented on CUDA count-sketch algorithm. It requires d = 2 * t + 1 calculating of 2 different family of hashes. As you can see d is always odd and don't fit on warpsize 32, so I used reverse approach - warp processing 32 items from stream and each thread calculates it's own hashes in loop. The code is terrible, consists of nothing but dirty hacks and optimized for specific structures, so that’s why I’m ashamed to show it in its entirety. Nsight shows that code for hashes calculating is where most of the time is spent (~80%), so this code will be our test data. As you can see it's just plain boring integer arith - no fashionable mma or even warp reduce operations

For tests I used clang-21 and nvcc/ptxas from CUDA SDK 13.1. Output data located in 2 sub-dirs:

clang-21, options for clang --target=nvptx64-nvidia-cuda --cuda-device-only -fomit-frame-pointer -O --offload-arch=sm_XX -S

nvcc, see details how to dump LLVM bc here. Btw cicc from sdk 13.1 is based on llvm21 too, like
strings ../../../13.1/cicc/cicc | grep ^LLVM
LLVM21.0.0

As final stage the same ptxas was used to produce object files with same set of options -c -arch sm_XX

Results

пятница, 2 октября 2026 г.

ptx generated by LLVM NVPTX

I decided to complete saga with ptx instructions which can be generated with popular compilers and check clang with NVPTX target

Gathering from LLVM source files with PTX instructions turned out to be a challenging task. The Usual Suspects NVPTXInstrInfo.td & NVPTXIntrinsics.td lay in directory llvm/lib/Target/NVPTX, but they don't contain operation definitions. For unknown reason file NVVMOps.td located in mlir/include/mlir/Dialect/LLVMIR/ - don't ask me why

Then I add new option -N to my long-suffering iptx.pl to collect PTX instructions. As you can see it's not true parser - it just extracting any strings and then try to find matches in set of PTX instructions. Dirty & ugly hack but since we lookup on small dictionary with only 270 instruction it works in near-linear time. Another problem is that strings with instruction names can be modified like append operands etc. Well, since cicc itself based on LLVM - if some instruction marked as missed in clang it's highly likely also will be marked as missed in cicc too, so the obtained sets are sufficient for the comparison task

Results

Check two files:

  1. ptx-cicc.txt - set of PTX instructions which cicc can't produce. As you can see coverage 57.8%
  2. ptx-nv.txt - set of PTX instructions which clang can't produce for NVPTX. Coverage 58.9%

And instructions missed in clang (but presented in cicc) are:

  • _ldsm
  • _mma
  • discard
  • dp2a hi/lo
  • madc hi/lo
  • p2r
  • trap
9 / (270 * 0.58) = 5.7%, which correlates reasonably well with the number of PTX instructions from the cicc that use undocumented attributes (5-7%)

воскресенье, 27 сентября 2026 г.

read "the anatomy of go"

As you can expect if book about language with deliberately castrated syntax (even python has something similar to ternary operator btw) has 864 pages - it detailed everything about it's runtime. The only couple of missed things are

  1. integration with CGO
  2. generic methods - but they were introduced in version 1.27 month ago

I personally especially appreciated chapter 7 about integration of GC into native code with multithreading - with detailed description of what happened between "stop the world" and end of sweeping phase

So if you doing occasionally RE of go binaries - this book is absolutely Must Read

And now my cynical thoughts about go language

Pros

Idea of usermode threads scheduling + polling of sockets is very good and allows processing of network traffic with minimal latency (although I have a vague doubt that it was stolen from Erlang)

functions are first-class citizens and this allows to do things like fp-go (sadly practically no one uses it anyway)

Cons

I personally think that biggest flaw in design of go is lack of normal macros allowing modification of AST. Having such macros lets you write your own syntax with blackjack and patter matching

io_uring support looks unorganic- there are lots of 3rd party libraries but no embedding in language itself like they done with sockets polling. I think this is very strange - the run-time already has almost all code for it in Windows IO Completion processing logic

go lang implements it's own codegen - no LLVM or other monsters. At one hand this allows very fast compilation, but on other - it means that they lack of SSE/AVX (or generally speaking - automatic loop vectorization)

Implementation of generics is weird. Сommon objection against C++ VTBLs is that indirect calls cause code cache miss. Ok, but golang went even further - they have two calls for generics:

  1. first for interface dictionary loading
  2. second for shapes

Poor stack management - especially for recursive functions. They manage size of stack for every function call and in case of stack enlargement

  1. allocate new memory for stack
  2. copy whole content from old stack to newly allocated memory
As you can expect this is not cheap operation, and there is good question - do you really need to have for each frame contiguous region of memory? Highly likely that better solution would be chain of more short stack frames each allocated in heap at least for cold paths/recursive calls

defered code executes at end of function - and so it can't be used as C++ RAII

PGO is very limited  - for example they have hardcoded table class_to_size consisting of 67 elements and describing the sizes of pools for allocated objects. The authors provide no explanation as to why they chose precisely these sizes, but PGO could collect statistics about allocations of you application and made new table tailored specially for you

четверг, 24 сентября 2026 г.

fatbin tools for object files

Yesterday, I needed to patch CUBIN inside object file, and my fb failed to do it. Let's check why:

file bobhash32.o
bobhash32.o: ELF 64-bit LSB relocatable, x86-64, version 1 (SYSV), not stripped

readelf -S bobhash32.o
  [ 8] __nv_relfatbin    PROGBITS         0000000000000000  00000720
       0000000000005f18  0000000000000000   A       0     0     8
  [ 9] .nvFatBinSegment  PROGBITS         0000000000000000  00006638
       0000000000000018  0000000000000000  WA       0     0     8
  [10] .rela.nvFatBinSeg RELA             0000000000000000  000070d8
       0000000000000018  0000000000000018   I      18     9     8
As you can see we have section .nvFatBinSegment but section with CUBINs has name __nv_relfatbin instead of usual .nv_fatbin. Beside we also have relocs for .nvFatBinSegment:

readelf -r bobhash32.o

Relocation section '.rela.nvFatBinSegment' at offset 0x70d8 contains 1 entry:
  Offset          Info           Type           Sym. Value    Sym. Name + Addend
000000000008  001000000001 R_X86_64_64       0000000000000000 __nv_relfatbin + 0
Offset 8 is field data and in object file it zeroed, but 64bit reloc points to section __nv_relfatbin with addend 0

So I added some very limited support of object files - currently only for x86-64 and single reloc type R_X86_64_64. And magically it works now

суббота, 19 сентября 2026 г.

ptx asm in llvm ir

I asked 7 month ago in r/llvm question how I can insert PTX asm right in LLVM IR and got exactly zero answers. So, as usual, I had to figure it out on my own (depressing little song "No Help is Coming" is playing in the background)

How inline PTX looks like in text form:
%7 = call i32 asm sideeffect "madc.hi.cc.u32 $0,$1,$2,$3;", "=r,r,r,r"(i32 %.sroa.018.0.extract.trunc, i32 %.sroa.282.0.extract.trunc, i32 0) #5, !srcloc !9 

So basically it is just call result-type asm with some arguments in parentheses (note that type of result $0 is i32 and it described after keyword call). If you need result of PTX instruction - just assign it to some variable. Official documentation says that #5 is attributes list - somewhere below it defined as
attributes #5 = { nounwind }
and !9 is metadata - is this case for debug info srcloc:
!9 = !{i32 46731}

Well, that was easy part of story - and now Something Completely Different (tm). LLVM IR is strictly typed (I would say - redundantly strictly), so types first time defined for each argument - like i32 for $1, $2 and $3. Second time - in string called operand constraint codes - in my case it is "=r,r,r,r". And official documentation blatantly lies about them. Let's check some source code - method getRegForInlineAsmConstraint in NVPTXISelLowering.cpp. As you can see it accepts following codes:

  • b - 1bit, predicates
  • c & h - 16bit, like (.b16 / .u16 / .s16)
  • r & f - 32bit, like (.b32 / .u32 / .s32) and .f32 for f
  • l, N, d - 64bit, (.b64 / .u64 / .s64) & .f64 for d
  • q - 128bit since sm70+
  • 0 - meaning is still unknown

Symbol '=' is so called Constraint Modifier:

  • = Write-only output operand (overwrites previous contents)
  • + Read-write operand (input and output tied to the same register)
  • & Early-clobber operand (modified before inputs are consumed)
  • ~ Clobber list marker (tells LLVM a register or memory/flags are modified implicitly
Yet another unpleasant discovery - you can freely swap order of operands - for example this variant is exactly the same as above one:
call i32 asm sideeffect "madc.hi.cc.u32 $0,$2,$1,$3;", "=r,r,r,r"(i32 %.sroa.282.0.extract.trunc, i32 %.sroa.018.0.extract.trunc, i32 0)

This makes the task of parsing & comparison of PTX instructions non-trivial - especially in complex cases like
%1 = call { i32, i32, i32, i32 } asm sideeffect "tex.grad.1d.v4.u32.f32 {$0, $1, $2, $3}, [$4, {$5}], {$6}, {$7};", "=r,=r,=r,=r,l,f,f,f"(i64 %tmp5, float %tmp6, float %tmp7, float %tmp8)

PTX from cicc

Once you understand how inline PTX is represented in LLVM IR, the next step is examining how nvidia’s own internal toolchain leverages it.

While doing some RE of nvidia's llvm-based back-end I dumped inline PTX instructions. Now when I have PTX parser the next logic step is try to parse PTX from cicc and for example try find some undocumented instruction/attributes (which nvidia uses for unfair competitive advantage). So I added to my parser option -r to dump instructions with unrecognized attributes, and also wrote little perl script to collect them. Then run whole pipe like

../ptx.parse/tp -r < ptx.txt | perl ../ptx.parse/ra.pl

And try to guess what happened? Yes - nvidia uses ~5-7% of instructions with undocumented attributes

пятница, 11 сентября 2026 г.

shrinking holes in SASS allocated registers

In my previous post I discovered that SASS register allocation can have holes - non-contiguous register indices allocated to a function where intermediate registers like R57 remain unused despite R56 and R58 being live/allocated

To estimate size of problem I wrote some code to collect statistics about number (and share) of functions having holes in register allocations:

  • libcublas.so.13.7.0.74.sm_90.cubin
    ; 34 holes in regs (784), 0.043367
    ; 3 holes in uregs (434), 0.006912
    ; 34 functions with holes (0.629630 from total)
  • libcublas.so.13.7.0.608.sm_90.cubin
    ; 41 holes in regs (8546), 0.004798
    ; 15 holes in uregs (2784), 0.005388
    ; 39 functions with holes (0.102632 from total)
  • libcublas.so.13.7.0.935.sm_90.cubin
    ; 19 holes in regs (5016), 0.003788
    ; 17 holes in uregs (2012), 0.008449
    ; 11 functions with holes (0.059783 from total)

As you can see holes occupy up to 4% of total registers (in average 0.3-0.5%) and it's very tempting to try reduce them. It would seem—what could be simpler? If we have something like that
; RHoles max 61: R56 R58

just remap in whole function R61 to R58 and R60 to R56, and then reduce EIATTR_REGCOUNT,right? Well, actually no

понедельник, 31 августа 2026 г.

Cyclomatic complexity of SASS code

Many algorithms of my SASS optimizer work with code blocks. So I decided to collect some metrics about blocks, resources usage per block/function etc to find outliers (like too short blocks or blocks with anomaly high registers numbers). But before I present the results I should note that building of cyclomatic complexity for SASS is not easy task:

  • approximately half of EIATTR attributes are undocumented. And yet, there are some very remarkable ones there - like EIATTR_COROUTINE_RESUME_ID_OFFSETS. Judging by the name they are clearly related to coroutines and so should be taken into account while carving code blocks. Unfortunately, there are no Cubin files in my collection that contain this attribute
  • Predicated instructions. Well, this is not SASS-specific problem - for example old 32bit arm had them too. But for example how consider case with several instructions with predicates in the same block? Each of them can modify value of predicate register - then this will be another branch, right? So I just ignore predicates for now
  • How to carve code blocks? For my needs, I require maximum-sized blocks to minimize the number of blocks used - so I ignore many cases like BSSY/BSYNC pairs. Sure you can modify my logic of CFG building and make it more similar to classic SSA - see function dg in dg2.pl and the preceding extensive commentary

All tests were conducted on libcublas.so.13.7.0.10 from CUDA SDK 13.4 for sm90 cubins, command line options for dg2.pl -gtT:

  • -g to build CFG
  • -t for registers/predicates tracking
  • -T is new option added special to produce various useless metrics 

Count and length of blocks

четверг, 20 августа 2026 г.

parser of PTX instructions

A couple of facts to start things off

From official "Inline PTX Assembly in CUDA":

The compiler front end does not parse the asm() statement template string and does not know what it means or even whether it is valid PTX input

And second, less well-known one: order of instruction's attributes (except types of operand) is not important

The combination of these facts leads to stark conclusion - CUDA compiler front-ends totally ignore PTX inline asm and only PTXAS known how to parse them. For example cuKLEE does this wrong

So I made simple (and hopefully fast) parser of PTX instructions

Note: this is not full featured replacement of PTX parser. it is designed specifically to extract instruction attributes and determine the correct instruction form based on argument types and counts

For example for
cvt.bf16x2.e5m2x2.rn.relu.scaled::n2::ue8m0.satfinite d, a, scale-factor;
output will be something like

tail: d, a, scale-factor;
3 tail operands
--> cvt
 line 71: 01x E32Q16
--- types 2:
 bf16x2
 e5m2x2
--- attrs 4:
 1:5 satfinite
 2:7 scaled::n2::ue8m0
 1:0 relu
 3:3 rn 

пятница, 7 августа 2026 г.

optimization of SASS stall counts, part 2

In part 1 I suggested that "native" latency tables are too conservative and can be relaxed for some instructions. Indeed, let's look at couple of examples:

In c8.txt there is two delays for IMAD - with value 4 and IMAD.WIDE with value 9. In *_2.txt IMAD included in many groups but none reflect 'wide' form, like

 IMAD_OP = {IMAD,IMADfmalighter_pipe,IMAD32I,IMAD32Ifmalighter_pipe,
             IMUL,IMULfmalighter_pipe,IMUL32I,IMUL32Ifmalighter_pipe}

Corresponding row in RaW table looks like
IMAD_OP`{Rd @RdRange,Rd2 @Rd2Range} : 5 4 6 6 6 6 8 6 6 7 7 7 7 7 7 6 4

For what instructions such relaxation is possible? Well, FP instructions already cleanly separated right at ISA level - for FP64 we have DADD/DMUL/DFMA vs standard FP32 ops. So I patched only restricted set of integer instructions like IMAD/IMUL/IMNMX & SEL, then made binding of this method in Perl and ran tests

An unpleasant discovery awaited me - we can't safely patch delay for xxSETP instructions (ISETP/PSETP/UISETP). I don't know why - maybe due to the fact that predicates can be used to select every instruction for execution and so update requires some hardcore synchronization with instructions decoder/scheduler

results

As usually it depends from version of CUDA SDK, optimization options and your kernel. For FP intensive kernels speed-up is negligible like 0.06%

However for kernels with lots of integer arithmetic it can be much bigger - 0.2-0.3% 

new cmd line options for dg2.pl

  • -R to apply delays relaxation
  • -S to collect detailed statistics on instructions types distribution

среда, 22 июля 2026 г.

optimization of SASS stall counts

Optimal instructions scheduling is NP-hard task. For this reason almost all compilers implement metaheuristic methods like list scheduling/Gibbons–Muchnick algorithm etc. ptxas is no exception - it also generates non-optimal scheduling, and this opens some opportunity for automatic optimization. Here I want to present scheduling model for SASS, tool for optimization of stall counts for binary CUBIN files, achieved results and possible direction for further improvements

First version

Has name dg.pl and used latency table extracted from ptxas with RE. Unfortunately it has at least 2 fatal flaws

  1. This latency table is incomplete - for example some instructions like PRET/BFE/ICMP are missed. I tried to find similar table in more old ptxas versions - like 12, 11 and even 9 - it seems that they all incomplete
  2. It takes into account only Read after Write joints and patched code crashed in random places, and on each launch in different places
After considerable and agonizing reflection, I concluded that it had used an incorrect model
so I decided to continue experiments with latency tables early extracted from nvdisasm

Latency tables

среда, 1 июля 2026 г.

identification of const bank0 params

Official documentation doesn't disclose ConstBank0 (c[0x0]) memory layout used at the SASS level for kernel arguments and special registers (like %gridid, %nctaid)

So I've spent last week trying to solve this deceptively simple problem. Names of params are documented in official doc - seems that this time ptxas can't add something new to this list

Unfortunately I was unable to find inside ptxas some nice looking tables for pile of SM.  What other approaches can we use? As usually the first thought is to do some brute-force.


Brute-forcing

Lets write in plain PTX dummy function trash with u32 return value - something like
.visible .func (.param .u32 func_retval0) trash
{
  .reg .u32       %r<3>;
  mov.u32    %r0, %gridid;
  mov.u32    %r1, %nctaid.x;
  add.u32    %r0, %r0, %r1;
  st.param.u32 [func_retval0+0], %r0;
  ret;
}
The final st.param is very important bcs otherwise compiler will just eliminate whole code. Instead of gridid & nctaid.x we can substitute pair of special registers, compile with ptxas to specific SM and then parse output of nvdisasm/nvd/whatever can disasm SASS
Surprisingly, this stupid method worked very well, however there are holes in params. So it's time to check


CUDA runtime

I extracted them in December and now we can parse output of nvdisasm to find not identified yet offsets. The funny part is that official nvdisasm failed on several files, like sm54.elf
nvdisasm error   : Could not establish the target of this branch operation
or on sm23.elf
nvdisasm error   : Wrong Anti dependency order in function 'vfprintf_internal'
nvdisasm         .         @P1 LD.E.CG.64 R14, [R4], P0
nvdisasm         .          -- Anti(PRED,0),0*,0 -->
nvdisasm         .         @!P1 LEA.HI.X P0, R7, R12, RZ, R13

So I was forced to use my own nvd
It turned out that the parameter space is divided into two parts - there are block of parameters at offset 0x1860 (holding for example starting PC of kernel) used by kernel launch logic and CnpXXX functions
So now we know lots of offsets and their sizes. However to identify semantics of many found offsets we need debugger


cuda-gdb rushes to the rescue

I made fake PTX for each SM, patched it with my ced and inspected in debugger values with command $_cuda_const_bank(0, offset). Actually this was the most boring part of work and I still didn't recognized some fields. Also I don't have expensive monsters like sm100+ so I extracted only params from Maxwell till Hopper

 

Results

I also add this code to my XS perl module and nvd, so output looks like
/*58*/  XMAD R02,R17,c[0][0x8],R02 ?trans1;
 ; cb0 param %ntid_x
Names starting with '%' were extracted with just disasm of dummy trash function
 
Happy hacking!

вторник, 23 июня 2026 г.

RE of PTX grammar from ptxas, part 4

Parts 1, 2 & 3

First of all, it should be noted that the mask of instruction attributes has size 20 bytes, so I updated dump for them.
structure for this attributes descriptor has size 0xd8 bytes and some fields:
  • mask at offset 0
  • name of instruction at 0xC8
  • index at 0xD0
Instructions selecting first by name and then right form by operand types. This means that while the order of the attributes does not matter, the relative order of the operand types is important - leftmost is type of operand 0, next is type of operand 1 and so on

 

Names of numerical pseudo-instructions

in part 3 I pointed out that there are 473 names consisting only of numbers, like "1030557441". Grigory Evko suggested that this is adler32 hash from builtin function names, so I found huge function for instruction 0xc6 (_gen_proto) returning 1078 prototypes like
.weak .func (.reg .f32 %fv1) __cuda_sm20_div_rz_f32 (.reg .f32 %fa1, .reg .f32 %fa2)
and then intersected them by hash - so now we know all real names


EBNF grammar

You can see it here
To build run iptx.pl -e
The last two columns are operand suffix & encoding 

 

How complete it is?

That's good question. If we accept that attributes descriptors contain full list of attributes for each instruction then 20 bytes masks has 121 non-zero bits:
FD FF FF FF F1 FF FF 9F F9 FF E7 CF FF F3 DF FF FF 00 00 00
I was able to identify 114 of them - this is 94%
Also currently I extracted 119 tables with attributes names and only 11 are still not connected (check them with iptx.pl -t)

On other hand in function for attributes processing there are 3 switch tables with 139, 140 & 173 cases (last one has ~90% of entries with error "Unexpected instruction types specified")