开源 企业版 高校版 私有云 模力方舟 AI 队友
代码拉取完成,页面将自动刷新
捐赠
捐赠前请先登录
扫描微信二维码支付
取消
支付完成
支付提示
将跳转至支付宝完成支付
确定
取消
1 Star 0 Fork 3

xiongying/Halide

加入 Gitee
与超过 1400万 开发者一起发现、参与优秀开源项目,私有仓库也完全免费 :)
免费加入
已有帐号? 立即登录
文件
main
分支 (1093)
标签 (17)
main
xtensa-codegen
vksnk/dma-limit-channels
rootjalex/trs-codegen-cross
abadams/fix_7374
abadams/remove_hack_from_gpu_only_aottest
srj/gpu-cache
srj/generator_aot_gpu_multi_context_threaded
srj/xtensa-merge
abadams/vector_scan
abadams/fix_7365
darya-ver/ir-viz
vulkan-phase2-runtime
srj/param-map-deprecation
srj/rt-return-types
srj/main-vs2022
release/15.x
srj/param-map
abadams/ir_builder_unique_ptr
vksnk/restrict
v14.0.0
v13.0.4
v13.0.3
v13.0.2
v13.0.1
v13.0.0
v12.0.1
v12.0.0
v11.0.1
v11.0.0
v10.0.1
v10.0.0
release_2019_08_27
release_8.0.0
v8.0.0
release_2018_02_15
release_2013_11_11
main
分支 (1093)
标签 (17)
main
xtensa-codegen
vksnk/dma-limit-channels
rootjalex/trs-codegen-cross
abadams/fix_7374
abadams/remove_hack_from_gpu_only_aottest
srj/gpu-cache
srj/generator_aot_gpu_multi_context_threaded
srj/xtensa-merge
abadams/vector_scan
abadams/fix_7365
darya-ver/ir-viz
vulkan-phase2-runtime
srj/param-map-deprecation
srj/rt-return-types
srj/main-vs2022
release/15.x
srj/param-map
abadams/ir_builder_unique_ptr
vksnk/restrict
v14.0.0
v13.0.4
v13.0.3
v13.0.2
v13.0.1
v13.0.0
v12.0.1
v12.0.0
v11.0.1
v11.0.0
v10.0.1
v10.0.0
release_2019_08_27
release_8.0.0
v8.0.0
release_2018_02_15
release_2013_11_11
克隆/下载
克隆/下载
提示
下载代码请复制以下命令到终端执行
为确保你提交的代码身份被 Gitee 正确识别,请执行以下命令完成配置
初次使用 SSH 协议进行代码克隆、推送等操作时,需按下述提示完成 SSH 配置
1 生成 RSA 密钥
2 获取 RSA 公钥内容,并配置到 SSH公钥
在 Gitee 上使用 SVN,请访问 使用指南
使用 HTTPS 协议时,命令行会出现如下账号密码验证步骤。基于安全考虑,Gitee 建议 配置并使用私人令牌 替代登录密码进行克隆、推送等操作
Username for 'https://gitee.com': userName
Password for 'https://userName@gitee.com': # 私人令牌
main
分支 (1093)
标签 (17)
main
xtensa-codegen
vksnk/dma-limit-channels
rootjalex/trs-codegen-cross
abadams/fix_7374
abadams/remove_hack_from_gpu_only_aottest
srj/gpu-cache
srj/generator_aot_gpu_multi_context_threaded
srj/xtensa-merge
abadams/vector_scan
abadams/fix_7365
darya-ver/ir-viz
vulkan-phase2-runtime
srj/param-map-deprecation
srj/rt-return-types
srj/main-vs2022
release/15.x
srj/param-map
abadams/ir_builder_unique_ptr
vksnk/restrict
v14.0.0
v13.0.4
v13.0.3
v13.0.2
v13.0.1
v13.0.0
v12.0.1
v12.0.0
v11.0.1
v11.0.0
v10.0.1
v10.0.0
release_2019_08_27
release_8.0.0
v8.0.0
release_2018_02_15
release_2013_11_11
Halide
/
src
/
LoopCarry.cpp
Halide
/
src
/
LoopCarry.cpp
LoopCarry.cpp 19.47 KB
一键复制 编辑 原始数据 按行查看 历史
Steven Johnson 提交于 2021年10月08日 04:04 +08:00 . Modernize loops, part 3 (#6295)
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
#include "LoopCarry.h"
#include "CSE.h"
#include "ExprUsesVar.h"
#include "IREquality.h"
#include "IRMutator.h"
#include "IROperator.h"
#include "Simplify.h"
#include "Substitute.h"
#include <algorithm>
namespace Halide {
namespace Internal {
using std::pair;
using std::set;
using std::string;
using std::vector;
namespace {
/** If an integer expression varies linearly with the variables in the
* scope, return the linear term. Otherwise return an undefined
* Expr. */
Expr is_linear(const Expr &e, const Scope<Expr> &linear) {
if (e.type() != Int(32)) {
return Expr();
}
if (const Variable *v = e.as<Variable>()) {
if (linear.contains(v->name)) {
return linear.get(v->name);
} else {
return make_zero(v->type);
}
} else if (const IntImm *op = e.as<IntImm>()) {
return make_zero(op->type);
} else if (const Add *add = e.as<Add>()) {
Expr la = is_linear(add->a, linear);
Expr lb = is_linear(add->b, linear);
if (is_const_zero(lb)) {
return la;
} else if (is_const_zero(la)) {
return lb;
} else if (la.defined() && lb.defined()) {
return la + lb;
} else {
return Expr();
}
} else if (const Sub *sub = e.as<Sub>()) {
Expr la = is_linear(sub->a, linear);
Expr lb = is_linear(sub->b, linear);
if (is_const_zero(lb)) {
return la;
} else if (la.defined() && lb.defined()) {
return la - lb;
} else {
return Expr();
}
} else if (const Mul *mul = e.as<Mul>()) {
Expr la = is_linear(mul->a, linear);
Expr lb = is_linear(mul->b, linear);
if (is_const_zero(la) && is_const_zero(lb)) {
return la;
} else if (is_const_zero(la) && lb.defined()) {
return mul->a * lb;
} else if (la.defined() && is_const_zero(lb)) {
return la * mul->b;
} else {
return Expr();
}
} else if (const Ramp *r = e.as<Ramp>()) {
Expr la = is_linear(r->base, linear);
Expr lb = is_linear(r->stride, linear);
if (is_const_zero(lb)) {
return la;
} else {
return Expr();
}
} else if (const Broadcast *b = e.as<Broadcast>()) {
return is_linear(b->value, linear);
} else {
return Expr();
}
}
class FindLoads : public IRGraphVisitor {
using IRVisitor::visit;
// We don't use this set as the result directly, to avoid
// non-deterministic behavior due to pointers changing value from
// one run to the next.
set<const Load *> found;
void visit(const Load *op) override {
if (found.count(op) == 0) {
found.insert(op);
result.push_back(op);
}
// Don't consider nested loads inside the index
// IRVisitor::visit(op);
}
public:
vector<const Load *> result;
};
/** A helper for block_to_vector below. */
void block_to_vector(const Stmt &s, vector<Stmt> &v) {
const Block *b = s.as<Block>();
if (!b) {
v.push_back(s);
} else {
block_to_vector(b->first, v);
block_to_vector(b->rest, v);
}
}
/** Unpack a block into its component Stmts. */
vector<Stmt> block_to_vector(const Stmt &s) {
vector<Stmt> result;
block_to_vector(s, result);
return result;
}
Expr scratch_index(int i, Type t) {
if (t.is_scalar()) {
return i;
} else {
return Ramp::make(i * t.lanes(), 1, t.lanes());
}
}
/** Given a scope of things that move linearly over time, come up with
* the next time step's version of some arbitrary Expr (which may be a
* nasty graph). Variables that move non-linearly through time are
* undefined Exprs in the scope. */
class StepForwards : public IRGraphMutator {
const Scope<Expr> &linear;
using IRGraphMutator::visit;
Expr visit(const Variable *op) override {
if (linear.contains(op->name)) {
Expr step = linear.get(op->name);
if (!step.defined()) {
// It's non-linear
success = false;
return op;
} else if (is_const_zero(step)) {
// It's a known inner constant
return op;
} else {
// It's linear
return Expr(op) + step;
}
} else {
// It's some external constant
return op;
}
}
public:
bool success = true;
StepForwards(const Scope<Expr> &s)
: linear(s) {
}
};
Expr step_forwards(Expr e, const Scope<Expr> &linear) {
StepForwards step(linear);
e = step.mutate(e);
if (!step.success) {
return Expr();
} else {
// We need to simplify it to reduce it to a canonical form,
// but it's a full graph, so we'll need to CSE it first.
e = common_subexpression_elimination(e);
e = simplify(e);
e = substitute_in_all_lets(e);
return e;
}
}
/** Carry loads over a single For loop body. */
class LoopCarryOverLoop : public IRMutator {
// Track vars that step linearly with loop iterations
Scope<Expr> linear;
vector<pair<string, Expr>> containing_lets;
// Productions we're in a consume node for. They're fixed and safe
// to lift out.
const Scope<> &in_consume;
int max_carried_values;
using IRMutator::visit;
Stmt visit(const LetStmt *op) override {
// Track containing LetStmts and their linearity w.r.t. the
// loop variable.
Expr value = mutate(op->value);
Expr step = is_linear(value, linear);
ScopedBinding<Expr> bind(linear, op->name, step);
containing_lets.emplace_back(op->name, value);
Stmt stmt;
Stmt body = mutate(op->body);
if (value.same_as(op->value) &&
body.same_as(op->body)) {
stmt = op;
} else {
stmt = LetStmt::make(op->name, value, body);
}
containing_lets.pop_back();
return stmt;
}
Stmt visit(const Store *op) override {
return lift_carried_values_out_of_stmt(op);
}
Stmt visit(const Block *op) override {
vector<Stmt> v = block_to_vector(op);
vector<Stmt> stores;
vector<Stmt> result;
for (Stmt &stmt : v) {
if (stmt.as<Store>()) {
stores.push_back(stmt);
} else {
if (!stores.empty()) {
result.push_back(lift_carried_values_out_of_stmt(Block::make(stores)));
stores.clear();
}
result.push_back(mutate(stmt));
}
}
if (!stores.empty()) {
result.push_back(lift_carried_values_out_of_stmt(Block::make(stores)));
}
return Block::make(result);
}
Stmt lift_carried_values_out_of_stmt(const Stmt &orig_stmt) {
debug(4) << "About to lift carried values out of stmt: " << orig_stmt << "\n";
// The stmts, as graphs (lets subtituted in). We must only use
// graph-aware methods to touch these, lest we incur
// exponential runtime.
Stmt graph_stmt = substitute_in_all_lets(orig_stmt);
// Find all the loads in these stmts.
FindLoads find_loads;
graph_stmt.accept(&find_loads);
debug(4) << "Found " << find_loads.result.size() << " loads\n";
// Group equal loads
vector<vector<const Load *>> loads;
for (const Load *load : find_loads.result) {
// Check if it's safe to lift out.
bool safe = (load->image.defined() ||
load->param.defined() ||
in_consume.contains(load->name));
if (!safe) {
continue;
}
bool represented = false;
for (vector<const Load *> &v : loads) {
if (graph_equal(Expr(load), Expr(v[0]))) {
v.push_back(load);
represented = true;
}
}
if (!represented) {
loads.push_back({load});
}
}
// For each load, move the load index forwards by one loop iteration
vector<Expr> indices, next_indices, predicates, next_predicates;
for (const vector<const Load *> &v : loads) {
indices.push_back(v[0]->index);
next_indices.push_back(step_forwards(v[0]->index, linear));
predicates.push_back(v[0]->predicate);
next_predicates.push_back(step_forwards(v[0]->predicate, linear));
}
// Find loads done on this loop iteration that will be
// reusable as some other Expr on the next loop iteration.
vector<vector<int>> chains;
for (int i = 0; i < (int)indices.size(); i++) {
for (int j = 0; j < (int)indices.size(); j++) {
// Don't catch loop invariants here.
if (i == j) {
continue;
}
if (loads[i][0]->name == loads[j][0]->name &&
next_indices[j].defined() &&
graph_equal(indices[i], next_indices[j]) &&
next_predicates[j].defined() &&
graph_equal(predicates[i], next_predicates[j])) {
chains.push_back({j, i});
debug(3) << "Found carried value:\n"
<< i << ": -> " << Expr(loads[i][0]) << "\n"
<< j << ": -> " << Expr(loads[j][0]) << "\n";
}
}
}
if (chains.empty()) {
return orig_stmt;
}
// Agglomerate chains of carries
bool done = false;
while (!done) {
done = true;
for (size_t i = 0; i < chains.size(); i++) {
if (chains[i].empty()) {
continue;
}
for (size_t j = 0; j < chains.size(); j++) {
if (chains[j].empty()) {
continue;
}
if (chains[i].back() == chains[j].front()) {
chains[i].insert(chains[i].end(), chains[j].begin() + 1, chains[j].end());
chains[j].clear();
done = false;
}
}
}
for (size_t i = 0; i < chains.size(); i++) {
while (i < chains.size() && chains[i].empty()) {
chains[i].swap(chains.back());
chains.pop_back();
}
}
}
// Sort the carry chains by decreasing order of size. The
// longest ones get the most reuse of each value.
//
// Use of stable_sort is just so that IR generated by different C++ compilers
// is identical; it doesn't appear to make any meaningful difference
// in code output, but makes debugging IR output easier to deal with.
std::stable_sort(chains.begin(), chains.end(),
[&](const vector<int> &c1, const vector<int> &c2) { return c1.size() > c2.size(); });
for (const vector<int> &c : chains) {
debug(3) << "Found chain of carried values:\n";
for (int i : c) {
debug(3) << i << ": <- " << indices[i] << "\n";
}
}
// Only keep the top N carried values. Otherwise we'll just
// spray stack spills everywhere. This is ugly, because we're
// relying on a heuristic.
vector<vector<int>> trimmed;
size_t sz = 0;
for (const vector<int> &c : chains) {
if (sz + c.size() > (size_t)max_carried_values) {
if (sz < (size_t)max_carried_values - 1) {
// Take a partial chain
trimmed.emplace_back(c.begin(), c.begin() + max_carried_values - sz);
}
break;
}
trimmed.push_back(c);
sz += c.size();
}
chains.swap(trimmed);
// We now have chains of the form:
// f[x] <- f[x+1] <- ... <- f[x+N-1]
// There are N values in that chain. N-1 of these can be
// reused from the previous loop iteration. We make a scratch
// buffer of size N. First we load the leading edge (the end
// of the chain) into in the last position. Then we run the
// original stmt with the loads replaced with loads from the
// scratch buffer, then we move the last N-1 values in the
// scratch buffer down one, so they're in the right place for
// the next loop iteration. If it's the first loop iteration,
// we need to populate the entire scratch buffer.
vector<Stmt> not_first_iteration_scratch_stores;
vector<Stmt> scratch_shuffles;
Stmt core = graph_stmt;
for (const vector<int> &c : chains) {
string scratch = unique_name('c');
vector<Expr> initial_scratch_values;
for (size_t i = 0; i < c.size(); i++) {
const Load *orig_load = loads[c[i]][0];
Expr scratch_idx = scratch_index(i, orig_load->type);
// Don't worry about alignment - the load is at a constant address.
Expr load_from_scratch = Load::make(orig_load->type, scratch, scratch_idx,
Buffer<>(), Parameter(), const_true(orig_load->type.lanes()), ModulusRemainder());
for (const Load *l : loads[c[i]]) {
core = graph_substitute(l, load_from_scratch, core);
}
if (i == c.size() - 1) {
Stmt store_to_scratch = Store::make(scratch, orig_load, scratch_idx,
Parameter(), const_true(orig_load->type.lanes()), ModulusRemainder());
not_first_iteration_scratch_stores.push_back(store_to_scratch);
} else {
initial_scratch_values.emplace_back(orig_load);
}
if (i > 0) {
Stmt shuffle = Store::make(scratch, load_from_scratch,
scratch_index(i - 1, orig_load->type),
Parameter(), const_true(orig_load->type.lanes()), ModulusRemainder());
scratch_shuffles.push_back(shuffle);
}
}
// Do joint CSE on the initial scratch values instead of
// cse'ing each independently. They'll shared common
// values and they originated from the same Expr.
vector<pair<string, Expr>> initial_lets;
// Group them into a single expression with a call node
Expr call = Call::make(Int(32), unique_name('b'), initial_scratch_values, Call::PureIntrinsic);
// Run CSE
call = simplify(common_subexpression_elimination(call));
// Peel off lets
while (const Let *l = call.as<Let>()) {
initial_lets.emplace_back(l->name, l->value);
call = l->body;
}
internal_assert(call.as<Call>());
initial_scratch_values = call.as<Call>()->args;
// Create the initial stores to scratch
vector<Stmt> initial_scratch_stores;
for (size_t i = 0; i < c.size() - 1; i++) {
Expr scratch_idx = scratch_index(i, initial_scratch_values[i].type());
Stmt store_to_scratch = Store::make(scratch, initial_scratch_values[i],
scratch_idx, Parameter(),
const_true(scratch_idx.type().lanes()),
ModulusRemainder());
initial_scratch_stores.push_back(store_to_scratch);
}
Stmt initial_stores = Block::make(initial_scratch_stores);
// Wrap them in the appropriate lets
for (size_t i = initial_lets.size(); i > 0; i--) {
auto l = initial_lets[i - 1];
initial_stores = LetStmt::make(l.first, l.second, initial_stores);
}
// We may be lifting the initial stores out of let stmts,
// so rewrap them in the necessary ones.
for (size_t i = containing_lets.size(); i > 0; i--) {
auto l = containing_lets[i - 1];
if (stmt_uses_var(initial_stores, l.first)) {
initial_stores = LetStmt::make(l.first, l.second, initial_stores);
}
}
allocs.push_back({scratch,
loads[c.front()][0]->type.element_of(),
(int)c.size() * loads[c.front()][0]->type.lanes(),
initial_stores});
}
Stmt s = Block::make(not_first_iteration_scratch_stores);
s = Block::make(s, core);
s = Block::make(s, Block::make(scratch_shuffles));
s = common_subexpression_elimination(s);
return s;
}
Stmt visit(const For *op) override {
// Don't lift loads out of code that might not run. Besides,
// stashing things in registers while we run an inner loop
// probably isn't a good use of registers.
return op;
}
Stmt visit(const IfThenElse *op) override {
// Don't lift loads out of code that might not run.
return op;
}
public:
LoopCarryOverLoop(const string &var, const Scope<> &s, int max_carried_values)
: in_consume(s), max_carried_values(max_carried_values) {
linear.push(var, 1);
}
struct ScratchAllocation {
string name;
Type type;
int size;
Stmt initial_stores;
};
vector<ScratchAllocation> allocs;
};
class LoopCarry : public IRMutator {
using IRMutator::visit;
int max_carried_values;
Scope<> in_consume;
Stmt visit(const ProducerConsumer *op) override {
if (op->is_producer) {
return IRMutator::visit(op);
} else {
ScopedBinding<> bind(in_consume, op->name);
Stmt body = mutate(op->body);
return ProducerConsumer::make(op->name, op->is_producer, body);
}
}
Stmt visit(const For *op) override {
if (op->for_type == ForType::Serial && !is_const_one(op->extent)) {
Stmt stmt;
Stmt body = mutate(op->body);
LoopCarryOverLoop carry(op->name, in_consume, max_carried_values);
body = carry.mutate(body);
if (body.same_as(op->body)) {
stmt = op;
} else {
stmt = For::make(op->name, op->min, op->extent, op->for_type, op->device_api, body);
}
// Inject the scratch buffer allocations.
for (const auto &alloc : carry.allocs) {
stmt = Block::make(substitute(op->name, op->min, alloc.initial_stores), stmt);
stmt = Allocate::make(alloc.name, alloc.type, MemoryType::Stack, {alloc.size}, const_true(), stmt);
}
if (!carry.allocs.empty()) {
stmt = IfThenElse::make(op->extent > 0, stmt);
}
return stmt;
} else {
return IRMutator::visit(op);
}
}
public:
LoopCarry(int max_carried_values)
: max_carried_values(max_carried_values) {
}
};
} // namespace
Stmt loop_carry(Stmt s, int max_carried_values) {
s = LoopCarry(max_carried_values).mutate(s);
return s;
}
} // namespace Internal
} // namespace Halide
Loading...
举报
举报成功
我们将于2个工作日内通过站内信反馈结果给你!
请认真填写举报原因,尽可能描述详细。
请选择举报类型
取消
发送
误判申诉

此处可能存在不合适展示的内容,页面不予展示。您可通过相关编辑功能自查并修改。

如您确认内容无涉及 不当用语 / 纯广告导流 / 暴力 / 低俗色情 / 侵权 / 盗版 / 虚假 / 无价值内容或违法国家有关法律法规的内容,可点击提交进行申诉,我们将尽快为您处理。

取消
提交

简介

MIT计算机科学和人工智能实验室的研究人员创造出一种专门设计简化图像处理的程序语言Halide,源代码托管在GitHub上,目前二进制程序只支持Mac OS X和Ubuntu 12
取消

发行版

暂无发行版

贡献者

全部

近期动态

不能加载更多了
编辑仓库简介
简介内容
主页
马建仓 AI 助手
尝试更多
代码解读
代码找茬
代码优化
C/C++
1
https://gitee.com/VisionDeveloper/Halide.git
git@gitee.com:VisionDeveloper/Halide.git
VisionDeveloper
Halide
Halide
main
点此查找更多帮助

搜索帮助

评论
仓库举报
回到顶部
登录提示
该操作需登录 Gitee 帐号,请先登录后再操作。
立即登录
没有帐号,去注册

AltStyle によって変換されたページ (->オリジナル) /