• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1#!/usr/bin/env ruby
2
3# Copyright (c) 2021-2022 Huawei Device Co., Ltd.
4# Licensed under the Apache License, Version 2.0 (the "License");
5# you may not use this file except in compliance with the License.
6# You may obtain a copy of the License at
7#
8# http://www.apache.org/licenses/LICENSE-2.0
9#
10# Unless required by applicable law or agreed to in writing, software
11# distributed under the License is distributed on an "AS IS" BASIS,
12# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13# See the License for the specific language governing permissions and
14# limitations under the License.
15
16require_relative 'output'
17
18class CppFunction
19  attr_reader :variants
20
21  def initialize(name)
22    @name = name
23    @variants = []
24  end
25
26  def condition(cond)
27    @current_variant.cond = cond
28  end
29
30  def code(&block)
31    @current_variant.func = Function.new(@current_variant.name, params: @params, mode: [:IrInline], &block)
32    @current_variant.func.compile
33  end
34
35  def params(**kwargs)
36    @params = kwargs
37  end
38
39  def return_type(type)
40    @return_type = type
41  end
42
43  def variant(name, &block)
44    @current_variant = OpenStruct.new({condition: nil, name: name, func: nil})
45    @variants << @current_variant
46    self.instance_eval(&block)
47  end
48
49  def generate_ir(gen)
50    @variants.each { |x| gen.generate_function(x.func) }
51
52    params = "IntrinsicInst *inst, #{@params.keys.map { |x| "AnyBaseType #{x}"}.join(', ')}"
53    Output.scoped_puts "inline #{@return_type} #{@name}(#{params}) {" do
54      @variants.each do |variant|
55        Output.scoped_puts "if (#{variant.cond}) {" do
56          Output << "return #{variant.name}(inst);"
57        end
58      end
59      Output << "return false;"
60    end
61  end
62end