/*
 * 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 intrin_rule_llvm.h
 * \brief Common utilities for llvm intrinsics.
 */
#ifndef TVM_TARGET_LLVM_INTRIN_RULE_LLVM_H_
#define TVM_TARGET_LLVM_INTRIN_RULE_LLVM_H_

#ifdef TVM_LLVM_VERSION

#include <llvm/IR/Intrinsics.h>
#include <tvm/ffi/function.h>
#include <tvm/target/codegen.h>
#include <tvm/tirx/builtin.h>
#include <tvm/tirx/expr.h>

#include "llvm_instance.h"

namespace tvm {
namespace codegen {
// num_signature means number of arguments used to query signature
template <unsigned id, int num_signature>
inline PrimExpr DispatchLLVMPureIntrin(const PrimExpr& e) {
  const CallNode* call = e.as<CallNode>();
  TVM_FFI_ICHECK(call != nullptr);
  ffi::Array<PrimExpr> cargs;
  // intrin id.
  cargs.push_back(IntImm(PrimType::UInt(32), id));
  TVM_FFI_ICHECK_EQ(call->args.size(), num_signature)
      << "llvm.call_llvm_intrin" << llvmGetIntrinName(id) << "expects " << num_signature
      << " arguments, but got " << call->args.size();

  for (PrimExpr arg : call->args.as_or_throw<ffi::Array<PrimExpr>>()) {
    cargs.push_back(arg);
  }
  return Call(call->ty.as_or_throw<PrimType>(), tirx::builtin::call_llvm_pure_intrin(), cargs)
      .as_or_throw<PrimExpr>();
}

template <unsigned id, int num_signature>
inline PrimExpr DispatchLLVMIntrin(const PrimExpr& e) {
  const CallNode* call = e.as<CallNode>();
  TVM_FFI_ICHECK(call != nullptr);
  ffi::Array<Expr> cargs;
  // intrin id.
  cargs.push_back(IntImm(PrimType::UInt(32), id));
  TVM_FFI_ICHECK_EQ(call->args.size(), num_signature)
      << "llvm.call_llvm_intrin" << llvmGetIntrinName(id) << "expects " << num_signature
      << " arguments, but got " << call->args.size();
  for (Expr arg : call->args) {
    cargs.push_back(arg);
  }
  return Call(call->ty.as_or_throw<PrimType>(), tirx::builtin::call_llvm_intrin(), cargs)
      .as_or_throw<PrimExpr>();
}

}  // namespace codegen
}  // namespace tvm

#endif  // LLVM_VERSION
#endif  // TVM_TARGET_LLVM_INTRIN_RULE_LLVM_H_
