codegen_aocl.cc 2.49 KB
Newer Older
1 2 3 4 5 6 7 8
/*
 * 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
9
 *
10
 *   http://www.apache.org/licenses/LICENSE-2.0
11
 *
12 13 14 15 16 17 18 19
 * 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.
 */

20 21 22 23 24 25 26
/*!
 *  Copyright (c) 2018 by Contributors
 * \file codegen_aocl.cc
 */
#include <tvm/build_module.h>
#include <vector>
#include <string>
27 28
#include "codegen_opencl.h"
#include "build_common.h"
29 30 31 32 33 34
#include "../runtime/opencl/aocl/aocl_module.h"
#include "../runtime/file_util.h"

namespace tvm {
namespace codegen {

35 36
runtime::Module BuildAOCL(Array<LoweredFunc> funcs, std::string target_str,
                          bool emulation) {
37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53
  // Get code.
  using tvm::runtime::Registry;
  bool output_ssa = false;
  CodeGenOpenCL cg;
  cg.Init(output_ssa);
  for (LoweredFunc f : funcs) {
    cg.AddFunction(f);
  }
  std::string code = cg.Finish();
  if (const auto* f = Registry::Get("tvm_callback_opencl_postproc")) {
    code = (*f)(code).operator std::string();
  }

  // Write a .cl file.
  runtime::SaveBinaryToFile("aocl.cl", code.c_str());

  // Compile the .cl file.
54
  std::string cmd = "aoc aocl.cl";
55 56
  // AOCL supports fp64.
  cmd += " -Dcl_khr_fp64";
57
  Target target = Target::Create(target_str);
58 59
  if (target->device_name != "") {
    cmd += " -board=" + target->device_name;
60
  }
61 62
  if (emulation) {
    cmd += " -march=emulator";
63 64 65 66 67 68 69 70 71 72 73 74 75 76
  }
  if (system(cmd.c_str()) != 0) {
    LOG(FATAL) << "OpenCL offline compilation error.";
  }

  // Read .aocx file
  std::string aocxbin;
  runtime::LoadBinaryFromFile("aocl.aocx", &aocxbin);

  return AOCLModuleCreate(aocxbin, "aocx", ExtractFuncInfo(funcs), code);
}

TVM_REGISTER_API("codegen.build_aocl")
.set_body([](TVMArgs args, TVMRetValue* rv) {
77 78 79 80 81 82
    *rv = BuildAOCL(args[0], args[1], false);
  });

TVM_REGISTER_API("codegen.build_aocl_sw_emu")
.set_body([](TVMArgs args, TVMRetValue* rv) {
    *rv = BuildAOCL(args[0], args[1], true);
83 84 85 86
  });

}  // namespace codegen
}  // namespace tvm