-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathsample.annotated.html
More file actions
1504 lines (1395 loc) · 70.9 KB
/
Copy pathsample.annotated.html
File metadata and controls
1504 lines (1395 loc) · 70.9 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>Saxpy with FMA — sample article</title>
<style>
body { font: 16px/1.55 -apple-system, sans-serif; max-width: 760px; margin: 2rem auto; padding: 0 1rem; color: #1d2129; }
h1 { font-size: 1.6rem; }
pre { background: #f6f7f8; padding: 12px 14px; border-radius: 6px; overflow-x: auto; font-size: 13px; }
code { font-family: ui-monospace, Menlo, Consolas, monospace; }
</style>
</head>
<body>
<h1>Saxpy with FMA on x86 and aarch64</h1>
<p>"Saxpy" — single-precision <code>a*x + y</code> — is the canonical kernel for measuring fused-multiply-add throughput.
Below are minimal SIMD implementations on x86 (AVX/FMA) and aarch64 (NEON).</p>
<h2>x86 (AVX + FMA, 8 lanes per iteration)</h2>
<pre>#include <immintrin.h>
void saxpy_avx(float a, const float *x, const float *y, float *out, size_t n) {
__m256 va = _mm256_set1_ps(a);
for (size_t i = 0; i + 8 <= n; i += 8) {
__m256 vx = _mm256_loadu_ps(x + i);
__m256 vy = _mm256_loadu_ps(y + i);
__m256 vr = _mm256_fmadd_ps(va, vx, vy);
_mm256_storeu_ps(out + i, vr);
}
}</pre>
<p>The hot intrinsic is <code>_mm256_fmadd_ps</code>: per-lane <code>a*b + c</code> with a single rounding step,
beating <code>_mm256_add_ps(_mm256_mul_ps(a, b), c)</code> in both throughput and accuracy.</p>
<h2>aarch64 (NEON, 4 lanes per iteration)</h2>
<pre>#include <arm_neon.h>
void saxpy_neon(float a, const float *x, const float *y, float *out, size_t n) {
float32x4_t va = vdupq_n_f32(a);
for (size_t i = 0; i + 4 <= n; i += 4) {
float32x4_t vx = vld1q_f32(x + i);
float32x4_t vy = vld1q_f32(y + i);
float32x4_t vr = vfmaq_f32(vy, vx, va);
vst1q_f32(out + i, vr);
}
}</pre>
<p>NEON's <code>vfmaq_f32(a, b, c)</code> computes <code>a + b * c</code> per lane (note the argument order is
different from Intel's <code>_mm256_fmadd_ps(a, b, c)</code> which is <code>a * b + c</code>).</p>
<h2>SVE — scalable, length-agnostic</h2>
<pre>#include <arm_sve.h>
void saxpy_sve(float a, const float *x, const float *y, float *out, size_t n) {
svfloat32_t va = svdup_n_f32(a);
for (size_t i = 0; i < n; i += svcntw()) {
svbool_t pg = svwhilelt_b32(i, n);
svfloat32_t vx = svld1_f32(pg, x + i);
svfloat32_t vy = svld1_f32(pg, y + i);
svfloat32_t vr = svmla_f32_m(pg, vy, vx, va);
svst1_f32(pg, out + i, vr);
}
}</pre>
<p>Notice the use of types <code>svfloat32_t</code> (a hardware-length-dependent vector) and <code>svbool_t</code>
(the predicate that handles the loop tail without needing a scalar epilogue). The
<code>svwhilelt_b32</code> intrinsic generates a per-lane mask that's true while <code>i < n</code>.</p>
<!-- simd-annotate: embedded simd-tooltips library + on-page intrinsic data -->
<script data-no-auto data-simd-tooltips-embed>
/**
* simd-tooltips.js — drop-in tooltip library for SIMD intrinsic names.
*
* Default mode (lazy): listens for mousemove globally; when the cursor is over
* a word that matches a known SIMD intrinsic, pops a tooltip with its
* signature and a short description. The DOM is never mutated.
*
* Optional mode (wrap): walks the page once at init, wraps every intrinsic
* in <span class="simd-intrinsic"> with tabIndex=0, gives keyboard users a
* focusable element and a visible underline. Set `wrap: true`.
*
* Usage (auto-init, default lazy mode):
*
* <script src="/path/to/simd-tooltips.js" defer><\/script>
*
* Usage (auto-init with options on the script tag):
*
* <script src="/path/to/simd-tooltips.js"
* data-scope="article"
* data-on="click"
* data-wrap // opt into DOM-walk + wrap-in-span mode
* data-base-url="/path/to/"
* defer><\/script>
*
* Usage (manual init):
*
* <script src="/path/to/simd-tooltips.js" data-no-auto defer><\/script>
* <script>
* SimdTooltips.init({
* scope: '.code', // only meaningful in wrap mode
* on: 'hover', // 'hover' | 'click'
* wrap: false, // default: lazy detection (no DOM walk)
* baseUrl: '/path/to/',
* names: {...}, // optional: pre-supplied names index
* data: {...}, // optional: pre-supplied records
* }).then(() => console.log('ready'));
* <\/script>
*
* License: same as the simd.dev project.
*/
(function (root) {
'use strict';
const VERSION = '0.1.0';
const DEFAULTS = {
scope: 'body',
on: 'hover', // 'hover' | 'click' | 'hover+?' (lazy only for 'hover+?')
wrap: false, // false = lazy hover detection, true = walk and wrap
pseudocode: 'collapsed', // 'collapsed' (default) | 'expanded' | 'off'
baseUrl: scriptDir(),
namesUrl: null, // defaults to baseUrl + 'simd-names.json'
dataUrl: null, // defaults to baseUrl + 'simd-data.json'
names: null, // pre-supplied (skip fetch)
data: null, // pre-supplied (skip fetch)
skipSelector: 'script,style,textarea,input,select,option,.simd-skip',
wrapClass: 'simd-intrinsic',
tooltipClass: 'simd-tooltip',
moveThrottleMs: 30, // throttle for lazy-mode mousemove handler
pageBase: 'https://simd.dev/', // dedicated-intrinsic-page base URL
};
// ---------------------------------------------------------------------
// State
// ---------------------------------------------------------------------
let cfg = null;
let nameSet = null; // Set<string> for O(1) token lookup
let typeSet = null; // Set<string> -- subset of names that are SIMD types
let ambiguous = null; // {alias: [canonical, ...]}
let records = null; // {name: record} -- lazy
let clusters = null; // {cluster_id: [name, ...]} -- variant groups
let dataPromise = null; // Promise<records> in flight
let activeTooltip = null;
let activeTarget = null; // current trigger element (or virtual key)
let activeKey = null; // string id of the current source word
let hideTimer = null;
let lastMoveTs = 0;
let attachedListeners = []; // [{target, type, fn, opts}, ...] for clean re-init
let activeHint = null; // {el, word, rect} -- "hover+?" mode badge
let hintHideTimer = null;
// ---------------------------------------------------------------------
// Public API
// ---------------------------------------------------------------------
const SimdTooltips = {
version: VERSION,
init: init,
scan: scan, // wrap-mode only: re-scan a subtree (SPAs)
unwrap: unwrap, // wrap-mode only: remove all wrappers
hide: hide,
compilerExplorerUrl: function (rec) { return compilerExplorerUrl(rec); },
// Compiler / march / headers for `rec`. Used by simd.dev's "run on CE"
// feature to build a custom harness with the same toolchain that
// produced the cached worked example.
ceConfigFor: function (rec) { return ceConfigFor(rec); },
_state: () => ({ cfg, nameCount: nameSet ? nameSet.size : 0, recordCount: records ? Object.keys(records).length : 0 }),
};
// ---------------------------------------------------------------------
// Init
// ---------------------------------------------------------------------
async function init(opts) {
// Tear down any previous configuration so re-init (e.g. switching trigger
// mode) doesn't stack handlers on top of the old ones.
detachListeners();
hide();
cfg = Object.assign({}, DEFAULTS, opts || {});
if (!cfg.namesUrl) cfg.namesUrl = joinUrl(cfg.baseUrl, 'simd-names.json');
if (!cfg.dataUrl) cfg.dataUrl = joinUrl(cfg.baseUrl, 'simd-data.json');
injectStyles();
// Names: load eagerly (needed for both modes).
let namesDoc;
if (cfg.names) {
namesDoc = cfg.names;
} else {
namesDoc = await fetchJSON(cfg.namesUrl);
}
nameSet = new Set(namesDoc.names || []);
typeSet = new Set(namesDoc.types || []);
ambiguous = namesDoc.ambiguous || {};
// Data: defer. If pre-supplied, use immediately.
if (cfg.data) {
records = cfg.data.records || cfg.data;
}
if (cfg.wrap) scan(cfg.scope);
attachListeners();
return SimdTooltips;
}
// ---------------------------------------------------------------------
// Listeners
// ---------------------------------------------------------------------
function listen(target, type, fn, opts) {
target.addEventListener(type, fn, opts);
attachedListeners.push({ target, type, fn, opts });
}
function detachListeners() {
for (const { target, type, fn, opts } of attachedListeners) {
target.removeEventListener(type, fn, opts);
}
attachedListeners = [];
}
function attachListeners() {
if (cfg.wrap) {
if (cfg.on === 'click') {
listen(document, 'click', onWrapClick, true);
// Focus handling in click mode: only react to *keyboard* focus
// (Tab arrival), not the mousedown-induced focus that would
// otherwise fire before the click and toggle the tooltip off.
// We gate on :focus-visible inside onWrapKbFocusIn.
listen(document, 'focusin', onWrapKbFocusIn, true);
listen(document, 'focusout', onWrapLeave, true);
} else {
listen(document, 'mouseover', onWrapEnter, true);
listen(document, 'mouseout', onWrapLeave, true);
listen(document, 'focusin', onWrapEnter, true);
listen(document, 'focusout', onWrapLeave, true);
}
} else {
// Lazy modes
if (cfg.on === 'click') {
listen(document, 'click', onLazyClick, true);
} else if (cfg.on === 'hover+?') {
// Hover surfaces a "?" badge; click on the word or the badge opens
// the full tooltip.
listen(document, 'mousemove', onLazyMove, true);
listen(document, 'click', onLazyClick, true);
listen(document, 'mouseleave', onDocLeave, true);
} else {
// Default 'hover': full tooltip on hover.
listen(document, 'mousemove', onLazyMove, true);
listen(document, 'mouseleave', onDocLeave, true);
}
}
listen(document, 'keydown', onKeydown, true);
listen(window, 'scroll', repositionOrHide, { passive: true, capture: true });
listen(window, 'resize', repositionOrHide, { passive: true });
}
function onDocLeave() { scheduleHide(); }
// ---------------------------------------------------------------------
// Lazy mode: detect word under cursor without DOM mutation
// ---------------------------------------------------------------------
function onLazyMove(ev) {
const now = performance.now();
if (now - lastMoveTs < cfg.moveThrottleMs) return;
lastMoveTs = now;
detectAndShow(ev.clientX, ev.clientY);
}
function onLazyClick(ev) {
// Clicks inside the open tooltip should pass through (so links work).
if (activeTooltip && activeTooltip.contains(ev.target)) return;
// Clicks on the hint badge are handled by the badge's own listener.
if (activeHint && activeHint.el && activeHint.el.contains(ev.target)) return;
if (!detectAndShow(ev.clientX, ev.clientY, /*click=*/true)) {
hide();
removeHint();
} else {
ev.preventDefault();
}
}
function detectAndShow(clientX, clientY, click) {
// If the pointer is over our tooltip, leave it alone. Use elementFromPoint
// + contains() rather than rect math so it's robust regardless of layout
// (children with overflow, transforms, etc. still resolve correctly).
if (isOverActiveTooltip(clientX, clientY)) {
if (hideTimer) { clearTimeout(hideTimer); hideTimer = null; }
return false;
}
if (isOverHint(clientX, clientY)) {
if (hintHideTimer) { clearTimeout(hintHideTimer); hintHideTimer = null; }
return false;
}
if (cfg.on === 'hover+?') return detectHoverHint(clientX, clientY, click);
const found = wordAtPoint(clientX, clientY);
if (!found) {
if (!click) scheduleHide();
return false;
}
const { word, rect } = found;
const key = word + '@' + Math.round(rect.left) + ',' + Math.round(rect.top);
if (key === activeKey) return true;
activeKey = key;
if (hideTimer) { clearTimeout(hideTimer); hideTimer = null; }
showAtRect(word, rect);
return true;
}
function detectHoverHint(x, y, click) {
const found = wordAtPoint(x, y);
if (click) {
// Click on a word: open full tooltip and clear the hint.
if (found) {
removeHint();
const key = found.word + '@' + Math.round(found.rect.left) + ',' + Math.round(found.rect.top);
activeKey = key;
if (hideTimer) { clearTimeout(hideTimer); hideTimer = null; }
showAtRect(found.word, found.rect);
return true;
}
return false; // click outside: caller will hide()
}
// Mouse move:
if (!found) {
scheduleRemoveHint();
return false;
}
if (!activeHint || activeHint.word !== found.word) {
showHint(found.word, found.rect);
}
return true;
}
function isOverActiveTooltip(x, y) {
if (!activeTooltip || activeTooltip.style.display === 'none') return false;
const e = document.elementFromPoint(x, y);
return !!(e && activeTooltip.contains(e));
}
function isOverHint(x, y) {
if (!activeHint || !activeHint.el || activeHint.el.style.display === 'none') return false;
const e = document.elementFromPoint(x, y);
return !!(e && activeHint.el.contains(e));
}
function ensureHintEl() {
if (activeHint && activeHint.el && activeHint.el.isConnected) return activeHint.el;
const el = document.createElement('span');
el.className = 'simd-hint';
el.setAttribute('role', 'button');
el.setAttribute('aria-label', 'Show intrinsic info');
el.tabIndex = 0;
el.textContent = '?';
document.body.appendChild(el);
el.addEventListener('mouseenter', () => {
if (hintHideTimer) { clearTimeout(hintHideTimer); hintHideTimer = null; }
});
el.addEventListener('mouseleave', scheduleRemoveHint);
el.addEventListener('click', (ev) => {
ev.stopPropagation();
ev.preventDefault();
if (!activeHint) return;
const { word, rect } = activeHint;
removeHint();
activeKey = word + '@' + Math.round(rect.left) + ',' + Math.round(rect.top);
if (hideTimer) { clearTimeout(hideTimer); hideTimer = null; }
showAtRect(word, rect);
});
return el;
}
function showHint(word, rect) {
const el = ensureHintEl();
el.style.display = 'inline-block';
// Position: just to the right of the word, top-aligned. Fall back to
// left-of when there's no room on the right.
el.style.left = '0px';
el.style.top = '0px';
const hr = el.getBoundingClientRect();
let left = rect.right + 2;
if (left + hr.width + 4 > window.innerWidth) left = rect.left - hr.width - 2;
if (left < 4) left = 4;
let top = rect.top + (rect.height - hr.height) / 2; // vertically centered with word
if (top < 4) top = 4;
if (top + hr.height + 4 > window.innerHeight) top = window.innerHeight - hr.height - 4;
el.style.left = Math.round(left + window.scrollX) + 'px';
el.style.top = Math.round(top + window.scrollY) + 'px';
if (hintHideTimer) { clearTimeout(hintHideTimer); hintHideTimer = null; }
activeHint = { el, word, rect };
}
function scheduleRemoveHint() {
if (hintHideTimer) clearTimeout(hintHideTimer);
hintHideTimer = setTimeout(removeHint, 150);
}
function removeHint() {
if (hintHideTimer) { clearTimeout(hintHideTimer); hintHideTimer = null; }
if (activeHint && activeHint.el) activeHint.el.style.display = 'none';
activeHint = null;
}
function wordAtPoint(x, y) {
const elt = document.elementFromPoint(x, y);
if (!elt) return null;
if (cfg.skipSelector && elt.closest(cfg.skipSelector)) return null;
if (activeTooltip && activeTooltip.contains(elt)) return null;
const pos = caretFromPoint(x, y);
if (!pos) return null;
const node = pos.node;
const offset = pos.offset;
if (!node || node.nodeType !== Node.TEXT_NODE) return null;
const text = node.nodeValue;
if (!text) return null;
let s = offset;
let e = offset;
while (s > 0 && /[A-Za-z0-9_]/.test(text[s - 1])) s--;
while (e < text.length && /[A-Za-z0-9_]/.test(text[e])) e++;
if (s === e) return null;
const word = text.slice(s, e);
if (!nameSet.has(word)) return null;
const range = document.createRange();
try {
range.setStart(node, s);
range.setEnd(node, e);
} catch (_) { return null; }
const rect = range.getBoundingClientRect();
return { word, rect };
}
function caretFromPoint(x, y) {
if (document.caretPositionFromPoint) {
const p = document.caretPositionFromPoint(x, y);
return p ? { node: p.offsetNode, offset: p.offset } : null;
}
if (document.caretRangeFromPoint) {
const r = document.caretRangeFromPoint(x, y);
return r ? { node: r.startContainer, offset: r.startOffset } : null;
}
return null;
}
// ---------------------------------------------------------------------
// Wrap mode (optional): scan + listen on wrapped spans
// ---------------------------------------------------------------------
function scan(scope) {
if (!nameSet) return;
const root = resolveRoot(scope);
if (!root) return;
const skipNodes = (() => {
try { return new Set(root.querySelectorAll(cfg.skipSelector)); } catch (_) { return new Set(); }
})();
const walker = document.createTreeWalker(root, NodeFilter.SHOW_TEXT, {
acceptNode(node) {
const p = node.parentElement;
if (!p) return NodeFilter.FILTER_REJECT;
if (p.classList && p.classList.contains(cfg.wrapClass)) return NodeFilter.FILTER_REJECT;
for (let n = p; n && n !== root; n = n.parentElement) {
if (skipNodes.has(n)) return NodeFilter.FILTER_REJECT;
}
return NodeFilter.FILTER_ACCEPT;
},
});
const TOKEN = /[A-Za-z_][A-Za-z0-9_]*/g;
const todo = [];
let node;
while ((node = walker.nextNode())) {
const text = node.nodeValue;
if (!text || text.length < 3) continue;
let m, hits = null;
TOKEN.lastIndex = 0;
while ((m = TOKEN.exec(text)) !== null) {
if (nameSet.has(m[0])) {
(hits = hits || []).push({ start: m.index, end: m.index + m[0].length, name: m[0] });
}
}
if (hits) todo.push({ node, text, hits });
}
for (const { node, text, hits } of todo) {
const frag = document.createDocumentFragment();
let cursor = 0;
for (const h of hits) {
if (h.start > cursor) frag.appendChild(document.createTextNode(text.slice(cursor, h.start)));
const isType = typeSet.has(h.name);
const span = document.createElement('span');
// Both kinds keep `cfg.wrapClass` so the existing event handlers and
// detach paths still work. Types add a `simd-type` modifier class for
// distinct styling and are NOT tabbable -- intrinsics are the primary
// navigation target; types are reference info.
span.className = isType ? (cfg.wrapClass + ' simd-type') : cfg.wrapClass;
span.dataset.name = h.name;
if (!isType) span.tabIndex = 0;
span.textContent = h.name;
frag.appendChild(span);
cursor = h.end;
}
if (cursor < text.length) frag.appendChild(document.createTextNode(text.slice(cursor)));
node.parentNode.replaceChild(frag, node);
}
}
function onWrapEnter(ev) {
const el = closestWrapped(ev.target);
if (!el) return;
if (hideTimer) { clearTimeout(hideTimer); hideTimer = null; }
if (activeTarget === el) return;
activeTarget = el;
activeKey = 'wrap:' + el.dataset.name + ':' + (el._uid || (el._uid = ++_uidCounter));
showAtRect(el.dataset.name, el.getBoundingClientRect());
}
function onWrapKbFocusIn(ev) {
// Click-mode focus listener: only react if focus came from the keyboard
// (Tab navigation), not from a mousedown. :focus-visible matches when the
// browser thinks a focus indicator should be shown -- which, by spec,
// means keyboard or programmatic focus, not mouse focus.
const el = closestWrapped(ev.target);
if (!el) return;
let kb = false;
try { kb = !!(el.matches && el.matches(':focus-visible')); } catch (_) { kb = false; }
if (!kb) return;
onWrapEnter(ev);
}
function onWrapLeave(ev) {
const fromEl = closestWrapped(ev.target);
if (!fromEl) return;
if (ev.relatedTarget && activeTooltip && activeTooltip.contains(ev.relatedTarget)) return;
const toEl = ev.relatedTarget && closestWrapped(ev.relatedTarget);
if (toEl === fromEl) return;
scheduleHide();
}
function onWrapClick(ev) {
// Clicks inside the open tooltip should pass through so the user can
// toggle the <details> pseudocode block, click the docs link, etc.
if (activeTooltip && activeTooltip.contains(ev.target)) return;
const el = closestWrapped(ev.target);
if (!el) { hide(); return; }
ev.preventDefault();
if (activeTarget === el) hide();
else onWrapEnter(ev);
}
function closestWrapped(target) {
if (!target || !target.closest) return null;
return target.closest('.' + cfg.wrapClass);
}
let _uidCounter = 0;
// ---------------------------------------------------------------------
// Keyboard
// ---------------------------------------------------------------------
function onKeydown(ev) {
if (ev.key === 'Escape' && activeTooltip && activeTooltip.style.display !== 'none') {
hide();
if (activeTarget && activeTarget.focus) activeTarget.focus();
return;
}
// Click-mode keyboard equivalent: Enter or Space on a focused wrapped span.
if (cfg && cfg.wrap && cfg.on === 'click' && (ev.key === 'Enter' || ev.key === ' ')) {
const el = document.activeElement;
if (el && el.classList && el.classList.contains(cfg.wrapClass)) {
ev.preventDefault();
if (activeTarget === el) {
hide();
} else {
activeTarget = el;
activeKey = 'wrap:' + el.dataset.name + ':' + (el._uid || (el._uid = ++_uidCounter));
showAtRect(el.dataset.name, el.getBoundingClientRect());
}
}
}
}
// ---------------------------------------------------------------------
// Tooltip rendering and positioning
// ---------------------------------------------------------------------
async function showAtRect(name, rect) {
const tip = ensureTooltip();
// Pre-mark the tooltip as a type if we know it before the data loads, so
// the placeholder is already coloured correctly.
tip.classList.toggle('simd-tooltip--type', !!(typeSet && typeSet.has(name)));
tip.innerHTML = renderPlaceholder(name);
tip.style.visibility = 'hidden';
tip.style.display = 'block';
positionAtRect(tip, rect);
tip.style.visibility = 'visible';
try {
const recordsMap = await ensureRecords();
// Race check: the user may have moved on while data was loading.
if (activeKey == null) return;
const rec = recordsMap[name];
const ambig = ambiguous[name];
tip.classList.toggle('simd-tooltip--type', !!(rec && rec.kind === 'type'));
tip.innerHTML = renderTooltip(name, rec, ambig);
positionAtRect(tip, rect);
} catch (e) {
tip.innerHTML = renderError(name, e);
positionAtRect(tip, rect);
}
}
function scheduleHide() {
if (hideTimer) clearTimeout(hideTimer);
hideTimer = setTimeout(hide, 150);
}
function hide() {
if (hideTimer) { clearTimeout(hideTimer); hideTimer = null; }
if (activeTooltip) activeTooltip.style.display = 'none';
activeTarget = null;
activeKey = null;
removeHint();
}
function ensureTooltip() {
if (activeTooltip) return activeTooltip;
const tip = document.createElement('div');
tip.className = cfg.tooltipClass;
tip.setAttribute('role', 'tooltip');
document.body.appendChild(tip);
tip.addEventListener('mouseenter', () => { if (hideTimer) { clearTimeout(hideTimer); hideTimer = null; } });
tip.addEventListener('mouseleave', scheduleHide);
// Tab toggles inside the tooltip: click any header to open its body
// (closing the others). Click the active header again to close.
tip.addEventListener('click', (ev) => {
// dec/hex switch on the example panel: any click flips, regardless
// of which label was hit. Doesn't reposition.
const modeBtn = ev.target.closest('button.simd-tt-ex-mode[data-mode]');
if (modeBtn && tip.contains(modeBtn)) {
ev.preventDefault();
ev.stopPropagation();
const ex = modeBtn.closest('.simd-tt-ex');
if (ex) {
const isHex = ex.classList.toggle('hex');
for (const b of ex.querySelectorAll('button.simd-tt-ex-mode')) {
const active = (b.dataset.mode === 'hex') === isHex;
b.classList.toggle('is-active', active);
b.setAttribute('aria-pressed', active ? 'true' : 'false');
}
}
return;
}
// "+N more" expander on the variants list.
const moreBtn = ev.target.closest('button.simd-tt-vars-more');
if (moreBtn && tip.contains(moreBtn)) {
ev.preventDefault();
ev.stopPropagation();
const tail = moreBtn.previousElementSibling;
if (tail && tail.classList.contains('simd-tt-vars-tail')) tail.hidden = false;
moreBtn.remove();
if (activeTarget && activeTarget.getBoundingClientRect) {
positionAtRect(tip, activeTarget.getBoundingClientRect());
}
return;
}
const btn = ev.target.closest('button.simd-tt-tab[data-tab]');
if (!btn || !tip.contains(btn)) return;
ev.preventDefault();
ev.stopPropagation();
const id = btn.dataset.tab;
const wasActive = btn.getAttribute('aria-expanded') === 'true';
for (const b of tip.querySelectorAll('button.simd-tt-tab')) {
b.setAttribute('aria-expanded', 'false');
}
for (const body of tip.querySelectorAll('.simd-tt-tab-body')) {
body.hidden = true;
}
if (!wasActive) {
btn.setAttribute('aria-expanded', 'true');
const body = tip.querySelector('.simd-tt-tab-body[data-body="' + id + '"]');
if (body) body.hidden = false;
}
// Reposition since the tooltip's height likely changed.
if (activeTarget && activeTarget.getBoundingClientRect) {
positionAtRect(tip, activeTarget.getBoundingClientRect());
}
});
activeTooltip = tip;
return tip;
}
function repositionOrHide() {
if (!activeTooltip || activeTooltip.style.display === 'none') return;
// For wrap mode we have an actual target rect.
if (activeTarget && activeTarget.getBoundingClientRect) {
const r = activeTarget.getBoundingClientRect();
if (r.bottom < 0 || r.top > window.innerHeight) { hide(); return; }
positionAtRect(activeTooltip, r);
return;
}
// Lazy mode: cursor likely moved already; hide on scroll/resize.
hide();
}
function positionAtRect(tip, r) {
// Default placement: to the *right* of the trigger word, top-aligned.
// This keeps following lines of code visible (a tooltip below would cover
// them). Fall back to left-of when there's no horizontal room.
tip.style.left = '0px';
tip.style.top = '0px';
const maxW = Math.min(560, window.innerWidth - 24);
tip.style.maxWidth = maxW + 'px';
const tr = tip.getBoundingClientRect();
const margin = 8;
// Horizontal: prefer right-of, fall back to left-of, then clamp to viewport.
let left = r.right + margin;
if (left + tr.width + margin > window.innerWidth) {
const leftAlt = r.left - tr.width - margin;
if (leftAlt >= margin) {
left = leftAlt;
} else {
// No room either side -- pick whichever side has more space and clamp.
const spaceRight = window.innerWidth - r.right;
const spaceLeft = r.left;
left = spaceRight >= spaceLeft
? Math.max(margin, window.innerWidth - tr.width - margin)
: Math.max(margin, r.left - tr.width - margin);
}
}
// Vertical: top-align with the word; clamp inside viewport.
let top = r.top;
if (top + tr.height + margin > window.innerHeight) top = window.innerHeight - tr.height - margin;
if (top < margin) top = margin;
tip.style.left = Math.round(left + window.scrollX) + 'px';
tip.style.top = Math.round(top + window.scrollY) + 'px';
}
// ---------------------------------------------------------------------
// Compiler Explorer URL builder
//
// Generates a godbolt.org URL prefilled with a tiny C function that
// calls the intrinsic, with the right include + compiler flags for the
// ISA family. Pure function of `rec`. Returns null for SIMD types
// (a typedef has no asm to show) and for records we can't classify.
//
// godbolt's `clientstate` URL form: a base64-encoded JSON describing
// sessions / compilers / source. URL-safe base64, padding stripped.
// ---------------------------------------------------------------------
// Intel CPUID flag → clang feature switch. Records carry a list of
// CPUID flags (e.g. ['AVX512F', 'AVX512VL']); we union them.
const CE_INTEL_FLAGS = {
'MMX': '-mmmx', 'SSE': '-msse', 'SSE2': '-msse2', 'SSE3': '-msse3',
'SSSE3': '-mssse3', 'SSE4.1': '-msse4.1', 'SSE4.2': '-msse4.2',
'AVX': '-mavx', 'AVX2': '-mavx2',
'FMA': '-mfma', 'AES': '-maes', 'SHA': '-msha', 'SHA512': '-msha512',
'BMI1': '-mbmi', 'BMI2': '-mbmi2', 'POPCNT': '-mpopcnt',
'F16C': '-mf16c', 'GFNI': '-mgfni', 'VAES': '-mvaes',
'VPCLMULQDQ': '-mvpclmulqdq', 'PCLMULQDQ': '-mpclmul',
'AVX512F': '-mavx512f', 'AVX512VL': '-mavx512vl',
'AVX512BW': '-mavx512bw', 'AVX512DQ': '-mavx512dq',
'AVX512CD': '-mavx512cd', 'AVX512_BF16': '-mavx512bf16',
'AVX512_FP16': '-mavx512fp16', 'AVX512_VBMI': '-mavx512vbmi',
'AVX512_VBMI2': '-mavx512vbmi2', 'AVX512_VNNI': '-mavx512vnni',
'AVX512_BITALG': '-mavx512bitalg', 'AVX512VPOPCNTDQ': '-mavx512vpopcntdq',
'AVX512IFMA52': '-mavx512ifma', 'AVX512_VP2INTERSECT': '-mavx512vp2intersect',
'AVX_VNNI': '-mavxvnni', 'AVX_VNNI_INT8': '-mavxvnniint8',
'AVX_VNNI_INT16': '-mavxvnniint16', 'AVX_IFMA': '-mavxifma',
'AVX_NE_CONVERT': '-mavxneconvert',
};
// ARM ACLE SIMD_ISA → compiler + arch + headers list. Each ARM family
// rides on an architecture-specific clang on godbolt:
// aarch64: armv8-full-cclang-trunk (the "all architectural features" build,
// ships with FP16/BF16/i8mm/dotprod/crypto enabled).
// aarch32 / M-profile: armv7-cclang-trunk (we pick the M-profile via -march).
//
// Clang ships several ARM-related headers:
// arm_neon.h -- NEON vector ops (vaddq_*, vfmaq_*, …)
// arm_fp16.h -- scalar FP16 ops (vfmah_f16, vaddh_f16, …)
// arm_bf16.h -- scalar BF16 ops
// arm_sve.h -- SVE / SVE2 (sv*)
// arm_sme.h -- SME / SME2 (separate from arm_sve.h)
// arm_neon_sve_bridge.h -- NEON↔SVE conversions
// arm_mve.h -- Helium / MVE
//
// Including a header that's irrelevant to the current march is harmless --
// the header declares functions, which only fail when actually called.
// So we err on the generous side per family.
// Note on -march: the "full" clang has every feature pre-enabled, but
// passing -march=<base> resets to just what that base implies. So we
// re-enable +fp16/+bf16/+i8mm/+dotprod/+crypto explicitly on the aarch64
// marches to avoid "needs target feature fullfp16" errors on scalar FP16
// intrinsics like vfmah_f16.
const ARM_EXT = '+fp16+bf16+i8mm+dotprod+crypto';
const CE_ARM_ARCHS = {
'Neon': { compiler: 'armv8-full-cclang-trunk', march: 'armv8.6-a' + ARM_EXT, headers: ['arm_neon.h', 'arm_fp16.h', 'arm_bf16.h'] },
'SVE': { compiler: 'armv8-full-cclang-trunk', march: 'armv8.6-a+sve' + ARM_EXT, headers: ['arm_sve.h', 'arm_neon_sve_bridge.h'] },
'SVE2': { compiler: 'armv8-full-cclang-trunk', march: 'armv9-a' + ARM_EXT, headers: ['arm_sve.h', 'arm_neon_sve_bridge.h'] },
'SME and SME2': { compiler: 'armv8-full-cclang-trunk', march: 'armv9.2-a+sme2+sme-i16i64+sme-f64f64' + ARM_EXT, headers: ['arm_sve.h', 'arm_sme.h', 'arm_neon_sve_bridge.h'] },
'Helium': { compiler: 'armv7-cclang-trunk', march: 'armv8.1-m.main+mve.fp+fp.dp', headers: ['arm_mve.h', 'arm_fp16.h', 'arm_bf16.h'] },
};
function ceParseSignature(def) {
if (!def) return null;
// Collapse multi-line definitions (we pretty-print 3+ args).
const flat = def.replace(/\s+/g, ' ').trim();
const open = flat.indexOf('(');
const close = flat.lastIndexOf(')');
if (open < 0 || close < 0 || close < open) return null;
const head = flat.slice(0, open).trim();
const paramStr = flat.slice(open + 1, close).trim();
const headParts = head.split(/\s+/);
const name = headParts.pop();
const returnType = headParts.join(' ');
if (!paramStr || paramStr === 'void') {
return { returnType, name, params: 'void', argList: '' };
}
// Split on commas (no nested parens in any current intrinsic signature).
const params = paramStr.split(',').map(p => p.trim());
const argNames = params.map(p => {
// If the type contains `const int`, the parameter must be a compile-time
// constant -- substitute a literal 0 so the code compiles.
if (/\bconst\s+int\b/.test(p) && !/\*/.test(p)) return '0';
const m = p.match(/([A-Za-z_]\w*)\s*$/);
return m ? m[1] : '0';
});
return { returnType, name, params: paramStr, argList: argNames.join(', ') };
}
function ceBase64Url(str) {
const utf8 = unescape(encodeURIComponent(str));
return btoa(utf8).replace(/\+/g, '-').replace(/\//g, '_').replace(/=+$/, '');
}
// ARM family priority -- least-specific march wins so an intrinsic that's
// available in both SVE and SME contexts compiles with -march=...+sve, not
// the heavier SME march.
const CE_ARM_ARCH_ORDER = ['Neon', 'Helium', 'SVE', 'SVE2', 'SME and SME2'];
function ceConfigFor(rec) {
if (!rec || rec.kind === 'type') return null;
if (rec.source === 'arm-acle') {
const fset = new Set(rec.family || []);
for (const archKey of CE_ARM_ARCH_ORDER) {
if (fset.has(archKey)) {
const a = CE_ARM_ARCHS[archKey];
return {
compiler: a.compiler,
options: `-O2 -march=${a.march}`,
headers: a.headers,
};
}
}
return null;
}
if (rec.source === 'intel-iguide') {
const flags = [];
for (const f of rec.family || []) {
const flag = CE_INTEL_FLAGS[f];
if (flag && flags.indexOf(flag) < 0) flags.push(flag);
}
// Default fallback if we don't know the family flag.
if (flags.length === 0) flags.push('-mavx2');
return {
compiler: 'cclang_trunk',
options: '-O2 ' + flags.join(' '),
headers: ['immintrin.h'],
};
}
return null;
}
function compilerExplorerUrl(rec) {
const cfg = ceConfigFor(rec);
if (!cfg) return null;
const sig = ceParseSignature(rec.definition);
if (!sig) return null;
const includes = cfg.headers.map(h => `#include <${h}>`).join('\n');
const source =
`${includes}\n\n` +
`${sig.returnType} example(${sig.params}) {\n` +
` return ${sig.name}(${sig.argList});\n` +
`}\n`;
const state = {
sessions: [{
id: 1,
language: 'c',
source: source,
compilers: [{
id: cfg.compiler,
options: cfg.options,
libs: [],
filters: {
binary: false, commentOnly: true, demangle: true, directives: true,
execute: false, intel: true, labels: true, libraryCode: false, trim: true,
},
}],
}],
version: 4,
};
return 'https://godbolt.org/clientstate/' + ceBase64Url(JSON.stringify(state));
}
function renderPlaceholder(name) {
return `<div class="simd-tt-head"><code>${escapeHtml(name)}<\/code><\/div><div class="simd-tt-loading">loading…<\/div>`;
}
function renderError(name, err) {
return `<div class="simd-tt-head"><code>${escapeHtml(name)}<\/code><\/div><div class="simd-tt-error">${escapeHtml(String(err && err.message || err || 'load failed'))}<\/div>`;
}
// ex = { inputs: [{name, type, values}], output: {type, bytes_hex, values} }
// Render as a CSS grid so lane values line up vertically across rows.
// Each value cell carries both dec and hex spans; a dec/hex toggle in the
// top-right corner switches which one is visible (CSS-only).
function renderExample(ex) {
const inputs = ex.inputs || [];
const out = ex.output || {};
const outVals = Array.isArray(out.values) ? out.values : [out.values];
function laneInfo(typeName) {
if (!typeName) return { bits: null, kind: null };
// const int / const unsigned int -- immediate; treat as 32-bit so
// it still has a meaningful hex form.
if (/^const\s+(?:unsigned\s+)?int$/.test(typeName)) return { bits: 32, kind: 'int' };
// Allow zero or more `xN` segments so tuple types like
// int8x16x2_t / float32x4x3_t / poly16x4x4_t match too.
let m = typeName.match(/^(u?)int(8|16|32|64|128)(?:x\d+)*_t$/);
if (m) return { bits: +m[2], kind: m[1] ? 'uint' : 'int' };
m = typeName.match(/^poly(8|16|32|64|128)(?:x\d+)*_t$/);
if (m) return { bits: +m[1], kind: 'poly' };
m = typeName.match(/^bfloat(16)(?:x\d+)*_t$/);
if (m) return { bits: 16, kind: 'bfloat' };
m = typeName.match(/^(?:m?float)(8|16|32|64)(?:x\d+)*_t$/);
if (m) return { bits: +m[1], kind: 'float' };
return { bits: null, kind: null };
}
function hexFromValue(v, bits, kind) {
if (bits == null) return String(v);
const len = bits / 4;
if (kind === 'float' || kind === 'bfloat') {
const f = Number(v);
if (kind === 'bfloat') {
// bf16: top 16 bits of the float32 representation.
const buf = new ArrayBuffer(4);
new Float32Array(buf)[0] = f;
const u = new Uint32Array(buf)[0];
return ((u >>> 16) & 0xffff).toString(16).padStart(4, '0');
}
if (bits === 32) {
const buf = new ArrayBuffer(4);
new Float32Array(buf)[0] = f;
return new Uint32Array(buf)[0].toString(16).padStart(8, '0');
}
if (bits === 64) {
const buf = new ArrayBuffer(8);
new Float64Array(buf)[0] = f;
return new BigUint64Array(buf)[0].toString(16).padStart(16, '0');
}
if (bits === 16 && typeof Float16Array !== 'undefined') {
const buf = new ArrayBuffer(2);
new Float16Array(buf)[0] = f;
return new Uint16Array(buf)[0].toString(16).padStart(4, '0');
}
return String(v); // fp16 fallback if Float16Array unavailable
}
if (bits <= 32) {
const mask = bits === 32 ? 0xffffffff : ((1 << bits) - 1);
const u = (Number(v) & mask) >>> 0;
return u.toString(16).padStart(len, '0');
}
let n = typeof v === 'bigint' ? v : BigInt(v);
if (n < 0n) n = (1n << 64n) + n;
return n.toString(16).padStart(len, '0');
}
function hexFromBytes(bytesHex, laneIdx, bits) {
// bytes are little-endian; flip per-lane for display.
const lb = bits / 8;
const slice = bytesHex.slice(laneIdx * lb * 2, (laneIdx + 1) * lb * 2);
return slice.match(/.{1,2}/g).reverse().join('');
}
function tupleCount(typeName) {
const m = (typeName || '').match(/^[a-z]+\d+x(\d+)x[234]_t$/);
return m ? +m[1] : 0;