/*
 * 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/target/canonicalizer/llvm/arm_mprofile.cc
 * \brief Target canonicalizer for Arm(R) Cortex(R) M-Profile CPUs
 */

#include "arm_mprofile.h"

#include <string>

namespace tvm {
namespace target {
namespace canonicalizer {
namespace llvm {
namespace mprofile {

const ffi::Map<ffi::String, ffi::Any> kNoExt = {{"feature.has_dsp", false},
                                                {"feature.has_mve", false}};
const ffi::Map<ffi::String, ffi::Any> kHasDSP = {{"feature.has_dsp", true},
                                                 {"feature.has_mve", false}};
const ffi::Map<ffi::String, ffi::Any> kHasMVE = {{"feature.has_dsp", true},
                                                 {"feature.has_mve", true}};

static const char* baseCPUs[] = {"cortex-m0", "cortex-m3"};
static const char* dspCPUs[] = {"cortex-m55", "cortex-m4",   "cortex-m7",
                                "cortex-m33", "cortex-m35p", "cortex-m85"};
static const char* mveCPUs[] = {"cortex-m55", "cortex-m85"};

template <typename Container>
static inline bool MatchesCpu(ffi::Optional<ffi::String> mcpu, const Container& cpus) {
  if (!mcpu) {
    return false;
  }
  std::string mcpu_string = mcpu.value();
  auto matches_cpu = [mcpu_string](const char* cpu) { return mcpu_string.find(cpu) == 0; };
  return std::find_if(std::begin(cpus), std::end(cpus), matches_cpu) != std::end(cpus);
}

static inline bool HasFlag(ffi::String attr, std::string flag) {
  std::string attr_str = attr;
  return attr_str.find(flag) != std::string::npos;
}

static inline bool HasFlag(ffi::Optional<ffi::String> attr, std::string flag) {
  if (!attr) {
    return false;
  }
  return HasFlag(attr.value(), flag);
}

static inline bool HasFlag(ffi::Optional<ffi::Array<ffi::String>> attr, std::string flag) {
  if (!attr) {
    return false;
  }
  ffi::Array<ffi::String> attr_array = attr.value();

  auto matching_attr =
      std::find_if(attr_array.begin(), attr_array.end(),
                   [flag](ffi::String attr_str) { return HasFlag(attr_str, flag); });
  return matching_attr != attr_array.end();
}

bool IsArch(ffi::Map<ffi::String, ffi::Any> attrs) {
  ffi::Optional<ffi::String> mcpu =
      attrs.Get("mcpu").value_or(nullptr).as_or_throw<ffi::Optional<ffi::String>>();
  if (mcpu) {
    bool matches_base = MatchesCpu(mcpu, baseCPUs);
    bool matches_dsp = MatchesCpu(mcpu, dspCPUs);
    bool matches_mve = MatchesCpu(mcpu, mveCPUs);
    return matches_base || matches_mve || matches_dsp;
  }
  return false;
}

static ffi::Map<ffi::String, ffi::Any> GetFeatures(ffi::Map<ffi::String, ffi::Any> target) {
  ffi::Optional<ffi::String> mcpu =
      target.Get("mcpu").value_or(nullptr).as_or_throw<ffi::Optional<ffi::String>>();
  ffi::Optional<ffi::Array<ffi::String>> mattr =
      target.Get("mattr").value_or(nullptr).as_or_throw<ffi::Optional<ffi::Array<ffi::String>>>();

  bool nomve = HasFlag(mcpu, "+nomve") || HasFlag(mattr, "+nomve");
  bool nodsp = HasFlag(mcpu, "+nodsp") || HasFlag(mattr, "+nodsp");

  bool has_mve = MatchesCpu(mcpu, mveCPUs);
  if (has_mve && !nomve && !nodsp) {
    return kHasMVE;
  }

  bool has_dsp = MatchesCpu(mcpu, dspCPUs);
  if (has_dsp && !nodsp) {
    return kHasDSP;
  }

  return kNoExt;
}

static ffi::Array<ffi::String> MergeKeys(ffi::Optional<ffi::Array<ffi::String>> existing_keys) {
  const ffi::Array<ffi::String> kExtraKeys = {"arm_cpu", "cpu"};

  if (!existing_keys) {
    return kExtraKeys;
  }

  ffi::Array<ffi::String> keys = existing_keys.value();
  for (ffi::String key : kExtraKeys) {
    if (std::find(keys.begin(), keys.end(), key) == keys.end()) {
      keys.push_back(key);
    }
  }
  return keys;
}

ffi::Map<ffi::String, ffi::Any> Canonicalize(ffi::Map<ffi::String, ffi::Any> target) {
  ffi::Map<ffi::String, ffi::Any> features = GetFeatures(target);
  for (const auto& kv : features) {
    target.Set(kv.first, kv.second);
  }
  target.Set("keys", MergeKeys((target.Get("keys"))
                                   .value_or(nullptr)
                                   .as_or_throw<ffi::Optional<ffi::Array<ffi::String>>>()));

  return target;
}

}  // namespace mprofile
}  // namespace llvm
}  // namespace canonicalizer
}  // namespace target
}  // namespace tvm
