• Home
  • Features
  • Pricing
  • Docs
  • Announcements
  • Sign In

daisytuner / docc / 28567141617

01 Jul 2026 03:33PM UTC coverage: 62.12% (-0.01%) from 62.13%
28567141617

push

github

web-flow
Merge pull request #826 from daisytuner/adapt-cuda-search-space

Reject shared memory cpu pointer anywhere in a gpu kernel

12 of 22 new or added lines in 2 files covered. (54.55%)

3 existing lines in 1 file now uncovered.

39463 of 63527 relevant lines covered (62.12%)

978.55 hits per line

Source File
Press 'n' to go to next uncovered line, 'b' for previous

84.27
/opt/src/transformations/in_local_storage.cpp
1
#include "sdfg/transformations/in_local_storage.h"
2

3
#include <algorithm>
4
#include <cstddef>
5
#include <functional>
6
#include <string>
7

8
#include "sdfg/analysis/memory_layout_analysis.h"
9
#include "sdfg/analysis/users.h"
10
#include "sdfg/builder/structured_sdfg_builder.h"
11
#include "sdfg/data_flow/access_node.h"
12
#include "sdfg/data_flow/library_nodes/barrier_local_node.h"
13
#include "sdfg/data_flow/memlet.h"
14
#include "sdfg/passes/structured_control_flow/dead_cfg_elimination.h"
15
#include "sdfg/passes/structured_control_flow/sequence_fusion.h"
16
#include "sdfg/structured_control_flow/if_else.h"
17
#include "sdfg/structured_control_flow/sequence.h"
18
#include "sdfg/structured_control_flow/structured_loop.h"
19
#include "sdfg/symbolic/symbolic.h"
20
#include "sdfg/targets/gpu/gpu_schedule_type.h"
21
#include "sdfg/types/array.h"
22
#include "sdfg/types/pointer.h"
23
#include "sdfg/types/scalar.h"
24

25
namespace sdfg {
26
namespace transformations {
27

28
InLocalStorage::InLocalStorage(
29
    structured_control_flow::StructuredLoop& loop,
30
    const data_flow::AccessNode& access_node,
31
    const types::StorageType& storage_type
32
)
33
    : loop_(loop), access_node_(access_node), container_(access_node.data()), storage_type_(storage_type) {}
43✔
34

35
std::string InLocalStorage::name() const { return "InLocalStorage"; }
13✔
36

37
bool InLocalStorage::can_be_applied(builder::StructuredSDFGBuilder& builder, analysis::AnalysisManager& analysis_manager) {
39✔
38
    auto& sdfg = builder.subject();
39✔
39
    auto& body = this->loop_.root();
39✔
40

41
    tile_info_ = TileInfo{};
39✔
42

43
    // Criterion: Container must exist and is pointer
44
    if (!sdfg.exists(this->container_)) {
39✔
45
        return false;
×
46
    }
×
47
    auto& type = sdfg.type(this->container_);
39✔
48
    if (type.type_id() != types::TypeID::Pointer) {
39✔
49
        return false;
×
50
    }
×
51

52
    // Criterion: Container must be used in the loop body
53
    auto& users = analysis_manager.get<analysis::Users>();
39✔
54
    analysis::UsersView body_users(users, body);
39✔
55
    if (body_users.uses(this->container_).empty()) {
39✔
56
        return false;
2✔
57
    }
2✔
58

59
    // Criterion: Container must be read-only within the loop (no writes)
60
    if (!body_users.writes(this->container_).empty()) {
37✔
61
        return false;
1✔
62
    }
1✔
63

64
    // Criterion (GPU path): Loop must not be outermost (shared memory is per-block, not global)
65
    if (storage_type_.is_nv_shared()) {
36✔
66
        auto& loop_analysis = analysis_manager.get<analysis::LoopAnalysis>();
8✔
67
        if (loop_analysis.is_outermost_loop(&this->loop_)) {
8✔
68
            return false;
1✔
69
        }
1✔
70
    }
8✔
71

72
    // Use MemoryLayoutAnalysis tile group API
73
    // Find a representative memlet from the access node to identify its group.
74
    auto& mla = analysis_manager.get<analysis::MemoryLayoutAnalysis>();
35✔
75
    const analysis::MemoryTileGroup* group = nullptr;
35✔
76
    auto& dfg = access_node_.get_parent();
35✔
77
    for (auto& memlet : dfg.out_edges(access_node_)) {
35✔
78
        auto* candidate = mla.tile_group_for(loop_, memlet);
35✔
79
        if (!candidate) {
35✔
80
            continue;
×
81
        }
×
82

83
        auto extents = candidate->tile.extents_approx();
35✔
84
        if (extents.empty()) {
35✔
85
            continue;
×
86
        }
×
87

88
        // Reject candidates with any unbounded-dependent extent (returned as null).
89
        bool has_null = false;
35✔
90
        for (auto& ext : extents) {
62✔
91
            if (ext.is_null()) {
62✔
92
                has_null = true;
×
93
                break;
×
94
            }
×
95
        }
62✔
96
        if (has_null) {
35✔
97
            continue;
×
98
        }
×
99

100
        // GPU path: accept first valid group (substitution happens later)
101
        if (storage_type_.is_nv_shared()) {
35✔
102
            group = candidate;
7✔
103
            break;
7✔
104
        }
7✔
105

106
        // CPU path: require provably integer extents
107
        bool all_integer = true;
28✔
108
        for (auto& ext : extents) {
49✔
109
            if (!SymEngine::is_a<SymEngine::Integer>(*ext)) {
49✔
110
                all_integer = false;
1✔
111
                break;
1✔
112
            }
1✔
113
        }
49✔
114
        if (all_integer) {
28✔
115
            group = candidate;
27✔
116
            break;
27✔
117
        }
27✔
118
    }
28✔
119
    if (!group) {
35✔
120
        return false;
1✔
121
    }
1✔
122

123
    auto& tile = group->tile;
34✔
124
    auto extents = tile.extents_approx();
34✔
125

126
    // Store group memlets for use in apply()
127
    group_memlets_.clear();
34✔
128
    group_memlets_.insert(group->memlets.begin(), group->memlets.end());
34✔
129

130
    // Store tile info (before substitution, bases/strides stay symbolic)
131
    tile_info_.dimensions = extents;
34✔
132
    tile_info_.bases = tile.min_subset;
34✔
133
    tile_info_.strides = std::vector<symbolic::Expression>(tile.layout.strides().begin(), tile.layout.strides().end());
34✔
134
    tile_info_.offset = tile.layout.offset();
34✔
135

136
    // GPU shared memory: resolve symbolic extents using GPU block sizes and
137
    // require at least one cooperative dimension
138
    if (storage_type_.is_nv_shared()) {
34✔
139
        auto ancestors = ControlFlowNode::parent_chain(loop_);
7✔
140

141
        // Build substitution map: symbolic GPU map bounds → integer block sizes
142
        // E.g., Map condition "i < N" with block_size=32 → N=32
143
        for (auto* node : ancestors) {
37✔
144
            if (auto* ancestor_map = dynamic_cast<structured_control_flow::Map*>(node)) {
37✔
145
                if (!gpu::is_gpu_schedule(ancestor_map->schedule_type())) {
13✔
146
                    continue;
×
147
                }
×
148
                auto block_size = gpu::gpu_block_size(ancestor_map->schedule_type());
13✔
149
                // Extract symbolic bound from condition: Lt(indvar, BOUND)
150
                auto condition = ancestor_map->condition();
13✔
151
                if (SymEngine::is_a<SymEngine::StrictLessThan>(*condition)) {
13✔
152
                    auto stl = SymEngine::rcp_static_cast<const SymEngine::StrictLessThan>(condition);
13✔
153
                    auto rhs = stl->get_args()[1];
13✔
154
                    auto iter_count = symbolic::sub(rhs, ancestor_map->init());
13✔
155
                    if (!SymEngine::is_a<SymEngine::Integer>(*iter_count)) {
13✔
156
                        // Symbolic bound — substitute with block size in extents and bases
157
                        for (auto& ext : tile_info_.dimensions) {
16✔
158
                            ext = symbolic::simplify(symbolic::subs(ext, iter_count, block_size));
16✔
159
                        }
16✔
160
                        for (auto& base : tile_info_.bases) {
16✔
161
                            base = symbolic::simplify(symbolic::subs(base, iter_count, block_size));
16✔
162
                        }
16✔
163
                    }
9✔
164
                }
13✔
165
            }
13✔
166
        }
37✔
167

168
        // Also resolve the loop's own bound if symbolic and matches a block size
169
        // E.g., For k = 0..K where K is a parameter — check if K can be resolved
170
        // from any GPU ancestor map
171
        // (Already handled above: if K appears as a GPU map bound, it's substituted)
172

173
        // Criterion: All extents must now be provably integer
174
        for (auto& ext : tile_info_.dimensions) {
13✔
175
            if (!SymEngine::is_a<SymEngine::Integer>(*ext)) {
13✔
176
                return false;
2✔
177
            }
2✔
178
        }
13✔
179

180
        // Criterion: At least one cooperative dimension
181
        bool has_cooperative_dim = false;
5✔
182
        for (auto* node : ancestors) {
16✔
183
            if (auto* ancestor_map = dynamic_cast<structured_control_flow::Map*>(node)) {
16✔
184
                if (!gpu::is_gpu_schedule(ancestor_map->schedule_type())) {
6✔
185
                    continue;
×
186
                }
×
187
                // A GPU dim is cooperative if its indvar does NOT appear in any tile base
188
                bool appears_in_bases = false;
6✔
189
                for (auto& base : tile_info_.bases) {
10✔
190
                    if (symbolic::uses(base, ancestor_map->indvar())) {
10✔
191
                        appears_in_bases = true;
1✔
192
                        break;
1✔
193
                    }
1✔
194
                }
10✔
195
                if (!appears_in_bases) {
6✔
196
                    has_cooperative_dim = true;
5✔
197
                    break;
5✔
198
                }
5✔
199
            }
6✔
200
        }
16✔
201
        if (!has_cooperative_dim) {
5✔
202
            return false;
×
203
        }
×
204
    } else {
27✔
205
        // CPU_Stack must not be applied when the loop itself is a
206
        // GPU-scheduled map at the kernel boundary (no GPU-scheduled ancestors).
207
        // In that case the init/writeback copies would be placed on the host
208
        // while the compute runs on the device.
209
        if (auto* self_map = dynamic_cast<structured_control_flow::Map*>(&loop_)) {
27✔
210
            if (gpu::is_gpu_schedule(self_map->schedule_type())) {
3✔
211
                auto ancestors = ControlFlowNode::parent_chain(loop_);
2✔
212
                bool has_gpu_ancestor = false;
2✔
213
                for (auto* node : ancestors) {
4✔
214
                    if (auto* ancestor_map = dynamic_cast<structured_control_flow::Map*>(node)) {
4✔
NEW
215
                        if (gpu::is_gpu_schedule(ancestor_map->schedule_type())) {
×
NEW
216
                            has_gpu_ancestor = true;
×
NEW
217
                            break;
×
NEW
218
                        }
×
NEW
219
                    }
×
220
                }
4✔
221
                if (!has_gpu_ancestor) {
2✔
222
                    return false;
2✔
223
                }
2✔
224
            }
2✔
225
        }
3✔
226

227
        // CPU_Stack inside a GPU region is only valid for per-thread locals
228
        // (all GPU map indvars appear in the tile bases). If there is a
229
        // cooperative dimension (a GPU indvar NOT in the bases), the buffer
230
        // must be NV_Shared so all threads in the block can see each other's reads.
231
        auto ancestors = ControlFlowNode::parent_chain(loop_);
25✔
232
        for (auto* node : ancestors) {
105✔
233
            if (auto* ancestor_map = dynamic_cast<structured_control_flow::Map*>(node)) {
105✔
234
                if (!gpu::is_gpu_schedule(ancestor_map->schedule_type())) {
×
235
                    continue;
×
236
                }
×
237
                bool appears_in_bases = false;
×
238
                for (auto& base : tile_info_.bases) {
×
239
                    if (symbolic::uses(base, ancestor_map->indvar())) {
×
240
                        appears_in_bases = true;
×
241
                        break;
×
242
                    }
×
243
                }
×
244
                if (!appears_in_bases) {
×
245
                    // Cooperative dimension detected with CPU_Stack — invalid.
246
                    // The buffer requires NV_Shared for cross-thread visibility.
247
                    return false;
×
248
                }
×
249
            }
×
250
        }
105✔
251
    }
25✔
252

253
    return true;
30✔
254
}
34✔
255

256
void InLocalStorage::apply(builder::StructuredSDFGBuilder& builder, analysis::AnalysisManager& analysis_manager) {
23✔
257
    auto& sdfg = builder.subject();
23✔
258

259
    auto parent_node = loop_.get_parent();
23✔
260
    auto parent = dynamic_cast<structured_control_flow::Sequence*>(parent_node);
23✔
261
    if (!parent) {
23✔
262
        throw InvalidSDFGException("InLocalStorage: Parent of loop must be a Sequence!");
×
263
    }
×
264

265
    // We replace all relevant memlets with flat local indices
266
    // Thus, we now use a flat pointer to index into container
267
    // Remark: sdfg.type may return an opaque pointer, so use
268
    //         memlet instead
269
    auto* memlet = *group_memlets_.begin();
23✔
270
    types::Scalar scalar_type(memlet->base_type().primitive_type());
23✔
271
    types::Pointer pointer_type(scalar_type);
23✔
272

273
    // Create local buffer name
274
    local_name_ = builder.find_new_name("__daisy_in_local_storage_" + this->container_);
23✔
275

276
    // Collect varying dimensions (extent > 1) and their sizes
277
    std::vector<size_t> varying_dims;
23✔
278
    std::vector<symbolic::Expression> varying_dim_sizes;
23✔
279
    for (size_t d = 0; d < tile_info_.dimensions.size(); d++) {
64✔
280
        auto& dim_size = tile_info_.dimensions.at(d);
41✔
281
        if (!symbolic::eq(dim_size, symbolic::integer(1))) {
41✔
282
            varying_dims.push_back(d);
32✔
283
            varying_dim_sizes.push_back(dim_size);
32✔
284
        }
32✔
285
    }
41✔
286

287
    // GPU classification: each ancestor GPU Map is either
288
    //  - per-thread (its Map indvar appears in tile.bases — each thread sees a
289
    //    distinct slice along that dim, so the shared buffer gets its own
290
    //    per-thread slot indexed by the within-block thread_idx), or
291
    //  - cooperative (Map indvar not in bases — all threads along that dim
292
    //    cooperatively load the same shared tile, strided by thread_idx).
293
    struct GpuDim {
23✔
294
        gpu::GPUDimension dim;
23✔
295
        symbolic::Symbol map_indvar; // global thread index (== thread_idx + blockIdx * blockDim)
23✔
296
        symbolic::Symbol thread_idx; // within-block thread index (NV_Symbol)
23✔
297
        symbolic::Integer block_size;
23✔
298
        bool is_per_thread;
23✔
299
    };
23✔
300
    std::vector<GpuDim> per_thread_dims; // populated only on GPU path
23✔
301
    std::vector<GpuDim> coop_dims; // populated only on GPU path
23✔
302
    bool is_rocm = false;
23✔
303

304
    if (storage_type_.is_nv_shared()) {
23✔
305
        auto ancestors = ControlFlowNode::parent_chain(loop_);
5✔
306
        for (auto* node : ancestors) {
29✔
307
            auto* m = dynamic_cast<structured_control_flow::Map*>(node);
29✔
308
            if (!m || !gpu::is_gpu_schedule(m->schedule_type())) continue;
29✔
309
            if (m->schedule_type().value() == "ROCM") {
10✔
310
                is_rocm = true;
×
311
                break;
×
312
            }
×
313
        }
10✔
314
        const std::string prefix = is_rocm ? "__daisy_hip_thread_idx_" : "__daisy_cuda_thread_idx_";
5✔
315
        auto suffix = [](gpu::GPUDimension d) -> std::string {
10✔
316
            switch (d) {
10✔
317
                case gpu::GPUDimension::X:
5✔
318
                    return "x";
5✔
319
                case gpu::GPUDimension::Y:
5✔
320
                    return "y";
5✔
321
                case gpu::GPUDimension::Z:
×
322
                    return "z";
×
323
            }
10✔
324
            return "?";
×
325
        };
10✔
326
        for (auto* node : ancestors) {
29✔
327
            auto* m = dynamic_cast<structured_control_flow::Map*>(node);
29✔
328
            if (!m || !gpu::is_gpu_schedule(m->schedule_type())) continue;
29✔
329
            GpuDim gd;
10✔
330
            gd.dim = gpu::gpu_dimension(m->schedule_type());
10✔
331
            gd.map_indvar = m->indvar();
10✔
332
            gd.thread_idx = symbolic::symbol(prefix + suffix(gd.dim));
10✔
333
            gd.block_size = gpu::gpu_block_size(m->schedule_type());
10✔
334
            gd.is_per_thread = false;
10✔
335
            for (auto& base : tile_info_.bases) {
15✔
336
                if (symbolic::uses(base, m->indvar())) {
15✔
337
                    gd.is_per_thread = true;
4✔
338
                    break;
4✔
339
                }
4✔
340
            }
15✔
341
            (gd.is_per_thread ? per_thread_dims : coop_dims).push_back(gd);
10✔
342
        }
10✔
343
        auto by_dim = [](const GpuDim& a, const GpuDim& b) {
5✔
344
            return static_cast<int>(a.dim) < static_cast<int>(b.dim);
1✔
345
        };
1✔
346
        std::sort(per_thread_dims.begin(), per_thread_dims.end(), by_dim);
5✔
347
        std::sort(coop_dims.begin(), coop_dims.end(), by_dim);
5✔
348

349
        // Ensure within-block thread_idx containers exist. Codegen recognises
350
        // NV_Symbol-typed scalars and substitutes them with threadIdx.{x,y,z}
351
        // (CUDA) or the ROCm equivalent at emission time.
352
        auto ensure_idx = [&](const symbolic::Symbol& sym) {
10✔
353
            if (!sdfg.exists(sym->get_name())) {
10✔
354
                types::Scalar idx_type(types::PrimitiveType::Int32);
8✔
355
                idx_type.storage_type(types::StorageType::NV_Symbol());
8✔
356
                builder.add_container(sym->get_name(), idx_type);
8✔
357
            }
8✔
358
        };
10✔
359
        for (auto& gd : per_thread_dims) ensure_idx(gd.thread_idx);
5✔
360
        for (auto& gd : coop_dims) ensure_idx(gd.thread_idx);
6✔
361
    }
5✔
362

363
    // Buffer dim sizes: [per-thread block sizes (X, Y, Z canonical order)] ++
364
    //                   [varying tile dim sizes (original access-dim order)]
365
    std::vector<symbolic::Expression> buf_dim_sizes;
23✔
366
    for (auto& gd : per_thread_dims) buf_dim_sizes.push_back(gd.block_size);
23✔
367
    for (auto& s : varying_dim_sizes) buf_dim_sizes.push_back(s);
32✔
368

369
    // Total buffer size (number of scalar slots)
370
    symbolic::Expression total_size = symbolic::integer(1);
23✔
371
    for (auto& s : buf_dim_sizes) total_size = symbolic::mul(total_size, s);
36✔
372

373
    // Per-thread index prefix (each thread's fixed buffer coords)
374
    std::vector<symbolic::Expression> per_thread_indices;
23✔
375
    for (auto& gd : per_thread_dims) per_thread_indices.push_back(gd.thread_idx);
23✔
376

377
    // Row-major linearization over buf_dim_sizes (leftmost dim = outermost stride)
378
    auto linearize_exprs = [&](const std::vector<symbolic::Expression>& indices) -> symbolic::Expression {
50✔
379
        symbolic::Expression linear_idx = symbolic::integer(0);
50✔
380
        symbolic::Expression stride = symbolic::integer(1);
50✔
381
        for (int i = static_cast<int>(indices.size()) - 1; i >= 0; i--) {
130✔
382
            linear_idx = symbolic::add(linear_idx, symbolic::mul(indices[i], stride));
80✔
383
            stride = symbolic::mul(stride, buf_dim_sizes[i]);
80✔
384
        }
80✔
385
        return linear_idx;
50✔
386
    };
50✔
387

388
    // Helper: build linearized local index from per-dimension indvars (symbols)
389
    auto linearize = [&](const std::vector<symbolic::Symbol>& indvars) -> symbolic::Expression {
23✔
390
        std::vector<symbolic::Expression> exprs(indvars.begin(), indvars.end());
18✔
391
        return linearize_exprs(exprs);
18✔
392
    };
18✔
393

394
    // Helper: build source subset (base[d] + copy_indvar[d]) for original container
395
    auto build_original_subset = [&](const std::vector<symbolic::Expression>& copy_indices) -> data_flow::Subset {
23✔
396
        std::vector<symbolic::Expression> full_indices;
23✔
397
        size_t var_idx = 0;
23✔
398
        for (size_t d = 0; d < tile_info_.dimensions.size(); d++) {
64✔
399
            if (!symbolic::eq(tile_info_.dimensions.at(d), symbolic::integer(1))) {
41✔
400
                full_indices.push_back(symbolic::add(tile_info_.bases.at(d), copy_indices.at(var_idx++)));
32✔
401
            } else {
32✔
402
                full_indices.push_back(tile_info_.bases.at(d));
9✔
403
            }
9✔
404
        }
41✔
405

406
        symbolic::Expression linear = tile_info_.offset;
23✔
407
        for (size_t d = 0; d < full_indices.size(); d++) {
64✔
408
            linear = symbolic::add(linear, symbolic::mul(tile_info_.strides.at(d), full_indices.at(d)));
41✔
409
        }
41✔
410
        return {linear};
23✔
411
    };
23✔
412

413
    // ==================================================================
414
    // Branch: GPU cooperative path vs CPU sequential path
415
    // ==================================================================
416
    if (storage_type_.is_nv_shared()) {
23✔
417
        // ============================================================
418
        // GPU COOPERATIVE PATH
419
        // ============================================================
420
        // Each thread owns a fixed slot along per-thread buffer dims and
421
        // strides through the varying-flat range with the other threads
422
        // sharing that slot (i.e. threads in cooperative dims only).
423

424
        // Total cooperative-thread count (= 1 if no cooperative dims)
425
        symbolic::Expression total_coop_threads = symbolic::integer(1);
5✔
426
        for (auto& cd : coop_dims) {
6✔
427
            total_coop_threads = symbolic::mul(total_coop_threads, cd.block_size);
6✔
428
        }
6✔
429

430
        // Flat within-block index over cooperative dims only (= 0 if none).
431
        // Row-major: X is least-significant when present.
432
        symbolic::Expression coop_flat = symbolic::integer(0);
5✔
433
        {
5✔
434
            symbolic::Expression stride = symbolic::integer(1);
5✔
435
            for (auto it = coop_dims.rbegin(); it != coop_dims.rend(); ++it) {
11✔
436
                coop_flat = symbolic::add(coop_flat, symbolic::mul(it->thread_idx, stride));
6✔
437
                stride = symbolic::mul(stride, it->block_size);
6✔
438
            }
6✔
439
        }
5✔
440

441
        // Varying-flat size = product of tile dim extents (excluding extent==1).
442
        // This is the address range each thread cooperatively walks within its
443
        // per-thread slot.
444
        symbolic::Expression varying_flat_size = symbolic::integer(1);
5✔
445
        for (auto& s : varying_dim_sizes) {
7✔
446
            varying_flat_size = symbolic::mul(varying_flat_size, s);
7✔
447
        }
7✔
448

449
        // Create the local buffer with NV_Shared storage
450
        types::Array buffer_type(storage_type_, 0, {}, scalar_type, total_size);
5✔
451
        builder.add_container(local_name_, buffer_type);
5✔
452

453
        // Emit: barrier → cooperative copy loop → barrier → main loop
454
        // 1. Barrier before copy
455
        auto& barrier_block1 = builder.add_block_before(*parent, loop_, {}, loop_.debug_info());
5✔
456
        builder.add_library_node<data_flow::BarrierLocalNode>(barrier_block1, {});
5✔
457

458
        // 2. Cooperative copy: for (idx = coop_flat; idx < varying_flat_size; idx += total_coop_threads)
459
        auto idx_name = builder.find_new_name("__daisy_ils_coop_" + this->container_);
5✔
460
        types::Scalar idx_type(types::PrimitiveType::UInt64);
5✔
461
        builder.add_container(idx_name, idx_type);
5✔
462
        auto idx_var = symbolic::symbol(idx_name);
5✔
463

464
        auto& copy_loop = builder.add_map_before(
5✔
465
            *parent,
5✔
466
            loop_,
5✔
467
            idx_var,
5✔
468
            symbolic::Lt(idx_var, varying_flat_size),
5✔
469
            coop_flat,
5✔
470
            symbolic::add(idx_var, total_coop_threads),
5✔
471
            structured_control_flow::ScheduleType_Sequential::create(),
5✔
472
            {},
5✔
473
            loop_.debug_info()
5✔
474
        );
5✔
475

476
        auto& copy_scope = copy_loop.root();
5✔
477
        auto& copy_block = builder.add_block(copy_scope);
5✔
478
        auto& copy_src = builder.add_access(copy_block, this->container_);
5✔
479
        auto& copy_dst = builder.add_access(copy_block, local_name_);
5✔
480
        auto& copy_tasklet = builder.add_tasklet(copy_block, data_flow::TaskletCode::assign, "_out", {"_in"});
5✔
481

482
        // Decompose idx_var into per-varying-dim indices (row-major).
483
        // For a single varying dim this is just idx_var.
484
        std::vector<symbolic::Expression> varying_decomp;
5✔
485
        symbolic::Expression remainder = idx_var;
5✔
486
        for (size_t i = 0; i < varying_dim_sizes.size(); i++) {
12✔
487
            if (i + 1 < varying_dim_sizes.size()) {
7✔
488
                symbolic::Expression divisor = symbolic::integer(1);
2✔
489
                for (size_t j = i + 1; j < varying_dim_sizes.size(); j++) {
4✔
490
                    divisor = symbolic::mul(divisor, varying_dim_sizes[j]);
2✔
491
                }
2✔
492
                varying_decomp.push_back(symbolic::div(remainder, divisor));
2✔
493
                remainder = symbolic::mod(remainder, divisor);
2✔
494
            } else {
5✔
495
                varying_decomp.push_back(remainder);
5✔
496
            }
5✔
497
        }
7✔
498

499
        // Source = original container at (bases — which already use the global
500
        // Map indvars — plus the varying decomposition along each varying dim).
501
        auto copy_src_subset = build_original_subset(varying_decomp);
5✔
502

503
        // Destination = buffer at (per_thread_indices ++ varying_decomp) linearized.
504
        std::vector<symbolic::Expression> dest_indices = per_thread_indices;
5✔
505
        for (auto& v : varying_decomp) dest_indices.push_back(v);
7✔
506
        data_flow::Subset copy_dst_subset = {linearize_exprs(dest_indices)};
5✔
507

508
        builder.add_computational_memlet(copy_block, copy_src, copy_tasklet, "_in", copy_src_subset, pointer_type);
5✔
509
        builder.add_computational_memlet(copy_block, copy_tasklet, "_out", copy_dst, copy_dst_subset, buffer_type);
5✔
510

511
        // 3. Barrier after copy
512
        auto& barrier_block2 = builder.add_block_before(*parent, loop_, {}, loop_.debug_info());
5✔
513
        builder.add_library_node<data_flow::BarrierLocalNode>(barrier_block2, {});
5✔
514
    } else {
18✔
515
        // ============================================================
516
        // CPU SEQUENTIAL PATH
517
        // ============================================================
518
        // Create the local buffer with specified storage type
519
        types::Array buffer_type(storage_type_, 0, {}, scalar_type, total_size);
18✔
520
        builder.add_container(local_name_, buffer_type);
18✔
521

522
        std::vector<symbolic::Symbol> copy_indvars;
18✔
523
        structured_control_flow::Sequence* copy_scope =
18✔
524
            &builder.add_sequence_before(*parent, loop_, {}, loop_.debug_info());
18✔
525
        for (size_t i = 0; i < varying_dims.size(); i++) {
43✔
526
            size_t d = varying_dims[i];
25✔
527
            auto indvar_name = builder.find_new_name("__daisy_ils_" + this->container_ + "_d" + std::to_string(d));
25✔
528
            types::Scalar indvar_type(types::PrimitiveType::UInt64);
25✔
529
            builder.add_container(indvar_name, indvar_type);
25✔
530
            auto indvar = symbolic::symbol(indvar_name);
25✔
531
            copy_indvars.push_back(indvar);
25✔
532

533
            auto init = symbolic::integer(0);
25✔
534
            auto condition = symbolic::Lt(indvar, varying_dim_sizes[i]);
25✔
535
            auto update = symbolic::add(indvar, symbolic::integer(1));
25✔
536

537
            auto& copy_loop = builder.add_map(
25✔
538
                *copy_scope,
25✔
539
                indvar,
25✔
540
                condition,
25✔
541
                init,
25✔
542
                update,
25✔
543
                structured_control_flow::ScheduleType_Sequential::create(),
25✔
544
                {},
25✔
545
                loop_.debug_info()
25✔
546
            );
25✔
547
            copy_scope = &copy_loop.root();
25✔
548
        }
25✔
549

550
        // Create copy block
551
        auto& copy_block = builder.add_block(*copy_scope);
18✔
552
        auto& copy_src = builder.add_access(copy_block, this->container_);
18✔
553
        auto& copy_dst = builder.add_access(copy_block, local_name_);
18✔
554
        auto& copy_tasklet = builder.add_tasklet(copy_block, data_flow::TaskletCode::assign, "_out", {"_in"});
18✔
555

556
        std::vector<symbolic::Expression> copy_exprs(copy_indvars.begin(), copy_indvars.end());
18✔
557
        auto copy_src_subset = build_original_subset(copy_exprs);
18✔
558
        data_flow::Subset copy_dst_subset = {linearize(copy_indvars)};
18✔
559

560
        builder.add_computational_memlet(copy_block, copy_src, copy_tasklet, "_in", copy_src_subset, pointer_type);
18✔
561
        types::Array buffer_type_ref(storage_type_, 0, {}, scalar_type, total_size);
18✔
562
        builder.add_computational_memlet(copy_block, copy_tasklet, "_out", copy_dst, copy_dst_subset, buffer_type_ref);
18✔
563
    }
18✔
564

565
    // ==================================================================
566
    // Update accesses in the main loop to use the local buffer
567
    // ==================================================================
568
    types::Array buffer_type(storage_type_, 0, {}, scalar_type, total_size);
23✔
569
    auto& mla = analysis_manager.get<analysis::MemoryLayoutAnalysis>();
23✔
570

571
    // Recursive helper to traverse all blocks in the loop body
572
    std::function<void(structured_control_flow::ControlFlowNode&)> rewrite_accesses;
23✔
573
    rewrite_accesses = [&](structured_control_flow::ControlFlowNode& node) {
93✔
574
        if (auto* block = dynamic_cast<structured_control_flow::Block*>(&node)) {
93✔
575
            auto& dfg = block->dataflow();
34✔
576

577
            // Collect access nodes to process (avoid iterator invalidation)
578
            std::vector<data_flow::AccessNode*> access_nodes;
34✔
579
            for (auto* access_node : dfg.data_nodes()) {
99✔
580
                if (access_node->data() == this->container_) {
99✔
581
                    access_nodes.push_back(access_node);
28✔
582
                }
28✔
583
            }
99✔
584

585
            for (auto* access : access_nodes) {
34✔
586
                // Classify memlets: group vs non-group
587
                struct MemletRewrite {
28✔
588
                    data_flow::Memlet* memlet;
28✔
589
                    data_flow::Subset local_subset;
28✔
590
                    bool is_outgoing;
28✔
591
                };
28✔
592
                std::vector<MemletRewrite> group_rewrites;
28✔
593
                bool all_in_group = true;
28✔
594

595
                for (auto& memlet : dfg.out_edges(*access)) {
29✔
596
                    if (group_memlets_.count(&memlet) == 0) {
29✔
597
                        all_in_group = false;
2✔
598
                        continue;
2✔
599
                    }
2✔
600
                    auto* acc = mla.access(memlet);
27✔
601
                    if (acc && acc->subset.size() == tile_info_.dimensions.size()) {
27✔
602
                        // Buffer index: [per-thread thread_idx (X,Y,Z order)] ++ [varying d: subset[d] - base[d]]
603
                        std::vector<symbolic::Expression> local_indices = per_thread_indices;
27✔
604
                        for (size_t d = 0; d < tile_info_.dimensions.size(); d++) {
76✔
605
                            if (!symbolic::eq(tile_info_.dimensions.at(d), symbolic::integer(1))) {
49✔
606
                                local_indices.push_back(symbolic::sub(acc->subset.at(d), tile_info_.bases.at(d)));
40✔
607
                            }
40✔
608
                        }
49✔
609
                        symbolic::Expression linear_idx = linearize_exprs(local_indices);
27✔
610
                        group_rewrites.push_back({&memlet, {linear_idx}, true});
27✔
611
                    }
27✔
612
                }
27✔
613
                for (auto& memlet : dfg.in_edges(*access)) {
28✔
614
                    if (group_memlets_.count(&memlet) == 0) {
×
615
                        all_in_group = false;
×
616
                        continue;
×
617
                    }
×
618
                    auto* acc = mla.access(memlet);
×
619
                    if (acc && acc->subset.size() == tile_info_.dimensions.size()) {
×
620
                        // Buffer index: [per-thread thread_idx (X,Y,Z order)] ++ [varying d: subset[d] - base[d]]
621
                        std::vector<symbolic::Expression> local_indices = per_thread_indices;
×
622
                        for (size_t d = 0; d < tile_info_.dimensions.size(); d++) {
×
623
                            if (!symbolic::eq(tile_info_.dimensions.at(d), symbolic::integer(1))) {
×
624
                                local_indices.push_back(symbolic::sub(acc->subset.at(d), tile_info_.bases.at(d)));
×
625
                            }
×
626
                        }
×
627
                        symbolic::Expression linear_idx = linearize_exprs(local_indices);
×
628
                        group_rewrites.push_back({&memlet, {linear_idx}, false});
×
629
                    }
×
630
                }
×
631

632
                if (group_rewrites.empty()) continue;
28✔
633

634
                if (all_in_group) {
27✔
635
                    // Simple case: all memlets in group → rewrite in-place and rename
636
                    for (auto& rw : group_rewrites) {
26✔
637
                        rw.memlet->set_subset(rw.local_subset);
26✔
638
                        rw.memlet->set_base_type(buffer_type);
26✔
639
                    }
26✔
640
                    access->data(local_name_);
26✔
641
                } else {
26✔
642
                    // Mixed case: split — create new local access node, redirect group memlets
643
                    auto& local_access = builder.add_access(*block, local_name_);
1✔
644
                    for (auto& rw : group_rewrites) {
1✔
645
                        if (rw.is_outgoing) {
1✔
646
                            // outgoing: access→tasklet  →  local_access→tasklet
647
                            auto& dst_node = rw.memlet->dst();
1✔
648
                            auto dst_conn = rw.memlet->dst_conn();
1✔
649
                            builder.remove_memlet(*block, *rw.memlet);
1✔
650
                            builder.add_memlet(
1✔
651
                                *block, local_access, "void", dst_node, dst_conn, rw.local_subset, buffer_type, {}
1✔
652
                            );
1✔
653
                        } else {
1✔
654
                            // incoming: tasklet→access  →  tasklet→local_access
655
                            auto& src_node = rw.memlet->src();
×
656
                            auto src_conn = rw.memlet->src_conn();
×
657
                            builder.remove_memlet(*block, *rw.memlet);
×
658
                            builder.add_memlet(
×
659
                                *block, src_node, src_conn, local_access, "void", rw.local_subset, buffer_type, {}
×
660
                            );
×
661
                        }
×
662
                    }
1✔
663
                }
1✔
664
            }
27✔
665
        } else if (auto* seq = dynamic_cast<structured_control_flow::Sequence*>(&node)) {
59✔
666
            for (size_t i = 0; i < seq->size(); i++) {
93✔
667
                rewrite_accesses(seq->at(i).first);
52✔
668
            }
52✔
669
        } else if (auto* loop = dynamic_cast<structured_control_flow::StructuredLoop*>(&node)) {
41✔
670
            rewrite_accesses(loop->root());
18✔
671
        } else if (auto* if_else = dynamic_cast<structured_control_flow::IfElse*>(&node)) {
18✔
672
            for (size_t i = 0; i < if_else->size(); i++) {
×
673
                rewrite_accesses(if_else->at(i).first);
×
674
            }
×
675
        }
×
676
    };
93✔
677
    rewrite_accesses(loop_.root());
23✔
678

679
    // Cleanup
680
    analysis_manager.invalidate_all();
23✔
681

682
    passes::SequenceFusion sf_pass;
23✔
683
    passes::DeadCFGElimination dce_pass;
23✔
684
    bool applies = false;
23✔
685
    do {
41✔
686
        applies = false;
41✔
687
        applies |= dce_pass.run(builder, analysis_manager);
41✔
688
        applies |= sf_pass.run(builder, analysis_manager);
41✔
689
    } while (applies);
41✔
690
}
23✔
691

692
void InLocalStorage::to_json(nlohmann::json& j) const {
8✔
693
    j["transformation_type"] = this->name();
8✔
694
    j["parameters"] = nlohmann::json::object();
8✔
695

696
    serializer::JSONSerializer serializer_full;
8✔
697
    j["parameters"]["storage_type"] = nlohmann::json::object();
8✔
698
    serializer_full.storage_type_to_json(j["parameters"]["storage_type"], storage_type_);
8✔
699

700
    serializer::JSONSerializer ser_flat(false);
8✔
701
    j["subgraph"] = nlohmann::json::object();
8✔
702
    j["subgraph"]["0"] = nlohmann::json::object();
8✔
703
    ser_flat.serialize_node(j["subgraph"]["0"], loop_);
8✔
704

705
    j["subgraph"]["1"] = nlohmann::json::object();
8✔
706
    j["subgraph"]["1"]["element_id"] = access_node_.element_id();
8✔
707
    j["subgraph"]["1"]["type"] = "access_node";
8✔
708
}
8✔
709

710
InLocalStorage InLocalStorage::from_json(builder::StructuredSDFGBuilder& builder, const nlohmann::json& desc) {
3✔
711
    auto loop_id = desc["subgraph"]["0"]["element_id"].get<size_t>();
3✔
712
    auto element = builder.find_element_by_id(loop_id);
3✔
713
    if (!element) {
3✔
714
        throw InvalidTransformationDescriptionException("Element with ID " + std::to_string(loop_id) + " not found.");
×
715
    }
×
716
    auto loop = dynamic_cast<structured_control_flow::StructuredLoop*>(element);
3✔
717
    if (!loop) {
3✔
718
        throw InvalidTransformationDescriptionException(
×
719
            "Element with ID " + std::to_string(loop_id) + " is not a structured loop."
×
720
        );
×
721
    }
×
722

723
    auto access_node = dynamic_cast<
3✔
724
        data_flow::AccessNode*>(builder.find_element_by_id(desc.at("subgraph").at("1").at("element_id").get<size_t>()));
3✔
725
    if (!access_node) {
3✔
726
        throw InvalidTransformationDescriptionException(
×
727
            "Access node with ID " + std::to_string(desc.at("subgraph").at("1").at("element_id").get<size_t>()) +
×
728
            " not found."
×
729
        );
×
730
    }
×
731

732
    types::StorageType storage_type = types::StorageType::CPU_Stack();
3✔
733
    if (desc["parameters"].contains("storage_type")) {
3✔
734
        serializer::JSONSerializer serializer_full;
3✔
735
        storage_type = serializer_full.json_to_storage_type(desc["parameters"]["storage_type"]);
3✔
736
    }
3✔
737

738
    return InLocalStorage(*loop, *access_node, storage_type);
3✔
739
}
3✔
740

741
} // namespace transformations
742
} // namespace sdfg
STATUS · Troubleshooting · Open an Issue · Sales · Support · CAREERS · ENTERPRISE · START FREE · SCHEDULE DEMO
ANNOUNCEMENTS · TWITTER · TOS & SLA · Supported CI Services · What's a CI service? · Automated Testing

© 2026 Coveralls, Inc