Debian Codegraph @

rhino/src/org/mozilla/javascript/optimizer/Block.java

raw symbols SCIP
1 /* This Source Code Form is subject to the terms of the Mozilla Public
2 * License, v. 2.0. If a copy of the MPL was not distributed with this
3 * file, You can obtain one at http://mozilla.org/MPL/2.0/. */
4
5 package org.mozilla.javascript.optimizer;
6
7 import org.mozilla.javascript.*;
8 import org.mozilla.javascript.ast.Jump;
9
10 import java.util.BitSet;
11 import java.util.HashMap;
12 import java.util.Map;
13
14 import java.io.PrintWriter;
15 import java.io.StringWriter;
16
17 class Block
18 {
19
20 private static class FatBlock
21 {
22
23 private static Block[] reduceToArray(ObjToIntMap map)
24 {
25 Block[] result = null;
26 if (!map.isEmpty()) {
27 result = new Block[map.size()];
28 int i = 0;
29 ObjToIntMap.Iterator iter = map.newIterator();
30 for (iter.start(); !iter.done(); iter.next()) {
31 FatBlock fb = (FatBlock)(iter.getKey());
32 result[i++] = fb.realBlock;
33 }
34 }
35 return result;
36 }
37
38 void addSuccessor(FatBlock b) { successors.put(b, 0); }
39 void addPredecessor(FatBlock b) { predecessors.put(b, 0); }
40
41 Block[] getSuccessors() { return reduceToArray(successors); }
42 Block[] getPredecessors() { return reduceToArray(predecessors); }
43
44 // all the Blocks that come immediately after this
45 private ObjToIntMap successors = new ObjToIntMap();
46 // all the Blocks that come immediately before this
47 private ObjToIntMap predecessors = new ObjToIntMap();
48
49 Block realBlock;
50 }
51
52 Block(int startNodeIndex, int endNodeIndex)
53 {
54 itsStartNodeIndex = startNodeIndex;
55 itsEndNodeIndex = endNodeIndex;
56 }
57
58 static void runFlowAnalyzes(OptFunctionNode fn, Node[] statementNodes)
59 {
60 int paramCount = fn.fnode.getParamCount();
61 int varCount = fn.fnode.getParamAndVarCount();
62 int[] varTypes = new int[varCount];
63 // If the variable is a parameter, it could have any type.
64 for (int i = 0; i != paramCount; ++i) {
65 varTypes[i] = Optimizer.AnyType;
66 }
67 // If the variable is from a "var" statement, its typeEvent will be set
68 // when we see the setVar node.
69 for (int i = paramCount; i != varCount; ++i) {
70 varTypes[i] = Optimizer.NoType;
71 }
72
73 Block[] theBlocks = buildBlocks(statementNodes);
74
75 if (DEBUG) {
76 ++debug_blockCount;
77 System.out.println("-------------------"+fn.fnode.getFunctionName()+" "+debug_blockCount+"--------");
78 System.out.println(fn.fnode.toStringTree(fn.fnode));
79 System.out.println(toString(theBlocks, statementNodes));
80 }
81
82 reachingDefDataFlow(fn, statementNodes, theBlocks, varTypes);
83 typeFlow(fn, statementNodes, theBlocks, varTypes);
84
85 if (DEBUG) {
86 for (int i = 0; i < theBlocks.length; i++) {
87 System.out.println("For block " + theBlocks[i].itsBlockID);
88 theBlocks[i].printLiveOnEntrySet(fn);
89 }
90 System.out.println("Variable Table, size = " + varCount);
91 for (int i = 0; i != varCount; i++) {
92 System.out.println("["+i+"] type: "+varTypes[i]);
93 }
94 }
95
96 for (int i = paramCount; i != varCount; i++) {
97 if (varTypes[i] == Optimizer.NumberType) {
98 fn.setIsNumberVar(i);
99 }
100 }
101
102 }
103
104 private static Block[] buildBlocks(Node[] statementNodes)
105 {
106 // a mapping from each target node to the block it begins
107 Map<Node,FatBlock> theTargetBlocks = new HashMap<Node,FatBlock>();
108 ObjArray theBlocks = new ObjArray();
109
110 // there's a block that starts at index 0
111 int beginNodeIndex = 0;
112
113 for (int i = 0; i < statementNodes.length; i++) {
114 switch (statementNodes[i].getType()) {
115 case Token.TARGET :
116 {
117 if (i != beginNodeIndex) {
118 FatBlock fb = newFatBlock(beginNodeIndex, i - 1);
119 if (statementNodes[beginNodeIndex].getType() == Token.TARGET) {
120 theTargetBlocks.put(statementNodes[beginNodeIndex], fb);
121 }
122 theBlocks.add(fb);
123 // start the next block at this node
124 beginNodeIndex = i;
125 }
126 }
127 break;
128 case Token.IFNE :
129 case Token.IFEQ :
130 case Token.GOTO :
131 {
132 FatBlock fb = newFatBlock(beginNodeIndex, i);
133 if (statementNodes[beginNodeIndex].getType() == Token.TARGET) {
134 theTargetBlocks.put(statementNodes[beginNodeIndex], fb);
135 }
136 theBlocks.add(fb);
137 // start the next block at the next node
138 beginNodeIndex = i + 1;
139 }
140 break;
141 }
142 }
143
144 if (beginNodeIndex != statementNodes.length) {
145 FatBlock fb = newFatBlock(beginNodeIndex, statementNodes.length - 1);
146 if (statementNodes[beginNodeIndex].getType() == Token.TARGET) {
147 theTargetBlocks.put(statementNodes[beginNodeIndex], fb);
148 }
149 theBlocks.add(fb);
150 }
151
152 // build successor and predecessor links
153
154 for (int i = 0; i < theBlocks.size(); i++) {
155 FatBlock fb = (FatBlock)(theBlocks.get(i));
156
157 Node blockEndNode = statementNodes[fb.realBlock.itsEndNodeIndex];
158 int blockEndNodeType = blockEndNode.getType();
159
160 if ((blockEndNodeType != Token.GOTO) && (i < (theBlocks.size() - 1))) {
161 FatBlock fallThruTarget = (FatBlock)(theBlocks.get(i + 1));
162 fb.addSuccessor(fallThruTarget);
163 fallThruTarget.addPredecessor(fb);
164 }
165
166
167 if ( (blockEndNodeType == Token.IFNE)
168 || (blockEndNodeType == Token.IFEQ)
169 || (blockEndNodeType == Token.GOTO) ) {
170 Node target = ((Jump)blockEndNode).target;
171 FatBlock branchTargetBlock = theTargetBlocks.get(target);
172 target.putProp(Node.TARGETBLOCK_PROP, branchTargetBlock.realBlock);
173 fb.addSuccessor(branchTargetBlock);
174 branchTargetBlock.addPredecessor(fb);
175 }
176 }
177
178 Block[] result = new Block[theBlocks.size()];
179
180 for (int i = 0; i < theBlocks.size(); i++) {
181 FatBlock fb = (FatBlock)(theBlocks.get(i));
182 Block b = fb.realBlock;
183 b.itsSuccessors = fb.getSuccessors();
184 b.itsPredecessors = fb.getPredecessors();
185 b.itsBlockID = i;
186 result[i] = b;
187 }
188
189 return result;
190 }
191
192 private static FatBlock newFatBlock(int startNodeIndex, int endNodeIndex)
193 {
194 FatBlock fb = new FatBlock();
195 fb.realBlock = new Block(startNodeIndex, endNodeIndex);
196 return fb;
197 }
198
199 private static String toString(Block[] blockList, Node[] statementNodes)
200 {
201 if (!DEBUG) return null;
202
203 StringWriter sw = new StringWriter();
204 PrintWriter pw = new PrintWriter(sw);
205
206 pw.println(blockList.length + " Blocks");
207 for (int i = 0; i < blockList.length; i++) {
208 Block b = blockList[i];
209 pw.println("#" + b.itsBlockID);
210 pw.println("from " + b.itsStartNodeIndex
211 + " "
212 + statementNodes[b.itsStartNodeIndex].toString());
213 pw.println("thru " + b.itsEndNodeIndex
214 + " "
215 + statementNodes[b.itsEndNodeIndex].toString());
216 pw.print("Predecessors ");
217 if (b.itsPredecessors != null) {
218 for (int j = 0; j < b.itsPredecessors.length; j++) {
219 pw.print(b.itsPredecessors[j].itsBlockID + " ");
220 }
221 pw.println();
222 } else {
223 pw.println("none");
224 }
225 pw.print("Successors ");
226 if (b.itsSuccessors != null) {
227 for (int j = 0; j < b.itsSuccessors.length; j++) {
228 pw.print(b.itsSuccessors[j].itsBlockID + " ");
229 }
230 pw.println();
231 } else {
232 pw.println("none");
233 }
234 }
235 return sw.toString();
236 }
237
238 private static void reachingDefDataFlow(OptFunctionNode fn, Node[] statementNodes,
239 Block theBlocks[], int[] varTypes)
240 {
241 /*
242 initialize the liveOnEntry and liveOnExit sets, then discover the variables
243 that are def'd by each function, and those that are used before being def'd
244 (hence liveOnEntry)
245 */
246 for (int i = 0; i < theBlocks.length; i++) {
247 theBlocks[i].initLiveOnEntrySets(fn, statementNodes);
248 }
249 /*
250 this visits every block starting at the last, re-adding the predecessors of
251 any block whose inputs change as a result of the dataflow.
252 REMIND, better would be to visit in CFG postorder
253 */
254 boolean visit[] = new boolean[theBlocks.length];
255 boolean doneOnce[] = new boolean[theBlocks.length];
256 int vIndex = theBlocks.length - 1;
257 boolean needRescan = false;
258 visit[vIndex] = true;
259 while (true) {
260 if (visit[vIndex] || !doneOnce[vIndex]) {
261 doneOnce[vIndex] = true;
262 visit[vIndex] = false;
263 if (theBlocks[vIndex].doReachedUseDataFlow()) {
264 Block pred[] = theBlocks[vIndex].itsPredecessors;
265 if (pred != null) {
266 for (int i = 0; i < pred.length; i++) {
267 int index = pred[i].itsBlockID;
268 visit[index] = true;
269 needRescan |= (index > vIndex);
270 }
271 }
272 }
273 }
274 if (vIndex == 0) {
275 if (needRescan) {
276 vIndex = theBlocks.length - 1;
277 needRescan = false;
278 } else {
279 break;
280 }
281 } else {
282 vIndex--;
283 }
284 }
285 /*
286 if any variable is live on entry to block 0, we have to mark it as
287 not jRegable - since it means that someone is trying to access the
288 'undefined'-ness of that variable.
289 */
290
291 theBlocks[0].markAnyTypeVariables(varTypes);
292 }
293
294 private static void typeFlow(OptFunctionNode fn, Node[] statementNodes,
295 Block theBlocks[], int[] varTypes)
296 {
297 boolean visit[] = new boolean[theBlocks.length];
298 boolean doneOnce[] = new boolean[theBlocks.length];
299 int vIndex = 0;
300 boolean needRescan = false;
301 visit[vIndex] = true;
302 while (true) {
303 if (visit[vIndex] || !doneOnce[vIndex]) {
304 doneOnce[vIndex] = true;
305 visit[vIndex] = false;
306 if (theBlocks[vIndex].doTypeFlow(fn, statementNodes, varTypes))
307 {
308 Block succ[] = theBlocks[vIndex].itsSuccessors;
309 if (succ != null) {
310 for (int i = 0; i < succ.length; i++) {
311 int index = succ[i].itsBlockID;
312 visit[index] = true;
313 needRescan |= (index < vIndex);
314 }
315 }
316 }
317 }
318 if (vIndex == (theBlocks.length - 1)) {
319 if (needRescan) {
320 vIndex = 0;
321 needRescan = false;
322 } else {
323 break;
324 }
325 } else {
326 vIndex++;
327 }
328 }
329 }
330
331 private static boolean assignType(int[] varTypes, int index, int type)
332 {
333 int prev = varTypes[index];
334 return prev != (varTypes[index] |= type);
335 }
336
337 private void markAnyTypeVariables(int[] varTypes)
338 {
339 for (int i = 0; i != varTypes.length; i++) {
340 if (itsLiveOnEntrySet.get(i)) {
341 assignType(varTypes, i, Optimizer.AnyType);
342 }
343 }
344
345 }
346
347 /*
348 We're tracking uses and defs - in order to
349 build the def set and to identify the last use
350 nodes.
351
352 The itsNotDefSet is built reversed then flipped later.
353
354 */
355 private void lookForVariableAccess(OptFunctionNode fn, Node n)
356 {
357 switch (n.getType()) {
358 case Token.TYPEOFNAME:
359 {
360 // TYPEOFNAME may be used with undefined names, which is why
361 // this is handled separately from GETVAR above.
362 int varIndex = fn.fnode.getIndexForNameNode(n);
363 if (varIndex > -1 && !itsNotDefSet.get(varIndex))
364 itsUseBeforeDefSet.set(varIndex);
365 }
366 break;
367 case Token.DEC :
368 case Token.INC :
369 {
370 Node child = n.getFirstChild();
371 if (child.getType() == Token.GETVAR) {
372 int varIndex = fn.getVarIndex(child);
373 if (!itsNotDefSet.get(varIndex))
374 itsUseBeforeDefSet.set(varIndex);
375 itsNotDefSet.set(varIndex);
376 } else {
377 lookForVariableAccess(fn, child);
378 }
379 }
380 break;
381 case Token.SETVAR :
382 case Token.SETCONSTVAR :
383 {
384 Node lhs = n.getFirstChild();
385 Node rhs = lhs.getNext();
386 lookForVariableAccess(fn, rhs);
387 itsNotDefSet.set(fn.getVarIndex(n));
388 }
389 break;
390 case Token.GETVAR :
391 {
392 int varIndex = fn.getVarIndex(n);
393 if (!itsNotDefSet.get(varIndex))
394 itsUseBeforeDefSet.set(varIndex);
395 }
396 break;
397 default :
398 Node child = n.getFirstChild();
399 while (child != null) {
400 lookForVariableAccess(fn, child);
401 child = child.getNext();
402 }
403 break;
404 }
405 }
406
407 /*
408 build the live on entry/exit sets.
409 Then walk the trees looking for defs/uses of variables
410 and build the def and useBeforeDef sets.
411 */
412 private void initLiveOnEntrySets(OptFunctionNode fn, Node[] statementNodes)
413 {
414 int listLength = fn.getVarCount();
415 itsUseBeforeDefSet = new BitSet(listLength);
416 itsNotDefSet = new BitSet(listLength);
417 itsLiveOnEntrySet = new BitSet(listLength);
418 itsLiveOnExitSet = new BitSet(listLength);
419 for (int i = itsStartNodeIndex; i <= itsEndNodeIndex; i++) {
420 Node n = statementNodes[i];
421 lookForVariableAccess(fn, n);
422 }
423 itsNotDefSet.flip(0, listLength); // truth in advertising
424 }
425
426 /*
427 the liveOnEntry of each successor is the liveOnExit for this block.
428 The liveOnEntry for this block is -
429 liveOnEntry = liveOnExit - defsInThisBlock + useBeforeDefsInThisBlock
430
431 */
432 private boolean doReachedUseDataFlow()
433 {
434 itsLiveOnExitSet.clear();
435 if (itsSuccessors != null) {
436 for (int i = 0; i < itsSuccessors.length; i++) {
437 itsLiveOnExitSet.or(itsSuccessors[i].itsLiveOnEntrySet);
438 }
439 }
440 return updateEntrySet(itsLiveOnEntrySet, itsLiveOnExitSet,
441 itsUseBeforeDefSet, itsNotDefSet);
442 }
443
444 private boolean updateEntrySet(BitSet entrySet, BitSet exitSet,
445 BitSet useBeforeDef, BitSet notDef) {
446 int card = entrySet.cardinality();
447 entrySet.or(exitSet);
448 entrySet.and(notDef);
449 entrySet.or(useBeforeDef);
450 return entrySet.cardinality() != card;
451 }
452
453 /*
454 the type of an expression is relatively unknown. Cases we can be sure
455 about are -
456 Literals,
457 Arithmetic operations - always return a Number
458 */
459 private static int findExpressionType(OptFunctionNode fn, Node n,
460 int[] varTypes)
461 {
462 switch (n.getType()) {
463 case Token.NUMBER:
464 return Optimizer.NumberType;
465
466 case Token.CALL:
467 case Token.NEW:
468 case Token.REF_CALL:
469 return Optimizer.AnyType;
470
471 case Token.GETELEM:
472 case Token.GETPROP:
473 case Token.NAME:
474 case Token.THIS:
475 return Optimizer.AnyType;
476
477 case Token.GETVAR:
478 return varTypes[fn.getVarIndex(n)];
479
480 case Token.INC:
481 case Token.DEC:
482 case Token.MUL:
483 case Token.DIV:
484 case Token.MOD:
485 case Token.BITOR:
486 case Token.BITXOR:
487 case Token.BITAND:
488 case Token.BITNOT:
489 case Token.LSH:
490 case Token.RSH:
491 case Token.URSH:
492 case Token.SUB:
493 case Token.POS:
494 case Token.NEG:
495 return Optimizer.NumberType;
496
497 case Token.VOID:
498 // NYI: undefined type
499 return Optimizer.AnyType;
500
501 case Token.FALSE:
502 case Token.TRUE:
503 case Token.EQ:
504 case Token.NE:
505 case Token.LT:
506 case Token.LE:
507 case Token.GT:
508 case Token.GE:
509 case Token.SHEQ:
510 case Token.SHNE:
511 case Token.NOT:
512 case Token.INSTANCEOF:
513 case Token.IN:
514 case Token.DEL_REF:
515 case Token.DELPROP:
516 // NYI: boolean type
517 return Optimizer.AnyType;
518
519 case Token.STRING:
520 case Token.TYPEOF:
521 case Token.TYPEOFNAME:
522 // NYI: string type
523 return Optimizer.AnyType;
524
525 case Token.NULL:
526 case Token.REGEXP:
527 case Token.ARRAYCOMP:
528 case Token.ARRAYLIT:
529 case Token.OBJECTLIT:
530 return Optimizer.AnyType; // XXX: actually, we know it's not
531 // number, but no type yet for that
532
533 case Token.ADD: {
534 // if the lhs & rhs are known to be numbers, we can be sure that's
535 // the result, otherwise it could be a string.
536 Node child = n.getFirstChild();
537 int lType = findExpressionType(fn, child, varTypes);
538 int rType = findExpressionType(fn, child.getNext(), varTypes);
539 return lType | rType; // we're not distinguishing strings yet
540 }
541
542 case Token.HOOK: {
543 Node ifTrue = n.getFirstChild().getNext();
544 Node ifFalse = ifTrue.getNext();
545 int ifTrueType = findExpressionType(fn, ifTrue, varTypes);
546 int ifFalseType = findExpressionType(fn, ifFalse, varTypes);
547 return ifTrueType | ifFalseType;
548 }
549
550 case Token.COMMA:
551 case Token.SETVAR:
552 case Token.SETCONSTVAR:
553 case Token.SETNAME:
554 case Token.SETPROP:
555 case Token.SETELEM:
556 return findExpressionType(fn, n.getLastChild(), varTypes);
557
558 case Token.AND:
559 case Token.OR: {
560 Node child = n.getFirstChild();
561 int lType = findExpressionType(fn, child, varTypes);
562 int rType = findExpressionType(fn, child.getNext(), varTypes);
563 return lType | rType;
564 }
565 }
566
567 return Optimizer.AnyType;
568 }
569
570 private static boolean findDefPoints(OptFunctionNode fn, Node n,
571 int[] varTypes)
572 {
573 boolean result = false;
574 Node first = n.getFirstChild();
575 for (Node next = first; next != null; next = next.getNext()) {
576 result |= findDefPoints(fn, next, varTypes);
577 }
578 switch (n.getType()) {
579 case Token.DEC :
580 case Token.INC :
581 if (first.getType() == Token.GETVAR) {
582 // theVar is a Number now
583 int i = fn.getVarIndex(first);
584 if (!fn.fnode.getParamAndVarConst()[i]) {
585 result |= assignType(varTypes, i, Optimizer.NumberType);
586 }
587 }
588 break;
589 case Token.SETVAR :
590 case Token.SETCONSTVAR : {
591 Node rValue = first.getNext();
592 int theType = findExpressionType(fn, rValue, varTypes);
593 int i = fn.getVarIndex(n);
594 if (!(n.getType() == Token.SETVAR
595 && fn.fnode.getParamAndVarConst()[i])) {
596 result |= assignType(varTypes, i, theType);
597 }
598 break;
599 }
600 }
601 return result;
602 }
603
604 private boolean doTypeFlow(OptFunctionNode fn, Node[] statementNodes,
605 int[] varTypes)
606 {
607 boolean changed = false;
608
609 for (int i = itsStartNodeIndex; i <= itsEndNodeIndex; i++) {
610 Node n = statementNodes[i];
611 if (n != null) {
612 changed |= findDefPoints(fn, n, varTypes);
613 }
614 }
615
616 return changed;
617 }
618
619 private void printLiveOnEntrySet(OptFunctionNode fn)
620 {
621 if (DEBUG) {
622 for (int i = 0; i < fn.getVarCount(); i++) {
623 String name = fn.fnode.getParamOrVarName(i);
624 if (itsUseBeforeDefSet.get(i))
625 System.out.println(name + " is used before def'd");
626 if (itsNotDefSet.get(i))
627 System.out.println(name + " is not def'd");
628 if (itsLiveOnEntrySet.get(i))
629 System.out.println(name + " is live on entry");
630 if (itsLiveOnExitSet.get(i))
631 System.out.println(name + " is live on exit");
632 }
633 }
634 }
635
636 // all the Blocks that come immediately after this
637 private Block[] itsSuccessors;
638 // all the Blocks that come immediately before this
639 private Block[] itsPredecessors;
640
641 private int itsStartNodeIndex; // the Node at the start of the block
642 private int itsEndNodeIndex; // the Node at the end of the block
643
644 private int itsBlockID; // a unique index for each block
645
646 // reaching def bit sets -
647 private BitSet itsLiveOnEntrySet;
648 private BitSet itsLiveOnExitSet;
649 private BitSet itsUseBeforeDefSet;
650 private BitSet itsNotDefSet;
651
652 static final boolean DEBUG = false;
653 private static int debug_blockCount;
654
655 }
656