legalize_safe_memory_access.cc 9.48 KB
Newer Older
1
/*!
2
3
 * \file legalize_safe_memory_access.cc
 * \brief legalize safe memory access
4
5
6
7
8
9
10
11
12
13
14
 */

#include <tvm/tir/builtin.h>
#include <tvm/tir/op.h>
#include <tvm/tir/stmt_functor.h>
#include <tvm/tir/transform.h>
#include <tvm/tir/utils.h>

#include <queue>

#include "../op/parallel.h"
15
#include "arith/ir_mutator_with_analyzer.h"
16
17
18
19
20
21
22
23
24
25
26
#include "loop_partition.h"
#include "loop_vectorize.h"

namespace tvm {
namespace tl {

using namespace tir;
using arith::IRMutatorWithAnalyzer;

// Helper class to find leaf For nodes in a given IR
class LeafForFinder : public StmtVisitor {
27
public:
28
29
  std::vector<For> leaf_for_nodes;

30
31
private:
  void VisitStmt_(const ForNode *op) final {
32
33
34
35
36
37
38
39
40
41
42
43
44
45
    has_child_for_ = false;
    bool parent_has_child_for = parent_has_child_for_;
    parent_has_child_for_ = false;

    StmtVisitor::VisitStmt(op->body);

    if (!has_child_for_) {
      leaf_for_nodes.push_back(GetRef<For>(op));
    }

    parent_has_child_for_ = parent_has_child_for;
    parent_has_child_for_ = true;
  }

46
private:
47
48
49
50
51
52
53
54
55
56
57
58
  bool has_child_for_ = false;
  bool parent_has_child_for_ = false;
};

// We will create a visitor to check BufferLoad and BufferStore nodes
// within this loop body. This visitor will:
// 1. Identify BufferLoad and BufferStore nodes.
// 2. Check if the buffer is in global scope.
// 3. For each index, compare against the buffer's shape.
//    If the index might exceed the shape (upper bound too large),
//    log a warning or handle accordingly.
struct GlobalMemChecker : public StmtExprVisitor {
59
  arith::Analyzer *analyzer;
60

61
  explicit GlobalMemChecker(arith::Analyzer *analyzer) : analyzer(analyzer) {}
62

63
  void VisitExpr_(const BufferLoadNode *op) final {
64
65
66
67
68
69
70
    // Check if the buffer is in global scope
    if (IsGlobalBuffer(op->buffer)) {
      CheckBufferIndices(op->buffer, op->indices, /*is_load=*/true);
    }
    StmtExprVisitor::VisitExpr_(op);
  }

71
  void VisitStmt_(const BufferStoreNode *op) final {
72
73
74
75
76
77
78
79
    // Check if the buffer is in global scope
    if (IsGlobalBuffer(op->buffer)) {
      CheckBufferIndices(op->buffer, op->indices, /*is_load=*/false);
    }
    StmtExprVisitor::VisitStmt_(op);
  }

  // Helper function to determine if a buffer is global
80
81
82
83
84
85
  bool IsGlobalBuffer(const Buffer &buffer) {
    // The storage scope is often encoded in the buffer->data var name or
    // associated attributes. In typical TVM IR, global buffers have scope
    // "global". Here we assume a helper function GetPtrStorageScope is
    // available. If not, you might need to parse buffer->data->name_hint or
    // associated attributes.
86
87
88
89
90
    String scope = buffer.scope();
    return scope == "global";
  }

  // Check each index against the buffer shape dimensions
91
92
  void CheckBufferIndices(const Buffer &buffer, const Array<PrimExpr> &indices,
                          bool is_load) {
93
94
    // Ensure indices count matches buffer dimension
    if (indices.size() != buffer->shape.size()) {
95
96
97
      LOG(WARNING) << "Buffer access dimension mismatch: indices size ("
                   << indices.size() << ") vs. shape size ("
                   << buffer->shape.size() << ")";
98
99
100
101
102
103
104
      return;
    }

    for (size_t i = 0; i < indices.size(); i++) {
      PrimExpr index = indices[i];
      PrimExpr shape_dim = buffer->shape[i];

105
106
107
108
109
110
111
112
113
114
      bool has_variable = false;
      PostOrderVisit(index, [&](const ObjectRef &obj) {
        if (const VarNode *v = obj.as<VarNode>()) {
          has_variable = true;
        }
      });
      if (!has_variable) {
        continue;
      }

115
116
117
118
119
120
121
122
123
124
125
126
      // We want to check if index < shape_dim can be proven.
      // If analyzer->CanProve(index < shape_dim) returns false,
      // it means we cannot prove the access is within bounds.
      PrimExpr cond = index < shape_dim;
      if (!analyzer->CanProve(cond)) {
        _conditions.push_back(cond);
      }
    }
  }

  Array<PrimExpr> GetConditions() { return _conditions; }

127
private:
128
129
130
131
  Array<PrimExpr> _conditions;
};

class SafeMemorysRewriter : public StmtExprMutator {
132
  arith::Analyzer *analyzer_;
133

134
135
136
public:
  explicit SafeMemorysRewriter(arith::Analyzer *analyzer)
      : analyzer_(analyzer) {}
137

138
139
private:
  Stmt VisitStmt_(const BufferStoreNode *op) final {
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
    // Check if the buffer is in global scope
    auto store = Downcast<BufferStore>(StmtExprMutator::VisitStmt_(op));
    GlobalMemChecker checker(analyzer_);
    checker(store);
    Array<PrimExpr> conditions = checker.GetConditions();
    if (conditions.size() == 0) {
      return store;
    }

    auto value = store->value;
    if (IsGlobalBuffer(store->buffer)) {
      Stmt store_with_conditions = store;
      for (auto cond : conditions) {
        store_with_conditions = IfThenElse(cond, store_with_conditions);
      }
      return store_with_conditions;
    } else if (isSharedBuffer(store->buffer)) {
      PrimExpr value = store->value;
      for (auto cond : conditions) {
159
160
        ICHECK(cond.dtype() == DataType::Bool(1))
            << "condition is not a boolean: " << cond;
161
162
163
164
        value = if_then_else(cond, value, make_zero(value->dtype));
      }
      store.CopyOnWrite()->value = value;
      return store;
165
166
167
168
169
170
171
172
173
174
175
176
    } else if (IsLocalBuffer(store->buffer)) {
      PrimExpr value = store->value;
      for (auto cond : conditions) {
        ICHECK(cond.dtype() == DataType::Bool(1))
            << "condition is not a boolean: " << cond;
        value = if_then_else(cond, value, make_zero(value->dtype));
      }
      store.CopyOnWrite()->value = value;
      return store;
    } else {
      LOG(FATAL) << "Check store buffer: " << store->buffer
                 << " is not a global or shared or local buffer";
177
178
179
180
181
182
183
    }

    return store;
  }

  // Handle Call Nodes
  // For example
184
185
186
  // T.call_extern("handle", "atomicAddx2", T.address_of(C),
  // T.address_of(C_shared))
  Stmt VisitStmt_(const EvaluateNode *op) final {
187
    auto evaluate = Downcast<Evaluate>(StmtExprMutator::VisitStmt_(op));
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
    if (const CallNode *call_op = op->value.as<CallNode>()) {
      auto call = Downcast<Call>(evaluate->value);
      if (call->op == builtin::call_extern()) {
        GlobalMemChecker checker(analyzer_);
        checker(call);
        Array<PrimExpr> conditions = checker.GetConditions();

        if (conditions.size() == 0) {
          return evaluate;
        }

        Stmt evaluate_with_conditions = evaluate;
        for (auto cond : conditions) {
          evaluate_with_conditions = IfThenElse(cond, evaluate_with_conditions);
        }
        return evaluate_with_conditions;
204
205
206
207
208
209
      }
    }

    return evaluate;
  }

210
211
212
213
214
  bool IsLocalBuffer(const Buffer &buffer) {
    String scope = buffer.scope();
    return scope == "local" || scope == "local.fragment";
  }

215
  bool isSharedBuffer(const Buffer &buffer) {
216
217
218
219
    String scope = buffer.scope();
    return scope == "shared" || scope == "shared.dyn";
  }

220
  bool IsGlobalBuffer(const Buffer &buffer) {
221
222
223
224
225
226
227
    String scope = buffer.scope();
    return scope == "global";
  }
};

// Class to legalize safe memory access by transforming them appropriately
class SafeMemoryLegalizer : IRMutatorWithAnalyzer {
228
public:
229
230
231
232
233
234
  // Static method to substitute and transform the given PrimFunc
  static PrimFunc Substitute(PrimFunc f) {
    arith::Analyzer analyzer;
    // Create an instance of the legalizer with the analyzer
    SafeMemoryLegalizer substituter(&analyzer);
    // Get a mutable copy of the function node
235
    PrimFuncNode *fptr = f.CopyOnWrite();
236
237
238
239
240
    // Apply the legalizer to the function body
    fptr->body = substituter.VisitStmt(f->body);
    return f;
  }

241
private:
242
  // Constructor initializing the base class with the analyzer
243
244
  SafeMemoryLegalizer(arith::Analyzer *analyzer)
      : arith::IRMutatorWithAnalyzer(analyzer) {}
245
246

  // Override the VisitStmt_ method to handle ForNode (loop statements)
247
  Stmt VisitStmt_(const ForNode *op) final {
248
249
250
251
252
253
    // Visit and potentially modify the loop node
    For for_node = Downcast<For>(IRMutatorWithAnalyzer::VisitStmt_(op));
    auto has_inner_loop = HasInnerLoop(for_node->body);
    if (!has_inner_loop) {
      SafeMemorysRewriter rewriter(analyzer_);
      for_node.CopyOnWrite()->body = rewriter(for_node->body);
254
255
      // // Detect Buffer Load Node in the loop body, collect the indices and
      // buffer size
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275

      // // Run the checker on the loop body
      // GlobalMemChecker checker(analyzer_);
      // checker(for_node->body);
      // Array<PrimExpr> conditions = checker.GetConditions();
      // auto body = for_node->body;
      // // Note that we might have duplicate conditions
      // // Which will be optimized by simplify pass
      // // Replace the loop body with the new body
      // for (auto cond : conditions) {
      //   body = IfThenElse(cond, body);
      // }
      // for_node.CopyOnWrite()->body = body;
      return std::move(for_node);
    }

    // Visit a For Node
    return IRMutatorWithAnalyzer::VisitStmt_(op);
  }

276
  static bool HasInnerLoop(const Stmt &stmt) {
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
    LeafForFinder finder;
    finder(stmt);
    return finder.leaf_for_nodes.size() > 0;
  }
};

// Create a pass that legalizes vectorized loops in the IRModule
tvm::transform::Pass LegalizeSafeMemoryAccess() {
  using namespace tir::transform;
  // Define the transformation function to be applied
  auto pass_func = [=](PrimFunc f, IRModule m, PassContext ctx) {
    return SafeMemoryLegalizer::Substitute(std::move(f));
  };
  // Create and return a PrimFunc pass with the transformation function
  return CreatePrimFuncPass(pass_func, 0, "tl.LegalizeSafeMemoryAccess", {});
}

// Register the pass globally so it can be used in the compilation pipeline
TVM_REGISTER_GLOBAL("tl.transform.LegalizeSafeMemoryAccess")
    .set_body_typed(LegalizeSafeMemoryAccess);

298
299
} // namespace tl
} // namespace tvm