package edu.gac.max.mcs388.s2002.compiler_support; /** The Register class is used to represent a pool from which * Registers can be allocated and to which they can then later be * deallocated. * * Some to-do items: * *

Written 7 Feb 1997 by * Max Hailperin * <max@gac.edu> */ public class RegisterAllocator{ Register[] pool; int inUse; /** The RegisterAllocator constructor takes a String prefix argument * that is used for constructing each Register. It also takes an * int number argument, which specifies how many registers there * will be. They are numbered consectively from 0. For example, * new RegisterAllocator("t", 10) will allocate * registers $t0 through $t9. */ public RegisterAllocator(String prefix, int number){ pool = new Register[number]; for(int i = 0; i < number; i++) pool[i] = new AllocatorOwnedRegister(prefix, i, this); inUse = 0; } public Register allocate(){ return pool[inUse++]; } public void deallocate(Register r) throws NotMyRegisterException{ if(!(r instanceof AllocatorOwnedRegister) || !((AllocatorOwnedRegister) r).ownedBy(this)){ throw new NotMyRegisterException(); } pool[--inUse] = r; } public void deallocateIfYours(Register r){ if((r instanceof AllocatorOwnedRegister) && ((AllocatorOwnedRegister) r).ownedBy(this)){ pool[--inUse] = r; } } } class AllocatorOwnedRegister extends Register{ RegisterAllocator owningAllocator; AllocatorOwnedRegister(String prefix, int num, RegisterAllocator owner){ super(prefix, num); owningAllocator = owner; } AllocatorOwnedRegister(String name, RegisterAllocator owner){ super(name); owningAllocator = owner; } boolean ownedBy(RegisterAllocator ra){ return ra == owningAllocator; } }