# Copyright (c) 2013 The Chromium Authors. All rights reserved.
# Use of this source code is governed by a BSD-style license that can be
# found in the LICENSE file.

import("//build/config/sanitizers/sanitizers.gni")
import("//build/config/win/visual_studio_version.gni")
import("//build/toolchain/goma.gni")
import("//build/toolchain/toolchain.gni")

# Should only be running on Windows.
assert(is_win)

# Setup the Visual Studio state.
#
# Its arguments are the VS path and the compiler wrapper tool. It will write
# "environment.x86" and "environment.x64" to the build directory and return a
# list to us.
gyp_win_tool_path =
    rebase_path("//tools/gyp/pylib/gyp/win_tool.py", root_build_dir)

if (use_goma) {
  goma_prefix = "$goma_dir/gomacc.exe "
} else {
  goma_prefix = ""
}

# This value will be inherited in the toolchain below.
concurrent_links = exec_script("../get_concurrent_links.py", [], "value")

# Copy the VS runtime DLL for the default toolchain to the root build directory
# so things will run.
if (current_toolchain == default_toolchain) {
  if (is_debug) {
    configuration_name = "Debug"
  } else {
    configuration_name = "Release"
  }
  exec_script("../../vs_toolchain.py",
              [
                "copy_dlls",
                rebase_path(root_build_dir),
                configuration_name,
                target_cpu,
              ])
}

# Parameters:
#  toolchain_cpu: current_cpu to pass as a build arg
#  toolchain_os: current_os to pass as a build arg
#  environment: File name of environment file.
template("msvc_toolchain") {
  if (defined(invoker.concurrent_links)) {
    concurrent_links = invoker.concurrent_links
  }

  env = invoker.environment

  if (invoker.is_clang && host_os != "win") {
    # This toolchain definition uses response files for compilations.  GN uses
    # the quoting rules of the host OS, while clang-cl always defaults to
    # cmd.exe quoting rules for parsing response files.  Tell clang-cl to use
    # POSIX quoting rules, so it can understand what GN generates.
    cl = "${invoker.cl} --rsp-quoting=posix"
  } else {
    cl = invoker.cl
  }

  if (use_lld) {
    if (host_os == "win") {
      lld_link = "lld-link.exe"
    } else {
      lld_link = "lld-link"
    }
    prefix = rebase_path("//third_party/llvm-build/Release+Asserts/bin",
                         root_build_dir)

    # lld-link includes a replacement for lib.exe that can produce thin
    # archives and understands bitcode (for lto builds).
    lib = "$prefix/$lld_link /lib /llvmlibthin"
    link = "$prefix/$lld_link"
  } else {
    lib = "lib.exe"
    link = "link.exe"
  }

  # If possible, pass system includes as flags to the compiler.  When that's
  # not possible, load a full environment file (containing %INCLUDE% and
  # %PATH%) -- e.g. 32-bit MSVS builds require %PATH% to be set and just passing
  # in a list of include directories isn't enough.
  if (defined(invoker.sys_include_flags)) {
    env_wrapper = ""
    sys_include_flags = "${invoker.sys_include_flags} "  # Note trailing space.
  } else {
    # clang-cl doesn't need this env hoop, so omit it there.
    assert(!invoker.is_clang)
    env_wrapper = "ninja -t msvc -e $env -- "  # Note trailing space.
    sys_include_flags = ""
  }

  toolchain(target_name) {
    # Make these apply to all tools below.
    lib_switch = ""
    lib_dir_switch = "/LIBPATH:"

    # Object files go in this directory.
    object_subdir = "{{target_out_dir}}/{{label_name}}"

    tool("cc") {
      rspfile = "{{output}}.rsp"
      precompiled_header_type = "msvc"
      pdbname = "{{target_out_dir}}/{{label_name}}_c.pdb"

      # Label names may have spaces in them so the pdbname must be quoted. The
      # source and output don't need to be quoted because GN knows they're a
      # full file name and will quote automatically when necessary.
      command = "$env_wrapper$cl /nologo /showIncludes /FC @$rspfile /c {{source}} /Fo{{output}} /Fd\"$pdbname\""
      depsformat = "msvc"
      description = "CC {{output}}"
      outputs = [
        "$object_subdir/{{source_name_part}}.obj",
      ]
      rspfile_content = "$sys_include_flags{{defines}} {{include_dirs}} {{cflags}} {{cflags_c}}"
    }

    tool("cxx") {
      rspfile = "{{output}}.rsp"
      precompiled_header_type = "msvc"

      # The PDB name needs to be different between C and C++ compiled files.
      pdbname = "{{target_out_dir}}/{{label_name}}_cc.pdb"

      # See comment in CC tool about quoting.
      command = "$env_wrapper$cl /nologo /showIncludes /FC @$rspfile /c {{source}} /Fo{{output}} /Fd\"$pdbname\""
      depsformat = "msvc"
      description = "CXX {{output}}"
      outputs = [
        "$object_subdir/{{source_name_part}}.obj",
      ]
      rspfile_content = "$sys_include_flags{{defines}} {{include_dirs}} {{cflags}} {{cflags_cc}}"
    }

    tool("rc") {
      command = "$python_path gyp-win-tool rc-wrapper $env rc.exe {{defines}} {{include_dirs}} /fo{{output}} {{source}}"
      outputs = [
        "$object_subdir/{{source_name_part}}.res",
      ]
      description = "RC {{output}}"
    }

    tool("asm") {
      if (invoker.toolchain_cpu == "x64") {
        ml = "ml64.exe"
      } else {
        ml = "ml.exe"
      }
      command = "$python_path gyp-win-tool asm-wrapper $env $ml {{defines}} {{include_dirs}} {{asmflags}} /c /Fo{{output}} {{source}}"
      description = "ASM {{output}}"
      outputs = [
        "$object_subdir/{{source_name_part}}.obj",
      ]
    }

    tool("alink") {
      rspfile = "{{output}}.rsp"
      command = "$python_path gyp-win-tool link-wrapper $env False $lib /nologo {{arflags}} /OUT:{{output}} @$rspfile"
      description = "LIB {{output}}"
      outputs = [
        # Ignore {{output_extension}} and always use .lib, there's no reason to
        # allow targets to override this extension on Windows.
        "{{output_dir}}/{{target_output_name}}.lib",
      ]
      default_output_extension = ".lib"
      default_output_dir = "{{target_out_dir}}"

      # The use of inputs_newline is to work around a fixed per-line buffer
      # size in the linker.
      rspfile_content = "{{inputs_newline}}"
    }

    tool("solink") {
      dllname = "{{output_dir}}/{{target_output_name}}{{output_extension}}"  # e.g. foo.dll
      libname = "${dllname}.lib"  # e.g. foo.dll.lib
      rspfile = "${dllname}.rsp"

      command = "$python_path gyp-win-tool link-wrapper $env False $link /nologo /IMPLIB:$libname /DLL /OUT:$dllname /PDB:${dllname}.pdb @$rspfile"

      default_output_extension = ".dll"
      default_output_dir = "{{root_out_dir}}"
      description = "LINK(DLL) {{output}}"
      outputs = [
        dllname,
        libname,
      ]
      link_output = libname
      depend_output = libname
      runtime_link_output = dllname

      # Since the above commands only updates the .lib file when it changes, ask
      # Ninja to check if the timestamp actually changed to know if downstream
      # dependencies should be recompiled.
      restat = true

      # The use of inputs_newline is to work around a fixed per-line buffer
      # size in the linker.
      rspfile_content = "{{libs}} {{solibs}} {{inputs_newline}} {{ldflags}}"
    }

    tool("solink_module") {
      dllname = "{{output_dir}}/{{target_output_name}}{{output_extension}}"  # e.g. foo.dll
      rspfile = "${dllname}.rsp"

      command = "$python_path gyp-win-tool link-wrapper $env False $link /nologo /DLL /OUT:$dllname /PDB:${dllname}.pdb @$rspfile"

      default_output_extension = ".dll"
      default_output_dir = "{{root_out_dir}}"
      description = "LINK_MODULE(DLL) {{output}}"
      outputs = [
        dllname,
      ]

      # The use of inputs_newline is to work around a fixed per-line buffer
      # size in the linker.
      rspfile_content = "{{libs}} {{solibs}} {{inputs_newline}} {{ldflags}}"
    }

    tool("link") {
      rspfile = "{{output}}.rsp"

      command = "$python_path gyp-win-tool link-wrapper $env False $link /nologo /OUT:{{output}} /PDB:{{output}}.pdb @$rspfile"

      default_output_extension = ".exe"
      default_output_dir = "{{root_out_dir}}"
      description = "LINK {{output}}"
      outputs = [
        "{{output_dir}}/{{target_output_name}}{{output_extension}}",
      ]

      # The use of inputs_newline is to work around a fixed per-line buffer
      # size in the linker.
      rspfile_content = "{{inputs_newline}} {{libs}} {{solibs}} {{ldflags}}"
    }

    # These two are really entirely generic, but have to be repeated in
    # each toolchain because GN doesn't allow a template to be used here.
    # See //build/toolchain/toolchain.gni for details.
    tool("stamp") {
      command = stamp_command
      description = stamp_description
    }
    tool("copy") {
      command = copy_command
      description = copy_description
    }

    # When invoking this toolchain not as the default one, these args will be
    # passed to the build. They are ignored when this is the default toolchain.
    toolchain_args() {
      current_cpu = invoker.toolchain_cpu
      if (defined(invoker.toolchain_os)) {
        current_os = invoker.toolchain_os
      }

      # These share a name with global variables that are already defined, and
      # forward_variables_from won't clobber the existing value, so we need to
      # set it explicitly.
      if (defined(invoker.is_clang)) {
        is_clang = invoker.is_clang
      }
      if (defined(invoker.is_component_build)) {
        is_component_build = invoker.is_component_build
      }

      # This value needs to be passed through unchanged.
      host_toolchain = host_toolchain
    }
  }
}

if (is_clang) {
  sys_include_prefix = "-imsvc"
} else {
  # MSVC doesn't have the concept of system headers.
  sys_include_prefix = "/I"
}

if (host_os == "win") {
  clang_cl = "clang-cl.exe"
} else {
  clang_cl = "clang-cl"
}

# 32-bit toolchains. Only define these when the target architecture is 32-bit
# since we don't do any 32-bit cross compiles when targeting 64-bit (the
# build does generate some 64-bit stuff from 32-bit target builds).
if (target_cpu == "x86") {
  x86_toolchain_data = exec_script("setup_toolchain.py",
                                   [
                                     visual_studio_path,
                                     gyp_win_tool_path,
                                     windows_sdk_path,
                                     visual_studio_runtime_dirs,
                                     "x86",
                                     "${sys_include_prefix}",
                                   ],
                                   "scope")

  msvc_toolchain("x86") {
    environment = "environment.x86"
    toolchain_cpu = "x86"
    cl = "${goma_prefix}\"${x86_toolchain_data.vc_bin_dir}/cl.exe\""
    is_clang = false
  }

  msvc_toolchain("clang_x86") {
    environment = "environment.x86"
    toolchain_cpu = "x86"
    prefix = rebase_path("//third_party/llvm-build/Release+Asserts/bin",
                         root_build_dir)
    cl = "${goma_prefix}$prefix/${clang_cl}"
    toolchain_os = "win"
    is_clang = true
    sys_include_flags = "${x86_toolchain_data.include_flags}"
  }
}

# 64-bit toolchains.
x64_toolchain_data = exec_script("setup_toolchain.py",
                                 [
                                   visual_studio_path,
                                   gyp_win_tool_path,
                                   windows_sdk_path,
                                   visual_studio_runtime_dirs,
                                   "x64",
                                   "${sys_include_prefix}",
                                 ],
                                 "scope")

template("win_x64_toolchains") {
  # TODO(mcgrathr): These assignments are only required because of
  # crbug.com/395883.  Drop them if that ever gets fixed in GN.
  concurrent_links = invoker.concurrent_links
  goma_prefix = invoker.goma_prefix
  x64_toolchain_data = invoker.x64_toolchain_data
  clang_cl = invoker.clang_cl

  msvc_toolchain(target_name) {
    environment = "environment.x64"
    toolchain_cpu = "x64"
    cl = "${goma_prefix}\"${x64_toolchain_data.vc_bin_dir}/cl.exe\""
    is_clang = false

    # This shares a name with a global and forward_variables_from won't clobber
    # the existing value, so we need to set it explicitly.
    if (defined(invoker.is_component_build)) {
      is_component_build = invoker.is_component_build
    }
  }

  msvc_toolchain("clang_" + target_name) {
    environment = "environment.x64"
    toolchain_cpu = "x64"
    prefix = rebase_path("//third_party/llvm-build/Release+Asserts/bin",
                         root_build_dir)
    cl = "${goma_prefix}$prefix/${clang_cl}"
    toolchain_os = "win"
    is_clang = true
    sys_include_flags = "${x64_toolchain_data.include_flags}"

    # This shares a name with a global and forward_variables_from won't clobber
    # the existing value, so we need to set it explicitly.
    if (defined(invoker.is_component_build)) {
      is_component_build = invoker.is_component_build
    }
  }
}

win_x64_toolchains("x64") {
  # TODO(mcgrathr): These assignments are only required because of
  # crbug.com/395883.  Drop them if that ever gets fixed in GN.
  concurrent_links = concurrent_links
  goma_prefix = goma_prefix
  x64_toolchain_data = x64_toolchain_data
}

# The nacl_win64 toolchain is nearly identical to the plain x64 toolchain.
# It's used solely for building nacl64.exe (//components/nacl/broker:nacl64).
# The only reason it's a separate toolchain is so that it can force
# is_component_build to false in the toolchain_args() block, because
# building nacl64.exe in component style does not work.
win_x64_toolchains("nacl_win64") {
  is_component_build = false

  # TODO(mcgrathr): These assignments are only required because of
  # crbug.com/395883.  Drop them if that ever gets fixed in GN.
  concurrent_links = concurrent_links
  goma_prefix = goma_prefix
  x64_toolchain_data = x64_toolchain_data
  clang_cl = clang_cl
}

# WinRT toolchains. Only define these when targeting them.
#
# NOTE: This is currently broken because it references vc_bin_dir. brettw@
# changed this around a bit, and I don't know what this should be set to
# in terms of what setup_toolchain returns for a certain CPU architecture.
if (target_os == "winrt_81" || target_os == "winrt_81_phone" ||
    target_os == "winrt_10") {
  msvc_toolchain("winrt_x86") {
    environment = "environment.winrt_x86"
    cl = "${goma_prefix}\"${vc_bin_dir}/cl.exe\""
    is_clang = false

    toolchain_cpu = "x86"
    toolchain_os = current_os
  }

  msvc_toolchain("winrt_x64") {
    environment = "environment.winrt_x64"
    cl = "${goma_prefix}\"${vc_bin_dir}/cl.exe\""
    is_clang = false

    toolchain_cpu = "x64"
    toolchain_os = current_os
  }
}