1. /*
  2. * Copyright 2001-2004 The Apache Software Foundation.
  3. *
  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. */
  16. /*
  17. * $Id: SlotAllocator.java,v 1.6 2004/02/16 22:26:44 minchau Exp $
  18. */
  19. package com.sun.org.apache.xalan.internal.xsltc.compiler.util;
  20. import com.sun.org.apache.bcel.internal.generic.LocalVariableGen;
  21. import com.sun.org.apache.bcel.internal.generic.Type;
  22. /**
  23. * @author Jacek Ambroziak
  24. */
  25. final class SlotAllocator {
  26. private int _firstAvailableSlot;
  27. private int _size = 8;
  28. private int _free = 0;
  29. private int[] _slotsTaken = new int[_size];
  30. public void initialize(LocalVariableGen[] vars) {
  31. final int length = vars.length;
  32. int slot = 0, size, index;
  33. for (int i = 0; i < length; i++) {
  34. size = vars[i].getType().getSize();
  35. index = vars[i].getIndex();
  36. slot = Math.max(slot, index + size);
  37. }
  38. _firstAvailableSlot = slot;
  39. }
  40. public int allocateSlot(Type type) {
  41. final int size = type.getSize();
  42. final int limit = _free;
  43. int slot = _firstAvailableSlot, where = 0;
  44. if (_free + size > _size) {
  45. final int[] array = new int[_size *= 2];
  46. for (int j = 0; j < limit; j++)
  47. array[j] = _slotsTaken[j];
  48. _slotsTaken = array;
  49. }
  50. while (where < limit) {
  51. if (slot + size <= _slotsTaken[where]) {
  52. // insert
  53. for (int j = limit - 1; j >= where; j--)
  54. _slotsTaken[j + size] = _slotsTaken[j];
  55. break;
  56. }
  57. else {
  58. slot = _slotsTaken[where++] + 1;
  59. }
  60. }
  61. for (int j = 0; j < size; j++)
  62. _slotsTaken[where + j] = slot + j;
  63. _free += size;
  64. return slot;
  65. }
  66. public void releaseSlot(LocalVariableGen lvg) {
  67. final int size = lvg.getType().getSize();
  68. final int slot = lvg.getIndex();
  69. final int limit = _free;
  70. for (int i = 0; i < limit; i++) {
  71. if (_slotsTaken[i] == slot) {
  72. int j = i + size;
  73. while (j < limit) {
  74. _slotsTaken[i++] = _slotsTaken[j++];
  75. }
  76. _free -= size;
  77. return;
  78. }
  79. }
  80. String state = "Variable slot allocation error"+
  81. "(size="+size+", slot="+slot+", limit="+limit+")";
  82. ErrorMsg err = new ErrorMsg(ErrorMsg.INTERNAL_ERR, state);
  83. throw new Error(err.toString());
  84. }
  85. }