summaryrefslogtreecommitdiff
path: root/plugins/java-decompiler/engine/src/org/jetbrains/java/decompiler/modules/decompiler/decompose/FastExtendedPostdominanceHelper.java
blob: f029016e5efef8985a6b302acf0429e2e4584910 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
/*
 * Copyright 2000-2014 JetBrains s.r.o.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package org.jetbrains.java.decompiler.modules.decompiler.decompose;

import org.jetbrains.java.decompiler.modules.decompiler.StatEdge;
import org.jetbrains.java.decompiler.modules.decompiler.stats.Statement;
import org.jetbrains.java.decompiler.util.FastFixedSetFactory;
import org.jetbrains.java.decompiler.util.FastFixedSetFactory.FastFixedSet;
import org.jetbrains.java.decompiler.util.InterpreterUtil;

import java.util.*;
import java.util.Map.Entry;

public class FastExtendedPostdominanceHelper {

  private List<Statement> lstReversePostOrderList;

  private HashMap<Integer, FastFixedSet<Integer>> mapSupportPoints = new HashMap<Integer, FastFixedSet<Integer>>();

  private HashMap<Integer, FastFixedSet<Integer>> mapExtPostdominators = new HashMap<Integer, FastFixedSet<Integer>>();

  private Statement statement;

  private FastFixedSetFactory<Integer> factory;

  public HashMap<Integer, Set<Integer>> getExtendedPostdominators(Statement statement) {

    this.statement = statement;

    HashSet<Integer> set = new HashSet<Integer>();
    for (Statement st : statement.getStats()) {
      set.add(st.id);
    }
    this.factory = new FastFixedSetFactory<Integer>(set);

    lstReversePostOrderList = statement.getReversePostOrderList();

    //		try {
    //			DotExporter.toDotFile(statement, new File("c:\\Temp\\stat1.dot"));
    //		} catch (Exception ex) {
    //			ex.printStackTrace();
    //		}

    calcDefaultReachableSets();

    removeErroneousNodes();

    DominatorTreeExceptionFilter filter = new DominatorTreeExceptionFilter(statement);
    filter.initialize();

    filterOnExceptionRanges(filter);

    filterOnDominance(filter);

    HashMap<Integer, Set<Integer>> res = new HashMap<Integer, Set<Integer>>();
    for (Entry<Integer, FastFixedSet<Integer>> entry : mapExtPostdominators.entrySet()) {
      res.put(entry.getKey(), entry.getValue().toPlainSet());
    }

    return res;
  }


  private void filterOnDominance(DominatorTreeExceptionFilter filter) {

    DominatorEngine engine = filter.getDomEngine();

    for (Integer head : new HashSet<Integer>(mapExtPostdominators.keySet())) {

      FastFixedSet<Integer> setPostdoms = mapExtPostdominators.get(head);

      LinkedList<Statement> stack = new LinkedList<Statement>();
      LinkedList<FastFixedSet<Integer>> stackPath = new LinkedList<FastFixedSet<Integer>>();

      stack.add(statement.getStats().getWithKey(head));
      stackPath.add(factory.spawnEmptySet());

      Set<Statement> setVisited = new HashSet<Statement>();

      while (!stack.isEmpty()) {

        Statement stat = stack.removeFirst();
        FastFixedSet<Integer> path = stackPath.removeFirst();

        if (setPostdoms.contains(stat.id)) {
          path.add(stat.id);
        }

        if (path.contains(setPostdoms)) {
          continue;
        }

        setVisited.add(stat);

        int domflag = 0;

        for (Iterator<Integer> it = setPostdoms.iterator(); it.hasNext(); ) {
          Integer post = it.next();

          if (!path.contains(post)) {
            if (domflag == 0) {
              domflag = engine.isDominator(stat.id, head) ? 2 : 1;
            }

            if (domflag == 1) { // not a dominator
              it.remove();
            }
          }
        }

        for (StatEdge edge : stat.getSuccessorEdges(StatEdge.TYPE_REGULAR)) {
          if (!setVisited.contains(edge.getDestination())) {
            stack.add(edge.getDestination());
            stackPath.add(path.getCopy());
          }
        }
      }

      if (setPostdoms.isEmpty()) {
        mapExtPostdominators.remove(head);
      }
    }
  }


  private void filterOnExceptionRanges(DominatorTreeExceptionFilter filter) {


    for (Integer head : new HashSet<Integer>(mapExtPostdominators.keySet())) {

      FastFixedSet<Integer> set = mapExtPostdominators.get(head);
      for (Iterator<Integer> it = set.iterator(); it.hasNext(); ) {
        if (!filter.acceptStatementPair(head, it.next())) {
          it.remove();
        }
      }
      if (set.isEmpty()) {
        mapExtPostdominators.remove(head);
      }
    }
  }


  private void removeErroneousNodes() {

    mapSupportPoints = new HashMap<Integer, FastFixedSet<Integer>>();

    calcReachabilitySuppPoints(StatEdge.TYPE_REGULAR);

    iterateReachability(new IReachabilityAction() {
      public boolean action(Statement node, HashMap<Integer, FastFixedSet<Integer>> mapSets) {

        Integer nodeid = node.id;

        FastFixedSet<Integer> setReachability = mapSets.get(nodeid);
        List<FastFixedSet<Integer>> lstPredSets = new ArrayList<FastFixedSet<Integer>>();

        for (StatEdge prededge : node.getPredecessorEdges(StatEdge.TYPE_REGULAR)) {
          FastFixedSet<Integer> setPred = mapSets.get(prededge.getSource().id);
          if (setPred == null) {
            setPred = mapSupportPoints.get(prededge.getSource().id);
          }

          // setPred cannot be empty as it is a reachability set
          lstPredSets.add(setPred);
        }

        for (Integer id : setReachability.toPlainSet()) {

          FastFixedSet<Integer> setReachabilityCopy = setReachability.getCopy();

          FastFixedSet<Integer> setIntersection = factory.spawnEmptySet();
          boolean isIntersectionInitialized = false;

          for (FastFixedSet<Integer> predset : lstPredSets) {
            if (predset.contains(id)) {
              if (!isIntersectionInitialized) {
                setIntersection.union(predset);
                isIntersectionInitialized = true;
              }
              else {
                setIntersection.intersection(predset);
              }
            }
          }

          if (nodeid != id.intValue()) {
            setIntersection.add(nodeid);
          }
          else {
            setIntersection.remove(nodeid);
          }

          setReachabilityCopy.complement(setIntersection);

          mapExtPostdominators.get(id).complement(setReachabilityCopy);
        }

        return false;
      }
    }, StatEdge.TYPE_REGULAR);

    // exception handlers cannot be postdominator nodes
    // TODO: replace with a standard set?
    FastFixedSet<Integer> setHandlers = factory.spawnEmptySet();
    boolean handlerfound = false;

    for (Statement stat : statement.getStats()) {
      if (stat.getPredecessorEdges(Statement.STATEDGE_DIRECT_ALL).isEmpty() &&
          !stat.getPredecessorEdges(StatEdge.TYPE_EXCEPTION).isEmpty()) { // exception handler
        setHandlers.add(stat.id);
        handlerfound = true;
      }
    }

    if (handlerfound) {
      for (FastFixedSet<Integer> set : mapExtPostdominators.values()) {
        set.complement(setHandlers);
      }
    }
  }


  private void calcDefaultReachableSets() {

    int edgetype = StatEdge.TYPE_REGULAR | StatEdge.TYPE_EXCEPTION;

    calcReachabilitySuppPoints(edgetype);

    for (Statement stat : statement.getStats()) {
      mapExtPostdominators.put(stat.id, factory.spawnEmptySet());
    }

    iterateReachability(new IReachabilityAction() {
      public boolean action(Statement node, HashMap<Integer, FastFixedSet<Integer>> mapSets) {

        Integer nodeid = node.id;
        FastFixedSet<Integer> setReachability = mapSets.get(nodeid);

        for (Integer id : setReachability.toPlainSet()) {
          mapExtPostdominators.get(id).add(nodeid);
        }

        return false;
      }
    }, edgetype);
  }


  private void calcReachabilitySuppPoints(final int edgetype) {

    iterateReachability(new IReachabilityAction() {
      public boolean action(Statement node, HashMap<Integer, FastFixedSet<Integer>> mapSets) {

        // consider to be a support point
        for (StatEdge sucedge : node.getAllSuccessorEdges()) {
          if ((sucedge.getType() & edgetype) != 0) {
            if (mapSets.containsKey(sucedge.getDestination().id)) {
              FastFixedSet<Integer> setReachability = mapSets.get(node.id);

              if (!InterpreterUtil.equalObjects(setReachability, mapSupportPoints.get(node.id))) {
                mapSupportPoints.put(node.id, setReachability);
                return true;
              }
            }
          }
        }

        return false;
      }
    }, edgetype);
  }

  private void iterateReachability(IReachabilityAction action, int edgetype) {

    while (true) {

      boolean iterate = false;

      HashMap<Integer, FastFixedSet<Integer>> mapSets = new HashMap<Integer, FastFixedSet<Integer>>();

      for (Statement stat : lstReversePostOrderList) {

        FastFixedSet<Integer> set = factory.spawnEmptySet();
        set.add(stat.id);

        for (StatEdge prededge : stat.getAllPredecessorEdges()) {
          if ((prededge.getType() & edgetype) != 0) {
            Statement pred = prededge.getSource();

            FastFixedSet<Integer> setPred = mapSets.get(pred.id);
            if (setPred == null) {
              setPred = mapSupportPoints.get(pred.id);
            }

            if (setPred != null) {
              set.union(setPred);
            }
          }
        }

        mapSets.put(stat.id, set);

        if (action != null) {
          iterate |= action.action(stat, mapSets);
        }

        // remove reachability information of fully processed nodes (saves memory)
        for (StatEdge prededge : stat.getAllPredecessorEdges()) {
          if ((prededge.getType() & edgetype) != 0) {
            Statement pred = prededge.getSource();

            if (mapSets.containsKey(pred.id)) {
              boolean remstat = true;
              for (StatEdge sucedge : pred.getAllSuccessorEdges()) {
                if ((sucedge.getType() & edgetype) != 0) {
                  if (!mapSets.containsKey(sucedge.getDestination().id)) {
                    remstat = false;
                    break;
                  }
                }
              }

              if (remstat) {
                mapSets.put(pred.id, null);
              }
            }
          }
        }
      }

      if (!iterate) {
        break;
      }
    }
  }


  private interface IReachabilityAction {
    boolean action(Statement node, HashMap<Integer, FastFixedSet<Integer>> mapSets);
  }
}