/*
 * Licensed to the Apache Software Foundation (ASF) under one
 * or more contributor license agreements.  See the NOTICE file
 * distributed with this work for additional information
 * regarding copyright ownership.  The ASF licenses this file
 * to you under the Apache License, Version 2.0 (the
 * "License"); you may not use this file except in compliance
 * with the License.  You may obtain a copy of the License at
 *
 *   http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing,
 * software distributed under the License is distributed on an
 * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
 * KIND, either express or implied.  See the License for the
 * specific language governing permissions and limitations
 * under the License.
 */

/*!
 * \file tvm/arith/ir_visitor_with_analyzer.cc
 */
#include "ir_visitor_with_analyzer.h"

#include <tvm/ir/op.h>
#include <tvm/s_tir/stmt.h>
#include <tvm/tirx/analysis.h>
#include <tvm/tirx/builtin.h>
#include <tvm/tirx/op.h>

namespace tvm {
namespace arith {

using namespace tirx;

void IRVisitorWithAnalyzer::VisitStmt_(const ForNode* op) {
  constraint_scope_.WithNewScope([&]() {
    analyzer_->Bind(op->loop_var, Range::FromMinExtent(op->min, op->extent));
    this->VisitExpr(op->min);
    this->VisitExpr(op->extent);
    if (op->step.has_value()) {
      this->VisitExpr(*op->step);
    }
    constraint_scope_.WithNewScope([&]() {
      constraint_scope_.Current().Emplace(analyzer_, op->extent > IntImm(op->extent.ty(), 0));
      this->VisitStmt(op->body);
    });
  });
}

void IRVisitorWithAnalyzer::VisitStmt_(const SBlockNode* op) {
  constraint_scope_.WithNewScope([&]() {
    for (const auto& iter_var : op->iter_vars) {
      analyzer_->Bind(iter_var->var, iter_var->dom);
    }
    StmtExprVisitor::VisitStmt_(op);
  });
}

void IRVisitorWithAnalyzer::VisitStmt_(const BindNode* op) {
  this->VisitExpr(op->value);
  if (ffi::Optional<PrimExpr> value = op->value.as<PrimExpr>()) {
    analyzer_->Bind(op->var, value.value());
  }
}

void IRVisitorWithAnalyzer::VisitStmt_(const IfThenElseNode* op) {
  constraint_scope_.WithNewScope([&]() {
    this->VisitExpr(op->condition);

    PrimExpr real_condition = ExtractRealCondition(op->condition);

    constraint_scope_.WithNewScope([&]() {
      constraint_scope_.Current().Emplace(analyzer_, real_condition);
      this->VisitStmt(op->then_case);
    });
    if (op->else_case) {
      constraint_scope_.WithNewScope([&]() {
        constraint_scope_.Current().Emplace(analyzer_,
                                            analyzer_->rewrite_simplify(Not(real_condition)));
        this->VisitStmt(op->else_case.value());
      });
    }
  });
}

void IRVisitorWithAnalyzer::VisitStmt_(const AttrStmtNode* op) {
  constraint_scope_.WithNewScope([&]() {
    if (op->attr_key == tirx::attr::thread_extent || op->attr_key == s_tir::attr::virtual_thread) {
      IterVar iv = op->node.as_or_throw<IterVar>();
      TVM_FFI_ICHECK_NE(iv->thread_tag.length(), 0U);
      analyzer_->Bind(iv->var, Range::FromMinExtent(IntImm(op->value.ty(), 0), op->value));
    }
    StmtExprVisitor::VisitStmt_(op);
  });
}

void IRVisitorWithAnalyzer::VisitStmt_(const AssertStmtNode* op) {
  this->VisitExpr(op->condition);
  constraint_scope_.Current().Emplace(analyzer_, op->condition);
}

void IRVisitorWithAnalyzer::VisitStmt_(const SeqStmtNode* op) {
  // SeqStmt does NOT get WithNewScope — constraints accumulate across siblings.
  StmtExprVisitor::VisitStmt_(op);
}

void IRVisitorWithAnalyzer::VisitExpr_(const CallNode* op) {
  // add condition context to if_then_else
  static const Op& if_then_else_op = Op::Get("tirx.if_then_else");
  if (op->op.same_as(if_then_else_op)) {
    PrimExpr cond = op->args[0].as_or_throw<PrimExpr>();
    this->VisitExpr(cond);
    constraint_scope_.WithNewScope([&]() {
      constraint_scope_.Current().Emplace(analyzer_, cond);
      this->VisitExpr(op->args[1]);
    });
    constraint_scope_.WithNewScope([&]() {
      constraint_scope_.Current().Emplace(analyzer_, analyzer_->rewrite_simplify(Not(cond)));
      this->VisitExpr(op->args[2]);
    });
  } else {
    StmtExprVisitor::VisitExpr_(op);
  }
}

void IRVisitorWithAnalyzer::VisitExpr_(const LetNode* op) {
  this->VisitExpr(op->value);
  analyzer_->Bind(op->var, op->value);
  this->VisitExpr(op->body);
}

void IRVisitorWithAnalyzer::VisitExpr_(const ReduceNode* op) {
  for (const IterVar& iv : op->axis) {
    analyzer_->Bind(iv->var, iv->dom);
  }
  StmtExprVisitor::VisitExpr_(op);
}

PrimExpr IRVisitorWithAnalyzer::ExtractRealCondition(PrimExpr condition) const {
  if (auto call = condition.as<CallNode>()) {
    if (call->op.same_as(builtin::likely())) {
      return call->args[0].as_or_throw<PrimExpr>();
    }
  }

  return condition;
}

}  // namespace arith
}  // namespace tvm
