emscripten.py 2.48 KB
Newer Older
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16
# 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.
17 18 19
"""Util to invoke emscripten compilers in the system."""
# pylint: disable=invalid-name
from __future__ import absolute_import as _abs
20

21
import subprocess
22
from .._ffi.base import py_str
23 24 25 26 27
from .._ffi.libinfo import find_lib_path

def create_js(output,
              objects,
              options=None,
28
              side_module=False,
29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47
              cc="emcc"):
    """Create emscripten javascript library.

    Parameters
    ----------
    output : str
        The target shared library.

    objects : list
        List of object files.

    options : str
        The additional options.

    cc : str, optional
        The compile string.
    """
    cmd = [cc]
    cmd += ["-Oz"]
48 49 50 51 52 53 54
    if not side_module:
        cmd += ["-s", "RESERVED_FUNCTION_POINTERS=2"]
        cmd += ["-s", "NO_EXIT_RUNTIME=1"]
        extra_methods = ['cwrap', 'getValue', 'setValue', 'addFunction']
        cfg = "[" + (','.join("\'%s\'" % x for x in extra_methods)) + "]"
        cmd += ["-s", "EXTRA_EXPORTED_RUNTIME_METHODS=" + cfg]
    else:
55
        cmd += ["-s", "SIDE_MODULE=1"]
56
    cmd += ["-o", output]
57 58 59 60 61 62
    objects = [objects] if isinstance(objects, str) else objects
    with_runtime = False
    for obj in objects:
        if obj.find("libtvm_web_runtime.bc") != -1:
            with_runtime = True

63
    if not with_runtime and not side_module:
64 65 66 67 68 69 70 71
        objects += [find_lib_path("libtvm_web_runtime.bc")[0]]

    cmd += objects

    if options:
        cmd += options

    proc = subprocess.Popen(
72
        cmd,
73 74 75 76 77 78
        stdout=subprocess.PIPE,
        stderr=subprocess.STDOUT)
    (out, _) = proc.communicate()

    if proc.returncode != 0:
        msg = "Compilation error:\n"
79
        msg += py_str(out)
80
        raise RuntimeError(msg)
81 82

create_js.object_format = "bc"