1/*
2 * Licensed to the Apache Software Foundation (ASF) under one
3 * or more contributor license agreements. See the NOTICE file
4 * distributed with this work for additional information
5 * regarding copyright ownership. The ASF licenses this file
6 * to you under the Apache License, Version 2.0 (the
7 * "License"); you may not use this file except in compliance
8 * with the License. You may obtain a copy of the License at
9 *
10 * http://www.apache.org/licenses/LICENSE-2.0
11 *
12 * Unless required by applicable law or agreed to in writing,
13 * software distributed under the License is distributed on an
14 * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
15 * KIND, either express or implied. See the License for the
16 * specific language governing permissions and limitations
17 * under the License.
18 */
19
20/*!
21 * \file codegen_aocl.cc
22 */
23#include <tvm/target/target.h>
24
25#include <string>
26#include <vector>
27
28#include "../../runtime/file_utils.h"
29#include "../../runtime/opencl/aocl/aocl_module.h"
30#include "../build_common.h"
31#include "codegen_opencl.h"
32
33namespace tvm {
34namespace codegen {
35
36runtime::Module BuildAOCL(IRModule mod, Target target, bool emulation) {
37 // Get code.
38 using tvm::runtime::Registry;
39 bool output_ssa = false;
40 CodeGenOpenCL cg;
41 cg.Init(output_ssa);
42
43 for (auto kv : mod->functions) {
44 ICHECK(kv.second->IsInstance<PrimFuncNode>()) << "CodegenOpenCL: Can only take PrimFunc";
45 auto f = Downcast<PrimFunc>(kv.second);
46 auto calling_conv = f->GetAttr<Integer>(tvm::attr::kCallingConv);
47 ICHECK(calling_conv == CallingConv::kDeviceKernelLaunch)
48 << "CodegenOpenCL: expect calling_conv equals CallingConv::kDeviceKernelLaunch";
49 cg.AddFunction(f);
50 }
51
52 std::string code = cg.Finish();
53 if (const auto* f = Registry::Get("tvm_callback_opencl_postproc")) {
54 code = (*f)(code).operator std::string();
55 }
56
57 // Write a .cl file.
58 runtime::SaveBinaryToFile("aocl.cl", code.c_str());
59
60 // Compile the .cl file.
61 std::string cmd = "aoc aocl.cl";
62 // AOCL supports fp64.
63 cmd += " -Dcl_khr_fp64";
64 Optional<String> device = target->GetAttr<String>("device");
65 if (device.defined()) {
66 cmd += " -board=" + device.value();
67 }
68 if (emulation) {
69 cmd += " -march=emulator";
70 }
71 if (system(cmd.c_str()) != 0) {
72 LOG(FATAL) << "OpenCL offline compilation error.";
73 }
74
75 // Read .aocx file
76 std::string aocxbin;
77 runtime::LoadBinaryFromFile("aocl.aocx", &aocxbin);
78
79 return AOCLModuleCreate(aocxbin, "aocx", ExtractFuncInfo(mod), code);
80}
81
82TVM_REGISTER_GLOBAL("target.build.aocl")
83 .set_body_typed([](IRModule mod, Target target) -> runtime::Module {
84 return BuildAOCL(mod, target, false);
85 });
86
87TVM_REGISTER_GLOBAL("target.build.aocl_sw_emu")
88 .set_body_typed([](IRModule mod, Target target) -> runtime::Module {
89 return BuildAOCL(mod, target, true);
90 });
91
92} // namespace codegen
93} // namespace tvm
94