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 BasicBlock 19 attr_reader :index, :function, :preds, :instructions 20 attr_reader :true_succ, :false_succ 21 22 def initialize(index, function) 23 @instructions = [] 24 @index = index 25 @function = function 26 @true_succ = nil 27 @false_succ = nil 28 @preds = [] 29 @variables = {} 30 end 31 32 def last_instruction 33 @instructions[-1] 34 end 35 36 def empty? 37 @instructions.empty? 38 end 39 40 def terminator? 41 !empty? && @instructions[-1].terminator? 42 end 43 44 def append(inst) 45 if inst.IsWhilePhi? 46 @instructions.prepend(inst) 47 else 48 @instructions << inst 49 end 50 end 51 52 def set_variable(var, inst) 53 @variables[var.to_sym] = inst 54 end 55 56 def set_successor(dir, bb) 57 if dir 58 @true_succ = bb 59 else 60 @false_succ = bb 61 end 62 bb.add_predecessor(self) 63 end 64 65 def set_true_succ(bb) 66 set_successor(true, bb) 67 end 68 69 def set_false_succ(bb) 70 set_successor(false, bb) 71 end 72 73 def add_predecessor(bb) 74 @preds << bb 75 end 76 77 def emit_ir 78 strue_str = @true_succ.nil? ? "-1" : @true_succ.index.to_s 79 sfalse_str = @false_succ.nil? ? "" : ", #{@false_succ.index}" 80 Output.printlni("BASIC_BLOCK(#{index}, #{strue_str}#{sfalse_str}) {") 81 @instructions.each(&:emit_ir) 82 Output.printlnd("}") 83 end 84 85 def generate_builder 86 @instructions.each(&:generate_builder) 87 end 88end 89