1 package Analysis.Disjoint;
3 import Analysis.CallGraph.*;
4 import Analysis.Liveness;
5 import Analysis.ArrayReferencees;
6 import Analysis.OoOJava.Accessible;
7 import Analysis.OoOJava.RBlockRelationAnalysis;
10 import IR.Tree.Modifiers;
15 public class DisjointAnalysis implements HeapAnalysis {
17 ///////////////////////////////////////////
19 // Public interface to discover possible
20 // sharing in the program under analysis
22 ///////////////////////////////////////////
24 // if an object allocated at the target site may be
25 // reachable from both an object from root1 and an
26 // object allocated at root2, return TRUE
27 public boolean mayBothReachTarget(FlatMethod fm,
32 AllocSite asr1 = getAllocationSiteFromFlatNew(fnRoot1);
33 AllocSite asr2 = getAllocationSiteFromFlatNew(fnRoot2);
34 assert asr1.isFlagged();
35 assert asr2.isFlagged();
37 AllocSite ast = getAllocationSiteFromFlatNew(fnTarget);
38 ReachGraph rg = getPartial(fm.getMethod() );
40 return rg.mayBothReachTarget(asr1, asr2, ast);
43 // similar to the method above, return TRUE if ever
44 // more than one object from the root allocation site
45 // may reach an object from the target site
46 public boolean mayManyReachTarget(FlatMethod fm,
50 AllocSite asr = getAllocationSiteFromFlatNew(fnRoot);
51 assert asr.isFlagged();
53 AllocSite ast = getAllocationSiteFromFlatNew(fnTarget);
54 ReachGraph rg = getPartial(fm.getMethod() );
56 return rg.mayManyReachTarget(asr, ast);
62 public HashSet<AllocSite>
63 getFlaggedAllocationSitesReachableFromTask(TaskDescriptor td) {
64 checkAnalysisComplete();
65 return getFlaggedAllocationSitesReachableFromTaskPRIVATE(td);
68 public AllocSite getAllocationSiteFromFlatNew(FlatNew fn) {
69 checkAnalysisComplete();
70 return getAllocSiteFromFlatNewPRIVATE(fn);
73 public AllocSite getAllocationSiteFromHeapRegionNodeID(Integer id) {
74 checkAnalysisComplete();
75 return mapHrnIdToAllocSite.get(id);
78 public Set<HeapRegionNode> hasPotentialSharing(Descriptor taskOrMethod,
81 checkAnalysisComplete();
82 ReachGraph rg=mapDescriptorToCompleteReachGraph.get(taskOrMethod);
83 FlatMethod fm=state.getMethodFlat(taskOrMethod);
85 return rg.mayReachSharedObjects(fm, paramIndex1, paramIndex2);
88 public Set<HeapRegionNode> hasPotentialSharing(Descriptor taskOrMethod,
89 int paramIndex, AllocSite alloc) {
90 checkAnalysisComplete();
91 ReachGraph rg = mapDescriptorToCompleteReachGraph.get(taskOrMethod);
92 FlatMethod fm=state.getMethodFlat(taskOrMethod);
94 return rg.mayReachSharedObjects(fm, paramIndex, alloc);
97 public Set<HeapRegionNode> hasPotentialSharing(Descriptor taskOrMethod,
98 AllocSite alloc, int paramIndex) {
99 checkAnalysisComplete();
100 ReachGraph rg = mapDescriptorToCompleteReachGraph.get(taskOrMethod);
101 FlatMethod fm=state.getMethodFlat(taskOrMethod);
103 return rg.mayReachSharedObjects(fm, paramIndex, alloc);
106 public Set<HeapRegionNode> hasPotentialSharing(Descriptor taskOrMethod,
107 AllocSite alloc1, AllocSite alloc2) {
108 checkAnalysisComplete();
109 ReachGraph rg = mapDescriptorToCompleteReachGraph.get(taskOrMethod);
111 return rg.mayReachSharedObjects(alloc1, alloc2);
114 public String prettyPrintNodeSet(Set<HeapRegionNode> s) {
115 checkAnalysisComplete();
119 Iterator<HeapRegionNode> i = s.iterator();
120 while (i.hasNext()) {
121 HeapRegionNode n = i.next();
123 AllocSite as = n.getAllocSite();
125 out += " " + n.toString() + ",\n";
127 out += " " + n.toString() + ": " + as.toStringVerbose()
136 // use the methods given above to check every possible sharing class
137 // between task parameters and flagged allocation sites reachable
139 public void writeAllSharing(String outputFile,
142 boolean tabularOutput,
145 throws java.io.IOException {
146 checkAnalysisComplete();
148 BufferedWriter bw = new BufferedWriter(new FileWriter(outputFile));
150 if (!tabularOutput) {
151 bw.write("Conducting ownership analysis with allocation depth = "
152 + allocationDepth + "\n");
153 bw.write(timeReport + "\n");
158 // look through every task for potential sharing
159 Iterator taskItr = state.getTaskSymbolTable().getDescriptorsIterator();
160 while (taskItr.hasNext()) {
161 TaskDescriptor td = (TaskDescriptor) taskItr.next();
163 if (!tabularOutput) {
164 bw.write("\n---------" + td + "--------\n");
167 HashSet<AllocSite> allocSites = getFlaggedAllocationSitesReachableFromTask(td);
169 Set<HeapRegionNode> common;
171 // for each task parameter, check for sharing classes with
172 // other task parameters and every allocation site
173 // reachable from this task
174 boolean foundSomeSharing = false;
176 FlatMethod fm = state.getMethodFlat(td);
177 for (int i = 0; i < fm.numParameters(); ++i) {
179 // skip parameters with types that cannot reference
181 if( !shouldAnalysisTrack(fm.getParameter(i).getType() ) ) {
185 // for the ith parameter check for sharing classes to all
186 // higher numbered parameters
187 for (int j = i + 1; j < fm.numParameters(); ++j) {
189 // skip parameters with types that cannot reference
191 if( !shouldAnalysisTrack(fm.getParameter(j).getType() ) ) {
196 common = hasPotentialSharing(td, i, j);
197 if (!common.isEmpty()) {
198 foundSomeSharing = true;
200 if (!tabularOutput) {
201 bw.write("Potential sharing between parameters " + i
202 + " and " + j + ".\n");
203 bw.write(prettyPrintNodeSet(common) + "\n");
208 // for the ith parameter, check for sharing classes against
209 // the set of allocation sites reachable from this
211 Iterator allocItr = allocSites.iterator();
212 while (allocItr.hasNext()) {
213 AllocSite as = (AllocSite) allocItr.next();
214 common = hasPotentialSharing(td, i, as);
215 if (!common.isEmpty()) {
216 foundSomeSharing = true;
218 if (!tabularOutput) {
219 bw.write("Potential sharing between parameter " + i
220 + " and " + as.getFlatNew() + ".\n");
221 bw.write(prettyPrintNodeSet(common) + "\n");
227 // for each allocation site check for sharing classes with
228 // other allocation sites in the context of execution
230 HashSet<AllocSite> outerChecked = new HashSet<AllocSite>();
231 Iterator allocItr1 = allocSites.iterator();
232 while (allocItr1.hasNext()) {
233 AllocSite as1 = (AllocSite) allocItr1.next();
235 Iterator allocItr2 = allocSites.iterator();
236 while (allocItr2.hasNext()) {
237 AllocSite as2 = (AllocSite) allocItr2.next();
239 if (!outerChecked.contains(as2)) {
240 common = hasPotentialSharing(td, as1, as2);
242 if (!common.isEmpty()) {
243 foundSomeSharing = true;
245 if (!tabularOutput) {
246 bw.write("Potential sharing between "
247 + as1.getFlatNew() + " and "
248 + as2.getFlatNew() + ".\n");
249 bw.write(prettyPrintNodeSet(common) + "\n");
255 outerChecked.add(as1);
258 if (!foundSomeSharing) {
259 if (!tabularOutput) {
260 bw.write("No sharing between flagged objects in Task " + td
268 bw.write(" & " + numSharing + " & " + justTime + " & " + numLines
269 + " & " + numMethodsAnalyzed() + " \\\\\n");
271 bw.write("\nNumber sharing classes: "+numSharing);
279 // this version of writeAllSharing is for Java programs that have no tasks
280 // ***********************************
281 // WARNING: THIS DOES NOT DO THE RIGHT THING, REPORTS 0 ALWAYS!
282 // It should use mayBothReachTarget and mayManyReachTarget like
283 // OoOJava does to query analysis results
284 // ***********************************
285 public void writeAllSharingJava(String outputFile,
288 boolean tabularOutput,
291 throws java.io.IOException {
292 checkAnalysisComplete();
298 BufferedWriter bw = new BufferedWriter(new FileWriter(outputFile));
300 bw.write("Conducting disjoint reachability analysis with allocation depth = "
301 + allocationDepth + "\n");
302 bw.write(timeReport + "\n\n");
304 boolean foundSomeSharing = false;
306 Descriptor d = typeUtil.getMain();
307 HashSet<AllocSite> allocSites = getFlaggedAllocationSites(d);
309 // for each allocation site check for sharing classes with
310 // other allocation sites in the context of execution
312 HashSet<AllocSite> outerChecked = new HashSet<AllocSite>();
313 Iterator allocItr1 = allocSites.iterator();
314 while (allocItr1.hasNext()) {
315 AllocSite as1 = (AllocSite) allocItr1.next();
317 Iterator allocItr2 = allocSites.iterator();
318 while (allocItr2.hasNext()) {
319 AllocSite as2 = (AllocSite) allocItr2.next();
321 if (!outerChecked.contains(as2)) {
322 Set<HeapRegionNode> common = hasPotentialSharing(d,
325 if (!common.isEmpty()) {
326 foundSomeSharing = true;
327 bw.write("Potential sharing between "
328 + as1.getDisjointAnalysisId() + " and "
329 + as2.getDisjointAnalysisId() + ".\n");
330 bw.write(prettyPrintNodeSet(common) + "\n");
336 outerChecked.add(as1);
339 if (!foundSomeSharing) {
340 bw.write("No sharing classes between flagged objects found.\n");
342 bw.write("\nNumber sharing classes: "+numSharing);
345 bw.write("Number of methods analyzed: "+numMethodsAnalyzed()+"\n");
352 public Alloc getCmdLineArgsAlloc() {
353 return getAllocationSiteFromFlatNew( constructedCmdLineArgsNew );
355 ///////////////////////////////////////////
357 // end public interface
359 ///////////////////////////////////////////
363 protected void checkAnalysisComplete() {
364 if( !analysisComplete ) {
365 throw new Error("Warning: public interface method called while analysis is running.");
374 // run in faster mode, only when bugs wrung out!
375 public static boolean releaseMode;
377 // use command line option to set this, analysis
378 // should attempt to be deterministic
379 public static boolean determinismDesired;
381 // when we want to enforce determinism in the
382 // analysis we need to sort descriptors rather
383 // than toss them in efficient sets, use this
384 public static DescriptorComparator dComp =
385 new DescriptorComparator();
388 // data from the compiler
390 public CallGraph callGraph;
391 public Liveness liveness;
392 public ArrayReferencees arrayReferencees;
393 public RBlockRelationAnalysis rblockRel;
394 public TypeUtil typeUtil;
395 public int allocationDepth;
397 protected boolean doEffectsAnalysis = false;
398 protected EffectsAnalysis effectsAnalysis;
399 protected BuildStateMachines buildStateMachines;
402 // data structure for public interface
403 private Hashtable< Descriptor, HashSet<AllocSite> >
404 mapDescriptorToAllocSiteSet;
407 // for public interface methods to warn that they
408 // are grabbing results during analysis
409 private boolean analysisComplete;
412 // used to identify HeapRegionNode objects
413 // A unique ID equates an object in one
414 // ownership graph with an object in another
415 // graph that logically represents the same
417 // start at 10 and increment to reserve some
418 // IDs for special purposes
419 static protected int uniqueIDcount = 10;
422 // An out-of-scope method created by the
423 // analysis that has no parameters, and
424 // appears to allocate the command line
425 // arguments, then invoke the source code's
426 // main method. The purpose of this is to
427 // provide the analysis with an explicit
428 // top-level context with no parameters
429 protected MethodDescriptor mdAnalysisEntry;
430 protected FlatMethod fmAnalysisEntry;
432 // main method defined by source program
433 protected MethodDescriptor mdSourceEntry;
435 // the set of task and/or method descriptors
436 // reachable in call graph
437 protected Set<Descriptor>
438 descriptorsToAnalyze;
440 // current descriptors to visit in fixed-point
441 // interprocedural analysis, prioritized by
442 // dependency in the call graph
443 protected Stack<Descriptor>
444 descriptorsToVisitStack;
445 protected PriorityQueue<DescriptorQWrapper>
448 // a duplication of the above structure, but
449 // for efficient testing of inclusion
450 protected HashSet<Descriptor>
451 descriptorsToVisitSet;
453 // storage for priorities (doesn't make sense)
454 // to add it to the Descriptor class, just in
456 protected Hashtable<Descriptor, Integer>
457 mapDescriptorToPriority;
459 // when analyzing a method and scheduling more:
460 // remember set of callee's enqueued for analysis
461 // so they can be put on top of the callers in
462 // the stack-visit mode
463 protected Set<Descriptor>
466 // maps a descriptor to its current partial result
467 // from the intraprocedural fixed-point analysis--
468 // then the interprocedural analysis settles, this
469 // mapping will have the final results for each
471 protected Hashtable<Descriptor, ReachGraph>
472 mapDescriptorToCompleteReachGraph;
474 // maps a descriptor to its known dependents: namely
475 // methods or tasks that call the descriptor's method
476 // AND are part of this analysis (reachable from main)
477 protected Hashtable< Descriptor, Set<Descriptor> >
478 mapDescriptorToSetDependents;
480 // if the analysis client wants to flag allocation sites
481 // programmatically, it should provide a set of FlatNew
482 // statements--this may be null if unneeded
483 protected Set<FlatNew> sitesToFlag;
485 // maps each flat new to one analysis abstraction
486 // allocate site object, these exist outside reach graphs
487 protected Hashtable<FlatNew, AllocSite>
488 mapFlatNewToAllocSite;
490 // maps intergraph heap region IDs to intergraph
491 // allocation sites that created them, a redundant
492 // structure for efficiency in some operations
493 protected Hashtable<Integer, AllocSite>
496 // maps a method to its initial heap model (IHM) that
497 // is the set of reachability graphs from every caller
498 // site, all merged together. The reason that we keep
499 // them separate is that any one call site's contribution
500 // to the IHM may changed along the path to the fixed point
501 protected Hashtable< Descriptor, Hashtable< FlatCall, ReachGraph > >
502 mapDescriptorToIHMcontributions;
504 // additionally, keep a mapping from descriptors to the
505 // merged in-coming initial context, because we want this
506 // initial context to be STRICTLY MONOTONIC
507 protected Hashtable<Descriptor, ReachGraph>
508 mapDescriptorToInitialContext;
510 // make the result for back edges analysis-wide STRICTLY
511 // MONOTONIC as well, but notice we use FlatNode as the
512 // key for this map: in case we want to consider other
513 // nodes as back edge's in future implementations
514 protected Hashtable<FlatNode, ReachGraph>
515 mapBackEdgeToMonotone;
518 public static final String arrayElementFieldName = "___element_";
519 static protected Hashtable<TypeDescriptor, FieldDescriptor>
523 protected boolean suppressOutput;
525 // for controlling DOT file output
526 protected boolean writeFinalDOTs;
527 protected boolean writeAllIncrementalDOTs;
529 // supporting DOT output--when we want to write every
530 // partial method result, keep a tally for generating
532 protected Hashtable<Descriptor, Integer>
533 mapDescriptorToNumUpdates;
535 //map task descriptor to initial task parameter
536 protected Hashtable<Descriptor, ReachGraph>
537 mapDescriptorToReachGraph;
539 protected PointerMethod pm;
541 //Keeps track of all the reach graphs at every program point
542 //DO NOT USE UNLESS YOU REALLY NEED IT
543 static protected Hashtable<FlatNode, ReachGraph> fn2rgAtEnter =
544 new Hashtable<FlatNode, ReachGraph>();
546 static protected Hashtable<FlatNode, ReachGraph> fn2rgAtExit =
547 new Hashtable<FlatNode, ReachGraph>();
550 private Hashtable<FlatCall, Descriptor> fc2enclosing;
552 Accessible accessible;
555 // we construct an entry method of flat nodes complete
556 // with a new allocation site to model the command line
557 // args creation just for the analysis, so remember that
558 // allocation site. Later in code gen we might want to
559 // know if something is pointing-to to the cmd line args
560 // and we can verify by checking the allocation site field.
561 protected FlatNew constructedCmdLineArgsNew;
566 // allocate various structures that are not local
567 // to a single class method--should be done once
568 protected void allocateStructures() {
570 if( determinismDesired ) {
571 // use an ordered set
572 descriptorsToAnalyze = new TreeSet<Descriptor>(dComp);
574 // otherwise use a speedy hashset
575 descriptorsToAnalyze = new HashSet<Descriptor>();
578 mapDescriptorToCompleteReachGraph =
579 new Hashtable<Descriptor, ReachGraph>();
581 mapDescriptorToNumUpdates =
582 new Hashtable<Descriptor, Integer>();
584 mapDescriptorToSetDependents =
585 new Hashtable< Descriptor, Set<Descriptor> >();
587 mapFlatNewToAllocSite =
588 new Hashtable<FlatNew, AllocSite>();
590 mapDescriptorToIHMcontributions =
591 new Hashtable< Descriptor, Hashtable< FlatCall, ReachGraph > >();
593 mapDescriptorToInitialContext =
594 new Hashtable<Descriptor, ReachGraph>();
596 mapBackEdgeToMonotone =
597 new Hashtable<FlatNode, ReachGraph>();
599 mapHrnIdToAllocSite =
600 new Hashtable<Integer, AllocSite>();
602 mapTypeToArrayField =
603 new Hashtable <TypeDescriptor, FieldDescriptor>();
605 if( state.DISJOINTDVISITSTACK ||
606 state.DISJOINTDVISITSTACKEESONTOP
608 descriptorsToVisitStack =
609 new Stack<Descriptor>();
612 if( state.DISJOINTDVISITPQUE ) {
613 descriptorsToVisitQ =
614 new PriorityQueue<DescriptorQWrapper>();
617 descriptorsToVisitSet =
618 new HashSet<Descriptor>();
620 mapDescriptorToPriority =
621 new Hashtable<Descriptor, Integer>();
624 new HashSet<Descriptor>();
626 mapDescriptorToAllocSiteSet =
627 new Hashtable<Descriptor, HashSet<AllocSite> >();
629 mapDescriptorToReachGraph =
630 new Hashtable<Descriptor, ReachGraph>();
632 pm = new PointerMethod();
634 fc2enclosing = new Hashtable<FlatCall, Descriptor>();
639 // this analysis generates a disjoint reachability
640 // graph for every reachable method in the program
641 public DisjointAnalysis(State s,
646 Set<FlatNew> sitesToFlag,
647 RBlockRelationAnalysis rra
649 init(s, tu, cg, l, ar, sitesToFlag, rra, null, false);
652 public DisjointAnalysis(State s,
657 Set<FlatNew> sitesToFlag,
658 RBlockRelationAnalysis rra,
659 boolean suppressOutput
661 init(s, tu, cg, l, ar, sitesToFlag, rra, null, suppressOutput);
664 public DisjointAnalysis(State s,
669 Set<FlatNew> sitesToFlag,
670 RBlockRelationAnalysis rra,
671 BuildStateMachines bsm,
672 boolean suppressOutput
674 init(s, tu, cg, l, ar, sitesToFlag, rra, bsm, suppressOutput);
677 protected void init(State state,
681 ArrayReferencees arrayReferencees,
682 Set<FlatNew> sitesToFlag,
683 RBlockRelationAnalysis rra,
684 BuildStateMachines bsm,
685 boolean suppressOutput
688 analysisComplete = false;
691 this.typeUtil = typeUtil;
692 this.callGraph = callGraph;
693 this.liveness = liveness;
694 this.arrayReferencees = arrayReferencees;
695 this.sitesToFlag = sitesToFlag;
696 this.rblockRel = rra;
697 this.suppressOutput = suppressOutput;
698 this.buildStateMachines = bsm;
700 if( rblockRel != null ) {
701 doEffectsAnalysis = true;
702 effectsAnalysis = new EffectsAnalysis();
704 EffectsAnalysis.state = state;
705 EffectsAnalysis.buildStateMachines = buildStateMachines;
707 //note: instead of reachgraph's isAccessible, using the result of accessible analysis
708 //since accessible gives us more accurate results
709 accessible=new Accessible(state, callGraph, rra, liveness);
710 accessible.doAnalysis();
713 this.allocationDepth = state.DISJOINTALLOCDEPTH;
714 this.releaseMode = state.DISJOINTRELEASEMODE;
715 this.determinismDesired = state.DISJOINTDETERMINISM;
717 this.writeFinalDOTs = state.DISJOINTWRITEDOTS && !state.DISJOINTWRITEALL;
718 this.writeAllIncrementalDOTs = state.DISJOINTWRITEDOTS && state.DISJOINTWRITEALL;
720 this.takeDebugSnapshots = state.DISJOINTSNAPSYMBOL != null;
721 this.descSymbolDebug = state.DISJOINTSNAPSYMBOL;
722 this.visitStartCapture = state.DISJOINTSNAPVISITTOSTART;
723 this.numVisitsToCapture = state.DISJOINTSNAPNUMVISITS;
724 this.stopAfterCapture = state.DISJOINTSNAPSTOPAFTER;
725 this.snapVisitCounter = 1; // count visits from 1 (user will write 1, means 1st visit)
726 this.snapNodeCounter = 0; // count nodes from 0
729 state.DISJOINTDVISITSTACK ||
730 state.DISJOINTDVISITPQUE ||
731 state.DISJOINTDVISITSTACKEESONTOP;
732 assert !(state.DISJOINTDVISITSTACK && state.DISJOINTDVISITPQUE);
733 assert !(state.DISJOINTDVISITSTACK && state.DISJOINTDVISITSTACKEESONTOP);
734 assert !(state.DISJOINTDVISITPQUE && state.DISJOINTDVISITSTACKEESONTOP);
736 // set some static configuration for ReachGraphs
737 ReachGraph.allocationDepth = allocationDepth;
738 ReachGraph.typeUtil = typeUtil;
739 ReachGraph.state = state;
741 ReachGraph.debugCallSiteVisitStartCapture
742 = state.DISJOINTDEBUGCALLVISITTOSTART;
744 ReachGraph.debugCallSiteNumVisitsToCapture
745 = state.DISJOINTDEBUGCALLNUMVISITS;
747 ReachGraph.debugCallSiteStopAfter
748 = state.DISJOINTDEBUGCALLSTOPAFTER;
750 ReachGraph.debugCallSiteVisitCounter
751 = 0; // count visits from 1, is incremented before first visit
756 if( suppressOutput ) {
757 System.out.println("* Running disjoint reachability analysis with output suppressed! *");
760 allocateStructures();
762 double timeStartAnalysis = (double) System.nanoTime();
764 // start interprocedural fixed-point computation
767 } catch( IOException e ) {
768 throw new Error("IO Exception while writing disjointness analysis output.");
771 analysisComplete=true;
773 double timeEndAnalysis = (double) System.nanoTime();
774 double dt = (timeEndAnalysis - timeStartAnalysis)/(Math.pow(10.0, 9.0) );
777 if( sitesToFlag != null ) {
778 treport = String.format("Disjoint reachability analysis flagged %d sites and took %.3f sec.", sitesToFlag.size(), dt);
779 if(sitesToFlag.size()>0) {
780 treport+="\nFlagged sites:"+"\n"+sitesToFlag.toString();
783 treport = String.format("Disjoint reachability analysis took %.3f sec.", dt);
785 String justtime = String.format("%.2f", dt);
786 System.out.println(treport);
790 if( writeFinalDOTs && !writeAllIncrementalDOTs ) {
794 if( state.DISJOINTWRITEIHMS && !suppressOutput ) {
798 if( state.DISJOINTWRITEINITCONTEXTS && !suppressOutput ) {
799 writeInitialContexts();
802 if( state.DISJOINTALIASFILE != null && !suppressOutput ) {
804 writeAllSharing(state.DISJOINTALIASFILE, treport, justtime, state.DISJOINTALIASTAB, state.lines);
806 writeAllSharingJava(state.DISJOINTALIASFILE,
809 state.DISJOINTALIASTAB,
816 buildStateMachines.writeStateMachines();
819 } catch( IOException e ) {
820 throw new Error("IO Exception while writing disjointness analysis output.");
825 protected boolean moreDescriptorsToVisit() {
826 if( state.DISJOINTDVISITSTACK ||
827 state.DISJOINTDVISITSTACKEESONTOP
829 return !descriptorsToVisitStack.isEmpty();
831 } else if( state.DISJOINTDVISITPQUE ) {
832 return !descriptorsToVisitQ.isEmpty();
835 throw new Error("Neither descriptor visiting mode set");
839 // fixed-point computation over the call graph--when a
840 // method's callees are updated, it must be reanalyzed
841 protected void analyzeMethods() throws java.io.IOException {
843 // task or non-task (java) mode determines what the roots
844 // of the call chain are, and establishes the set of methods
845 // reachable from the roots that will be analyzed
848 if( !suppressOutput ) {
849 System.out.println("Bamboo mode...");
852 Iterator taskItr = state.getTaskSymbolTable().getDescriptorsIterator();
853 while( taskItr.hasNext() ) {
854 TaskDescriptor td = (TaskDescriptor) taskItr.next();
855 if( !descriptorsToAnalyze.contains(td) ) {
856 // add all methods transitively reachable from the
858 descriptorsToAnalyze.add(td);
859 descriptorsToAnalyze.addAll(callGraph.getAllMethods(td) );
864 if( !suppressOutput ) {
865 System.out.println("Java mode...");
868 // add all methods transitively reachable from the
869 // source's main to set for analysis
870 mdSourceEntry = typeUtil.getMain();
871 descriptorsToAnalyze.add(mdSourceEntry);
872 descriptorsToAnalyze.addAll(callGraph.getAllMethods(mdSourceEntry) );
874 // fabricate an empty calling context that will call
875 // the source's main, but call graph doesn't know
876 // about it, so explicitly add it
877 makeAnalysisEntryMethod(mdSourceEntry);
878 descriptorsToAnalyze.add(mdAnalysisEntry);
882 // now, depending on the interprocedural mode for visiting
883 // methods, set up the needed data structures
885 if( state.DISJOINTDVISITPQUE ) {
887 // topologically sort according to the call graph so
888 // leaf calls are last, helps build contexts up first
889 LinkedList<Descriptor> sortedDescriptors =
890 topologicalSort(descriptorsToAnalyze);
892 // add sorted descriptors to priority queue, and duplicate
893 // the queue as a set for efficiently testing whether some
894 // method is marked for analysis
896 Iterator<Descriptor> dItr;
898 // for the priority queue, give items at the head
899 // of the sorted list a low number (highest priority)
900 while( !sortedDescriptors.isEmpty() ) {
901 Descriptor d = sortedDescriptors.removeFirst();
902 mapDescriptorToPriority.put(d, new Integer(p) );
903 descriptorsToVisitQ.add(new DescriptorQWrapper(p, d) );
904 descriptorsToVisitSet.add(d);
908 } else if( state.DISJOINTDVISITSTACK ||
909 state.DISJOINTDVISITSTACKEESONTOP
911 // if we're doing the stack scheme, just throw the root
912 // method or tasks on the stack
914 Iterator taskItr = state.getTaskSymbolTable().getDescriptorsIterator();
915 while( taskItr.hasNext() ) {
916 TaskDescriptor td = (TaskDescriptor) taskItr.next();
917 descriptorsToVisitStack.add(td);
918 descriptorsToVisitSet.add(td);
922 descriptorsToVisitStack.add(mdAnalysisEntry);
923 descriptorsToVisitSet.add(mdAnalysisEntry);
927 throw new Error("Unknown method scheduling mode");
931 // analyze scheduled methods until there are no more to visit
932 while( moreDescriptorsToVisit() ) {
935 if( state.DISJOINTDVISITSTACK ||
936 state.DISJOINTDVISITSTACKEESONTOP
938 d = descriptorsToVisitStack.pop();
940 } else if( state.DISJOINTDVISITPQUE ) {
941 d = descriptorsToVisitQ.poll().getDescriptor();
944 assert descriptorsToVisitSet.contains(d);
945 descriptorsToVisitSet.remove(d);
947 // because the task or method descriptor just extracted
948 // was in the "to visit" set it either hasn't been analyzed
949 // yet, or some method that it depends on has been
950 // updated. Recompute a complete reachability graph for
951 // this task/method and compare it to any previous result.
952 // If there is a change detected, add any methods/tasks
953 // that depend on this one to the "to visit" set.
955 if( !suppressOutput ) {
956 System.out.println("Analyzing " + d);
959 if( state.DISJOINTDVISITSTACKEESONTOP ) {
960 assert calleesToEnqueue.isEmpty();
963 ReachGraph rg = analyzeMethod(d);
964 ReachGraph rgPrev = getPartial(d);
966 if( !rg.equals(rgPrev) ) {
969 if( state.DISJOINTDEBUGSCHEDULING ) {
970 System.out.println(" complete graph changed, scheduling callers for analysis:");
973 // results for d changed, so enqueue dependents
974 // of d for further analysis
975 Iterator<Descriptor> depsItr = getDependents(d).iterator();
976 while( depsItr.hasNext() ) {
977 Descriptor dNext = depsItr.next();
980 if( state.DISJOINTDEBUGSCHEDULING ) {
981 System.out.println(" "+dNext);
986 // whether or not the method under analysis changed,
987 // we may have some callees that are scheduled for
988 // more analysis, and they should go on the top of
989 // the stack now (in other method-visiting modes they
990 // are already enqueued at this point
991 if( state.DISJOINTDVISITSTACKEESONTOP ) {
992 Iterator<Descriptor> depsItr = calleesToEnqueue.iterator();
993 while( depsItr.hasNext() ) {
994 Descriptor dNext = depsItr.next();
997 calleesToEnqueue.clear();
1003 protected ReachGraph analyzeMethod(Descriptor d)
1004 throws java.io.IOException {
1006 // get the flat code for this descriptor
1008 if( d == mdAnalysisEntry ) {
1009 fm = fmAnalysisEntry;
1011 fm = state.getMethodFlat(d);
1013 pm.analyzeMethod(fm);
1015 // intraprocedural work set
1016 Set<FlatNode> flatNodesToVisit = new HashSet<FlatNode>();
1017 flatNodesToVisit.add(fm);
1019 // if determinism is desired by client, shadow the
1020 // set with a queue to make visit order deterministic
1021 Queue<FlatNode> flatNodesToVisitQ = null;
1022 if( determinismDesired ) {
1023 flatNodesToVisitQ = new LinkedList<FlatNode>();
1024 flatNodesToVisitQ.add(fm);
1027 // mapping of current partial results
1028 Hashtable<FlatNode, ReachGraph> mapFlatNodeToReachGraph =
1029 new Hashtable<FlatNode, ReachGraph>();
1031 // the set of return nodes partial results that will be combined as
1032 // the final, conservative approximation of the entire method
1033 HashSet<FlatReturnNode> setReturns = new HashSet<FlatReturnNode>();
1037 boolean snapThisMethod = false;
1038 if( takeDebugSnapshots && d instanceof MethodDescriptor ) {
1039 MethodDescriptor mdThisMethod = (MethodDescriptor)d;
1040 ClassDescriptor cdThisMethod = mdThisMethod.getClassDesc();
1041 if( cdThisMethod != null ) {
1043 descSymbolDebug.equals( cdThisMethod.getSymbol()+
1045 mdThisMethod.getSymbol()
1052 while( !flatNodesToVisit.isEmpty() ) {
1055 if( determinismDesired ) {
1056 assert !flatNodesToVisitQ.isEmpty();
1057 fn = flatNodesToVisitQ.remove();
1059 fn = flatNodesToVisit.iterator().next();
1061 flatNodesToVisit.remove(fn);
1063 // effect transfer function defined by this node,
1064 // then compare it to the old graph at this node
1065 // to see if anything was updated.
1067 ReachGraph rg = new ReachGraph();
1068 TaskDescriptor taskDesc;
1069 if(fn instanceof FlatMethod && (taskDesc=((FlatMethod)fn).getTask())!=null) {
1070 if(mapDescriptorToReachGraph.containsKey(taskDesc)) {
1071 // retrieve existing reach graph if it is not first time
1072 rg=mapDescriptorToReachGraph.get(taskDesc);
1074 // create initial reach graph for a task
1075 rg=createInitialTaskReachGraph((FlatMethod)fn);
1077 mapDescriptorToReachGraph.put(taskDesc, rg);
1081 // start by merging all node's parents' graphs
1082 for( int i = 0; i < pm.numPrev(fn); ++i ) {
1083 FlatNode pn = pm.getPrev(fn,i);
1084 if( mapFlatNodeToReachGraph.containsKey(pn) ) {
1085 ReachGraph rgParent = mapFlatNodeToReachGraph.get(pn);
1091 if( snapThisMethod ) {
1092 debugSnapshot(rg, fn, true);
1096 // modify rg with appropriate transfer function
1097 rg = analyzeFlatNode(d, fm, fn, setReturns, rg);
1100 if( snapThisMethod ) {
1101 debugSnapshot(rg, fn, false);
1106 // if the results of the new graph are different from
1107 // the current graph at this node, replace the graph
1108 // with the update and enqueue the children
1109 ReachGraph rgPrev = mapFlatNodeToReachGraph.get(fn);
1110 if( !rg.equals(rgPrev) ) {
1111 mapFlatNodeToReachGraph.put(fn, rg);
1113 for( int i = 0; i < pm.numNext(fn); i++ ) {
1114 FlatNode nn = pm.getNext(fn, i);
1116 flatNodesToVisit.add(nn);
1117 if( determinismDesired ) {
1118 flatNodesToVisitQ.add(nn);
1125 // end by merging all return nodes into a complete
1126 // reach graph that represents all possible heap
1127 // states after the flat method returns
1128 ReachGraph completeGraph = new ReachGraph();
1130 assert !setReturns.isEmpty();
1131 Iterator retItr = setReturns.iterator();
1132 while( retItr.hasNext() ) {
1133 FlatReturnNode frn = (FlatReturnNode) retItr.next();
1135 assert mapFlatNodeToReachGraph.containsKey(frn);
1136 ReachGraph rgRet = mapFlatNodeToReachGraph.get(frn);
1138 completeGraph.merge(rgRet);
1142 if( snapThisMethod ) {
1143 // increment that we've visited the debug snap
1144 // method, and reset the node counter
1145 System.out.println(" @@@ debug snap at visit "+snapVisitCounter);
1147 snapNodeCounter = 0;
1149 if( snapVisitCounter == visitStartCapture + numVisitsToCapture &&
1152 System.out.println("!!! Stopping analysis after debug snap captures. !!!");
1158 return completeGraph;
1162 protected ReachGraph
1163 analyzeFlatNode(Descriptor d,
1164 FlatMethod fmContaining,
1166 HashSet<FlatReturnNode> setRetNodes,
1168 ) throws java.io.IOException {
1171 // any variables that are no longer live should be
1172 // nullified in the graph to reduce edges
1173 //rg.nullifyDeadVars( liveness.getLiveInTemps( fmContaining, fn ) );
1177 FieldDescriptor fld;
1178 TypeDescriptor tdElement;
1179 FieldDescriptor fdElement;
1180 FlatSESEEnterNode sese;
1181 FlatSESEExitNode fsexn;
1183 //Stores the flatnode's reach graph at enter
1184 ReachGraph rgOnEnter = new ReachGraph();
1185 rgOnEnter.merge(rg);
1186 fn2rgAtEnter.put(fn, rgOnEnter);
1190 // use node type to decide what transfer function
1191 // to apply to the reachability graph
1192 switch( fn.kind() ) {
1194 case FKind.FlatGenReachNode: {
1195 FlatGenReachNode fgrn = (FlatGenReachNode) fn;
1197 System.out.println(" Generating reach graph for program point: "+fgrn.getGraphName() );
1200 rg.writeGraph("genReach"+fgrn.getGraphName(),
1201 true, // write labels (variables)
1202 true, // selectively hide intermediate temp vars
1203 true, // prune unreachable heap regions
1204 true, // hide reachability altogether
1205 true, // hide subset reachability states
1206 true, // hide predicates
1207 false); // hide edge taints
1211 case FKind.FlatMethod: {
1212 // construct this method's initial heap model (IHM)
1213 // since we're working on the FlatMethod, we know
1214 // the incoming ReachGraph 'rg' is empty
1216 Hashtable<FlatCall, ReachGraph> heapsFromCallers =
1217 getIHMcontributions(d);
1219 Set entrySet = heapsFromCallers.entrySet();
1220 Iterator itr = entrySet.iterator();
1221 while( itr.hasNext() ) {
1222 Map.Entry me = (Map.Entry)itr.next();
1223 FlatCall fc = (FlatCall) me.getKey();
1224 ReachGraph rgContrib = (ReachGraph) me.getValue();
1226 assert fc.getMethod().equals(d);
1228 rg.merge(rgContrib);
1231 // additionally, we are enforcing STRICT MONOTONICITY for the
1232 // method's initial context, so grow the context by whatever
1233 // the previously computed context was, and put the most
1234 // up-to-date context back in the map
1235 ReachGraph rgPrevContext = mapDescriptorToInitialContext.get(d);
1236 rg.merge(rgPrevContext);
1237 mapDescriptorToInitialContext.put(d, rg);
1241 case FKind.FlatOpNode:
1242 FlatOpNode fon = (FlatOpNode) fn;
1243 if( fon.getOp().getOp() == Operation.ASSIGN ) {
1244 lhs = fon.getDest();
1245 rhs = fon.getLeft();
1247 // before transfer, do effects analysis support
1248 if( doEffectsAnalysis && fmContaining != fmAnalysisEntry ) {
1249 if(rblockRel.isPotentialStallSite(fn)) {
1250 // x gets status of y
1251 // if(!rg.isAccessible(rhs)){
1252 if(!accessible.isAccessible(fn, rhs)) {
1253 rg.makeInaccessible(lhs);
1259 rg.assignTempXEqualToTempY(lhs, rhs);
1263 case FKind.FlatCastNode:
1264 FlatCastNode fcn = (FlatCastNode) fn;
1268 TypeDescriptor td = fcn.getType();
1271 // before transfer, do effects analysis support
1272 if( doEffectsAnalysis && fmContaining != fmAnalysisEntry ) {
1273 if(rblockRel.isPotentialStallSite(fn)) {
1274 // x gets status of y
1275 // if(!rg.isAccessible(rhs)){
1276 if(!accessible.isAccessible(fn,rhs)) {
1277 rg.makeInaccessible(lhs);
1283 rg.assignTempXEqualToCastedTempY(lhs, rhs, td);
1286 case FKind.FlatFieldNode:
1287 FlatFieldNode ffn = (FlatFieldNode) fn;
1291 fld = ffn.getField();
1293 // before graph transform, possible inject
1294 // a stall-site taint
1295 if( doEffectsAnalysis && fmContaining != fmAnalysisEntry ) {
1297 if(rblockRel.isPotentialStallSite(fn)) {
1298 // x=y.f, stall y if not accessible
1299 // contributes read effects on stall site of y
1300 // if(!rg.isAccessible(rhs)) {
1301 if(!accessible.isAccessible(fn,rhs)) {
1302 rg.taintStallSite(fn, rhs);
1305 // after this, x and y are accessbile.
1306 rg.makeAccessible(lhs);
1307 rg.makeAccessible(rhs);
1311 if( shouldAnalysisTrack(fld.getType() ) ) {
1313 rg.assignTempXEqualToTempYFieldF(lhs, rhs, fld, fn);
1316 // after transfer, use updated graph to
1317 // do effects analysis
1318 if( doEffectsAnalysis && fmContaining != fmAnalysisEntry ) {
1319 effectsAnalysis.analyzeFlatFieldNode(rg, rhs, fld, fn);
1323 case FKind.FlatSetFieldNode:
1324 FlatSetFieldNode fsfn = (FlatSetFieldNode) fn;
1326 lhs = fsfn.getDst();
1327 fld = fsfn.getField();
1328 rhs = fsfn.getSrc();
1330 boolean strongUpdate = false;
1332 // before transfer func, possibly inject
1333 // stall-site taints
1334 if( doEffectsAnalysis && fmContaining != fmAnalysisEntry ) {
1336 if(rblockRel.isPotentialStallSite(fn)) {
1337 // x.y=f , stall x and y if they are not accessible
1338 // also contribute write effects on stall site of x
1339 // if(!rg.isAccessible(lhs)) {
1340 if(!accessible.isAccessible(fn,lhs)) {
1341 rg.taintStallSite(fn, lhs);
1344 // if(!rg.isAccessible(rhs)) {
1345 if(!accessible.isAccessible(fn,rhs)) {
1346 rg.taintStallSite(fn, rhs);
1349 // accessible status update
1350 rg.makeAccessible(lhs);
1351 rg.makeAccessible(rhs);
1355 if( shouldAnalysisTrack(fld.getType() ) ) {
1357 strongUpdate = rg.assignTempXFieldFEqualToTempY(lhs, fld, rhs, fn);
1360 // use transformed graph to do effects analysis
1361 if( doEffectsAnalysis && fmContaining != fmAnalysisEntry ) {
1362 effectsAnalysis.analyzeFlatSetFieldNode(rg, lhs, fld, fn, strongUpdate);
1366 case FKind.FlatElementNode:
1367 FlatElementNode fen = (FlatElementNode) fn;
1372 assert rhs.getType() != null;
1373 assert rhs.getType().isArray();
1375 tdElement = rhs.getType().dereference();
1376 fdElement = getArrayField(tdElement);
1378 // before transfer func, possibly inject
1380 if( doEffectsAnalysis && fmContaining != fmAnalysisEntry ) {
1381 if(rblockRel.isPotentialStallSite(fn)) {
1382 // x=y.f, stall y if not accessible
1383 // contributes read effects on stall site of y
1384 // after this, x and y are accessbile.
1385 // if(!rg.isAccessible(rhs)) {
1386 if(!accessible.isAccessible(fn,rhs)) {
1387 rg.taintStallSite(fn, rhs);
1390 rg.makeAccessible(lhs);
1391 rg.makeAccessible(rhs);
1395 if( shouldAnalysisTrack(lhs.getType() ) ) {
1397 rg.assignTempXEqualToTempYFieldF(lhs, rhs, fdElement, fn);
1400 // use transformed graph to do effects analysis
1401 if( doEffectsAnalysis && fmContaining != fmAnalysisEntry ) {
1402 effectsAnalysis.analyzeFlatFieldNode(rg, rhs, fdElement, fn);
1406 case FKind.FlatSetElementNode:
1407 FlatSetElementNode fsen = (FlatSetElementNode) fn;
1409 lhs = fsen.getDst();
1410 rhs = fsen.getSrc();
1412 assert lhs.getType() != null;
1413 assert lhs.getType().isArray();
1415 tdElement = lhs.getType().dereference();
1416 fdElement = getArrayField(tdElement);
1418 // before transfer func, possibly inject
1419 // stall-site taints
1420 if( doEffectsAnalysis && fmContaining != fmAnalysisEntry ) {
1422 if(rblockRel.isPotentialStallSite(fn)) {
1423 // x.y=f , stall x and y if they are not accessible
1424 // also contribute write effects on stall site of x
1425 // if(!rg.isAccessible(lhs)) {
1426 if(!accessible.isAccessible(fn,lhs)) {
1427 rg.taintStallSite(fn, lhs);
1430 // if(!rg.isAccessible(rhs)) {
1431 if(!accessible.isAccessible(fn,rhs)) {
1432 rg.taintStallSite(fn, rhs);
1435 // accessible status update
1436 rg.makeAccessible(lhs);
1437 rg.makeAccessible(rhs);
1441 if( shouldAnalysisTrack(rhs.getType() ) ) {
1442 // transfer func, BUT
1443 // skip this node if it cannot create new reachability paths
1444 if( !arrayReferencees.doesNotCreateNewReaching(fsen) ) {
1445 rg.assignTempXFieldFEqualToTempY(lhs, fdElement, rhs, fn);
1449 // use transformed graph to do effects analysis
1450 if( doEffectsAnalysis && fmContaining != fmAnalysisEntry ) {
1451 effectsAnalysis.analyzeFlatSetFieldNode(rg, lhs, fdElement, fn,
1457 FlatNew fnn = (FlatNew) fn;
1459 if( shouldAnalysisTrack(lhs.getType() ) ) {
1460 AllocSite as = getAllocSiteFromFlatNewPRIVATE(fnn);
1462 // before transform, support effects analysis
1463 if (doEffectsAnalysis && fmContaining != fmAnalysisEntry) {
1464 if (rblockRel.isPotentialStallSite(fn)) {
1465 // after creating new object, lhs is accessible
1466 rg.makeAccessible(lhs);
1471 rg.assignTempEqualToNewAlloc(lhs, as);
1475 case FKind.FlatSESEEnterNode:
1476 sese = (FlatSESEEnterNode) fn;
1478 if( doEffectsAnalysis && fmContaining != fmAnalysisEntry ) {
1480 // always remove ALL stall site taints at enter
1481 rg.removeAllStallSiteTaints();
1483 // inject taints for in-set vars
1484 rg.taintInSetVars(sese);
1489 case FKind.FlatSESEExitNode:
1490 fsexn = (FlatSESEExitNode) fn;
1491 sese = fsexn.getFlatEnter();
1493 if( doEffectsAnalysis && fmContaining != fmAnalysisEntry ) {
1495 // @ sese exit make all live variables
1496 // inaccessible to later parent statements
1497 rg.makeInaccessible(liveness.getLiveInTemps(fmContaining, fn) );
1499 // always remove ALL stall site taints at exit
1500 rg.removeAllStallSiteTaints();
1502 // remove in-set var taints for the exiting rblock
1503 rg.removeInContextTaints(sese);
1508 case FKind.FlatCall: {
1509 Descriptor mdCaller;
1510 if( fmContaining.getMethod() != null ) {
1511 mdCaller = fmContaining.getMethod();
1513 mdCaller = fmContaining.getTask();
1515 FlatCall fc = (FlatCall) fn;
1516 MethodDescriptor mdCallee = fc.getMethod();
1517 FlatMethod fmCallee = state.getMethodFlat(mdCallee);
1521 // all this jimma jamma to debug call sites is WELL WORTH the
1522 // effort, so many bugs or buggy info goes crazy through call
1524 boolean debugCallSite = false;
1525 if( state.DISJOINTDEBUGCALLEE != null &&
1526 state.DISJOINTDEBUGCALLER != null ) {
1528 boolean debugCalleeMatches = false;
1529 boolean debugCallerMatches = false;
1531 ClassDescriptor cdCallee = mdCallee.getClassDesc();
1532 if( cdCallee != null ) {
1533 debugCalleeMatches =
1534 state.DISJOINTDEBUGCALLEE.equals( cdCallee.getSymbol()+
1536 mdCallee.getSymbol()
1541 if( mdCaller instanceof MethodDescriptor ) {
1542 ClassDescriptor cdCaller = ((MethodDescriptor)mdCaller).getClassDesc();
1543 if( cdCaller != null ) {
1544 debugCallerMatches =
1545 state.DISJOINTDEBUGCALLER.equals( cdCaller.getSymbol()+
1547 mdCaller.getSymbol()
1551 // for bristlecone style tasks
1552 debugCallerMatches =
1553 state.DISJOINTDEBUGCALLER.equals( mdCaller.getSymbol() );
1556 debugCallSite = debugCalleeMatches && debugCallerMatches;
1562 boolean writeDebugDOTs = false;
1563 boolean stopAfter = false;
1564 if( debugCallSite ) {
1565 ++ReachGraph.debugCallSiteVisitCounter;
1566 System.out.println(" $$$ Debug call site visit "+
1567 ReachGraph.debugCallSiteVisitCounter+
1571 (ReachGraph.debugCallSiteVisitCounter >=
1572 ReachGraph.debugCallSiteVisitStartCapture) &&
1574 (ReachGraph.debugCallSiteVisitCounter <
1575 ReachGraph.debugCallSiteVisitStartCapture +
1576 ReachGraph.debugCallSiteNumVisitsToCapture)
1578 writeDebugDOTs = true;
1579 System.out.println(" $$$ Capturing this call site visit $$$");
1580 if( ReachGraph.debugCallSiteStopAfter &&
1581 (ReachGraph.debugCallSiteVisitCounter ==
1582 ReachGraph.debugCallSiteVisitStartCapture +
1583 ReachGraph.debugCallSiteNumVisitsToCapture - 1)
1591 // calculate the heap this call site can reach--note this is
1592 // not used for the current call site transform, we are
1593 // grabbing this heap model for future analysis of the callees,
1594 // so if different results emerge we will return to this site
1595 ReachGraph heapForThisCall_old =
1596 getIHMcontribution(mdCallee, fc);
1598 // the computation of the callee-reachable heap
1599 // is useful for making the callee starting point
1600 // and for applying the call site transfer function
1601 Set<Integer> callerNodeIDsCopiedToCallee =
1602 new HashSet<Integer>();
1604 ReachGraph heapForThisCall_cur =
1605 rg.makeCalleeView(fc,
1607 callerNodeIDsCopiedToCallee,
1611 // enforce that a call site contribution can only
1612 // monotonically increase
1613 heapForThisCall_cur.merge(heapForThisCall_old);
1615 if( !heapForThisCall_cur.equals(heapForThisCall_old) ) {
1616 // if heap at call site changed, update the contribution,
1617 // and reschedule the callee for analysis
1618 addIHMcontribution(mdCallee, fc, heapForThisCall_cur);
1620 // map a FlatCall to its enclosing method/task descriptor
1621 // so we can write that info out later
1622 fc2enclosing.put(fc, mdCaller);
1624 if( state.DISJOINTDEBUGSCHEDULING ) {
1625 System.out.println(" context changed, scheduling callee: "+mdCallee);
1628 if( state.DISJOINTDVISITSTACKEESONTOP ) {
1629 calleesToEnqueue.add(mdCallee);
1636 // the transformation for a call site should update the
1637 // current heap abstraction with any effects from the callee,
1638 // or if the method is virtual, the effects from any possible
1639 // callees, so find the set of callees...
1640 Set<MethodDescriptor> setPossibleCallees;
1641 if( determinismDesired ) {
1642 // use an ordered set
1643 setPossibleCallees = new TreeSet<MethodDescriptor>(dComp);
1645 // otherwise use a speedy hashset
1646 setPossibleCallees = new HashSet<MethodDescriptor>();
1649 if( mdCallee.isStatic() ) {
1650 setPossibleCallees.add(mdCallee);
1652 TypeDescriptor typeDesc = fc.getThis().getType();
1653 setPossibleCallees.addAll(callGraph.getMethods(mdCallee,
1658 ReachGraph rgMergeOfPossibleCallers = new ReachGraph();
1660 Iterator<MethodDescriptor> mdItr = setPossibleCallees.iterator();
1661 while( mdItr.hasNext() ) {
1662 MethodDescriptor mdPossible = mdItr.next();
1663 FlatMethod fmPossible = state.getMethodFlat(mdPossible);
1665 addDependent(mdPossible, // callee
1668 // don't alter the working graph (rg) until we compute a
1669 // result for every possible callee, merge them all together,
1670 // then set rg to that
1671 ReachGraph rgPossibleCaller = new ReachGraph();
1672 rgPossibleCaller.merge(rg);
1674 ReachGraph rgPossibleCallee = getPartial(mdPossible);
1676 if( rgPossibleCallee == null ) {
1677 // if this method has never been analyzed just schedule it
1678 // for analysis and skip over this call site for now
1679 if( state.DISJOINTDVISITSTACKEESONTOP ) {
1680 calleesToEnqueue.add(mdPossible);
1682 enqueue(mdPossible);
1685 if( state.DISJOINTDEBUGSCHEDULING ) {
1686 System.out.println(" callee hasn't been analyzed, scheduling: "+mdPossible);
1690 // calculate the method call transform
1691 rgPossibleCaller.resolveMethodCall(fc,
1694 callerNodeIDsCopiedToCallee,
1698 if( doEffectsAnalysis && fmContaining != fmAnalysisEntry ) {
1699 // if( !rgPossibleCallee.isAccessible( ReachGraph.tdReturn ) ) {
1700 if( !accessible.isAccessible(fn, ReachGraph.tdReturn) ) {
1701 rgPossibleCaller.makeInaccessible(fc.getReturnTemp() );
1707 rgMergeOfPossibleCallers.merge(rgPossibleCaller);
1712 System.out.println("$$$ Exiting after requested captures of call site. $$$");
1717 // now that we've taken care of building heap models for
1718 // callee analysis, finish this transformation
1719 rg = rgMergeOfPossibleCallers;
1722 // jjenista: what is this? It breaks compilation
1723 // of programs with no tasks/SESEs/rblocks...
1724 //XXXXXXXXXXXXXXXXXXXXXXXXX
1725 //need to consider more
1726 if( state.OOOJAVA ) {
1727 FlatNode nextFN=fmCallee.getNext(0);
1728 if( nextFN instanceof FlatSESEEnterNode ) {
1729 FlatSESEEnterNode calleeSESE=(FlatSESEEnterNode)nextFN;
1730 if(!calleeSESE.getIsLeafSESE()) {
1731 rg.makeInaccessible(liveness.getLiveInTemps(fmContaining, fn) );
1739 case FKind.FlatReturnNode:
1740 FlatReturnNode frn = (FlatReturnNode) fn;
1741 rhs = frn.getReturnTemp();
1743 // before transfer, do effects analysis support
1744 if( doEffectsAnalysis && fmContaining != fmAnalysisEntry ) {
1745 // if(!rg.isAccessible(rhs)){
1746 if(!accessible.isAccessible(fn,rhs)) {
1747 rg.makeInaccessible(ReachGraph.tdReturn);
1751 if( rhs != null && shouldAnalysisTrack(rhs.getType() ) ) {
1752 rg.assignReturnEqualToTemp(rhs);
1755 setRetNodes.add(frn);
1761 // dead variables were removed before the above transfer function
1762 // was applied, so eliminate heap regions and edges that are no
1763 // longer part of the abstractly-live heap graph, and sweep up
1764 // and reachability effects that are altered by the reduction
1765 //rg.abstractGarbageCollect();
1769 // back edges are strictly monotonic
1770 if( pm.isBackEdge(fn) ) {
1771 ReachGraph rgPrevResult = mapBackEdgeToMonotone.get(fn);
1772 rg.merge(rgPrevResult);
1773 mapBackEdgeToMonotone.put(fn, rg);
1777 ReachGraph rgOnExit = new ReachGraph();
1779 fn2rgAtExit.put(fn, rgOnExit);
1782 // at this point rg should be the correct update
1783 // by an above transfer function, or untouched if
1784 // the flat node type doesn't affect the heap
1790 // this method should generate integers strictly greater than zero!
1791 // special "shadow" regions are made from a heap region by negating
1793 static public Integer generateUniqueHeapRegionNodeID() {
1795 return new Integer(uniqueIDcount);
1800 static public FieldDescriptor getArrayField(TypeDescriptor tdElement) {
1801 FieldDescriptor fdElement = mapTypeToArrayField.get(tdElement);
1802 if( fdElement == null ) {
1803 fdElement = new FieldDescriptor(new Modifiers(Modifiers.PUBLIC),
1805 arrayElementFieldName,
1808 mapTypeToArrayField.put(tdElement, fdElement);
1815 private void writeFinalGraphs() {
1816 Set entrySet = mapDescriptorToCompleteReachGraph.entrySet();
1817 Iterator itr = entrySet.iterator();
1818 while( itr.hasNext() ) {
1819 Map.Entry me = (Map.Entry)itr.next();
1820 Descriptor d = (Descriptor) me.getKey();
1821 ReachGraph rg = (ReachGraph) me.getValue();
1824 if( d instanceof TaskDescriptor ) {
1825 graphName = "COMPLETEtask"+d;
1827 graphName = "COMPLETE"+d;
1830 rg.writeGraph(graphName,
1831 true, // write labels (variables)
1832 true, // selectively hide intermediate temp vars
1833 true, // prune unreachable heap regions
1834 true, // hide reachability altogether
1835 true, // hide subset reachability states
1836 true, // hide predicates
1837 false); // hide edge taints
1841 private void writeFinalIHMs() {
1842 Iterator d2IHMsItr = mapDescriptorToIHMcontributions.entrySet().iterator();
1843 while( d2IHMsItr.hasNext() ) {
1844 Map.Entry me1 = (Map.Entry)d2IHMsItr.next();
1845 Descriptor d = (Descriptor) me1.getKey();
1846 Hashtable<FlatCall, ReachGraph> IHMs = (Hashtable<FlatCall, ReachGraph>)me1.getValue();
1848 Iterator fc2rgItr = IHMs.entrySet().iterator();
1849 while( fc2rgItr.hasNext() ) {
1850 Map.Entry me2 = (Map.Entry)fc2rgItr.next();
1851 FlatCall fc = (FlatCall) me2.getKey();
1852 ReachGraph rg = (ReachGraph) me2.getValue();
1854 rg.writeGraph("IHMPARTFOR"+d+"FROM"+fc2enclosing.get(fc)+fc,
1855 true, // write labels (variables)
1856 true, // selectively hide intermediate temp vars
1857 true, // hide reachability altogether
1858 true, // prune unreachable heap regions
1859 true, // hide subset reachability states
1860 false, // hide predicates
1861 true); // hide edge taints
1866 private void writeInitialContexts() {
1867 Set entrySet = mapDescriptorToInitialContext.entrySet();
1868 Iterator itr = entrySet.iterator();
1869 while( itr.hasNext() ) {
1870 Map.Entry me = (Map.Entry)itr.next();
1871 Descriptor d = (Descriptor) me.getKey();
1872 ReachGraph rg = (ReachGraph) me.getValue();
1874 rg.writeGraph("INITIAL"+d,
1875 true, // write labels (variables)
1876 true, // selectively hide intermediate temp vars
1877 true, // prune unreachable heap regions
1878 false, // hide all reachability
1879 true, // hide subset reachability states
1880 true, // hide predicates
1881 false); // hide edge taints
1886 protected ReachGraph getPartial(Descriptor d) {
1887 return mapDescriptorToCompleteReachGraph.get(d);
1890 protected void setPartial(Descriptor d, ReachGraph rg) {
1891 mapDescriptorToCompleteReachGraph.put(d, rg);
1893 // when the flag for writing out every partial
1894 // result is set, we should spit out the graph,
1895 // but in order to give it a unique name we need
1896 // to track how many partial results for this
1897 // descriptor we've already written out
1898 if( writeAllIncrementalDOTs ) {
1899 if( !mapDescriptorToNumUpdates.containsKey(d) ) {
1900 mapDescriptorToNumUpdates.put(d, new Integer(0) );
1902 Integer n = mapDescriptorToNumUpdates.get(d);
1905 if( d instanceof TaskDescriptor ) {
1906 graphName = d+"COMPLETEtask"+String.format("%05d", n);
1908 graphName = d+"COMPLETE"+String.format("%05d", n);
1911 rg.writeGraph(graphName,
1912 true, // write labels (variables)
1913 true, // selectively hide intermediate temp vars
1914 true, // prune unreachable heap regions
1915 false, // hide all reachability
1916 true, // hide subset reachability states
1917 false, // hide predicates
1918 false); // hide edge taints
1920 mapDescriptorToNumUpdates.put(d, n + 1);
1926 // return just the allocation site associated with one FlatNew node
1927 protected AllocSite getAllocSiteFromFlatNewPRIVATE(FlatNew fnew) {
1929 boolean flagProgrammatically = false;
1930 if( sitesToFlag != null && sitesToFlag.contains(fnew) ) {
1931 flagProgrammatically = true;
1934 if( !mapFlatNewToAllocSite.containsKey(fnew) ) {
1935 AllocSite as = AllocSite.factory(allocationDepth,
1937 fnew.getDisjointId(),
1938 flagProgrammatically
1941 // the newest nodes are single objects
1942 for( int i = 0; i < allocationDepth; ++i ) {
1943 Integer id = generateUniqueHeapRegionNodeID();
1944 as.setIthOldest(i, id);
1945 mapHrnIdToAllocSite.put(id, as);
1948 // the oldest node is a summary node
1949 as.setSummary(generateUniqueHeapRegionNodeID() );
1951 mapFlatNewToAllocSite.put(fnew, as);
1954 return mapFlatNewToAllocSite.get(fnew);
1958 public static boolean shouldAnalysisTrack(TypeDescriptor type) {
1959 // don't track primitive types, but an array
1960 // of primitives is heap memory
1961 if( type.isImmutable() ) {
1962 return type.isArray();
1965 // everything else is an object
1969 protected int numMethodsAnalyzed() {
1970 return descriptorsToAnalyze.size();
1976 // Take in source entry which is the program's compiled entry and
1977 // create a new analysis entry, a method that takes no parameters
1978 // and appears to allocate the command line arguments and call the
1979 // source entry with them. The purpose of this analysis entry is
1980 // to provide a top-level method context with no parameters left.
1981 protected void makeAnalysisEntryMethod(MethodDescriptor mdSourceEntry) {
1983 Modifiers mods = new Modifiers();
1984 mods.addModifier(Modifiers.PUBLIC);
1985 mods.addModifier(Modifiers.STATIC);
1987 TypeDescriptor returnType =
1988 new TypeDescriptor(TypeDescriptor.VOID);
1990 this.mdAnalysisEntry =
1991 new MethodDescriptor(mods,
1993 "analysisEntryMethod"
1996 TempDescriptor cmdLineArgs =
1997 new TempDescriptor("args",
1998 mdSourceEntry.getParamType(0)
2002 new FlatNew(mdSourceEntry.getParamType(0),
2006 this.constructedCmdLineArgsNew = fn;
2008 TempDescriptor[] sourceEntryArgs = new TempDescriptor[1];
2009 sourceEntryArgs[0] = cmdLineArgs;
2012 new FlatCall(mdSourceEntry,
2018 FlatReturnNode frn = new FlatReturnNode(null);
2020 FlatExit fe = new FlatExit();
2022 this.fmAnalysisEntry =
2023 new FlatMethod(mdAnalysisEntry,
2027 this.fmAnalysisEntry.addNext(fn);
2034 protected LinkedList<Descriptor> topologicalSort(Set<Descriptor> toSort) {
2036 Set<Descriptor> discovered;
2038 if( determinismDesired ) {
2039 // use an ordered set
2040 discovered = new TreeSet<Descriptor>(dComp);
2042 // otherwise use a speedy hashset
2043 discovered = new HashSet<Descriptor>();
2046 LinkedList<Descriptor> sorted = new LinkedList<Descriptor>();
2048 Iterator<Descriptor> itr = toSort.iterator();
2049 while( itr.hasNext() ) {
2050 Descriptor d = itr.next();
2052 if( !discovered.contains(d) ) {
2053 dfsVisit(d, toSort, sorted, discovered);
2060 // While we're doing DFS on call graph, remember
2061 // dependencies for efficient queuing of methods
2062 // during interprocedural analysis:
2064 // a dependent of a method decriptor d for this analysis is:
2065 // 1) a method or task that invokes d
2066 // 2) in the descriptorsToAnalyze set
2067 protected void dfsVisit(Descriptor d,
2068 Set <Descriptor> toSort,
2069 LinkedList<Descriptor> sorted,
2070 Set <Descriptor> discovered) {
2073 // only methods have callers, tasks never do
2074 if( d instanceof MethodDescriptor ) {
2076 MethodDescriptor md = (MethodDescriptor) d;
2078 // the call graph is not aware that we have a fabricated
2079 // analysis entry that calls the program source's entry
2080 if( md == mdSourceEntry ) {
2081 if( !discovered.contains(mdAnalysisEntry) ) {
2082 addDependent(mdSourceEntry, // callee
2083 mdAnalysisEntry // caller
2085 dfsVisit(mdAnalysisEntry, toSort, sorted, discovered);
2089 // otherwise call graph guides DFS
2090 Iterator itr = callGraph.getCallerSet(md).iterator();
2091 while( itr.hasNext() ) {
2092 Descriptor dCaller = (Descriptor) itr.next();
2094 // only consider callers in the original set to analyze
2095 if( !toSort.contains(dCaller) ) {
2099 if( !discovered.contains(dCaller) ) {
2100 addDependent(md, // callee
2104 dfsVisit(dCaller, toSort, sorted, discovered);
2109 // for leaf-nodes last now!
2114 protected void enqueue(Descriptor d) {
2116 if( !descriptorsToVisitSet.contains(d) ) {
2118 if( state.DISJOINTDVISITSTACK ||
2119 state.DISJOINTDVISITSTACKEESONTOP
2121 descriptorsToVisitStack.add(d);
2123 } else if( state.DISJOINTDVISITPQUE ) {
2124 Integer priority = mapDescriptorToPriority.get(d);
2125 descriptorsToVisitQ.add(new DescriptorQWrapper(priority,
2130 descriptorsToVisitSet.add(d);
2135 // a dependent of a method decriptor d for this analysis is:
2136 // 1) a method or task that invokes d
2137 // 2) in the descriptorsToAnalyze set
2138 protected void addDependent(Descriptor callee, Descriptor caller) {
2139 Set<Descriptor> deps = mapDescriptorToSetDependents.get(callee);
2140 if( deps == null ) {
2141 deps = new HashSet<Descriptor>();
2144 mapDescriptorToSetDependents.put(callee, deps);
2147 protected Set<Descriptor> getDependents(Descriptor callee) {
2148 Set<Descriptor> deps = mapDescriptorToSetDependents.get(callee);
2149 if( deps == null ) {
2150 deps = new HashSet<Descriptor>();
2151 mapDescriptorToSetDependents.put(callee, deps);
2157 public Hashtable<FlatCall, ReachGraph> getIHMcontributions(Descriptor d) {
2159 Hashtable<FlatCall, ReachGraph> heapsFromCallers =
2160 mapDescriptorToIHMcontributions.get(d);
2162 if( heapsFromCallers == null ) {
2163 heapsFromCallers = new Hashtable<FlatCall, ReachGraph>();
2164 mapDescriptorToIHMcontributions.put(d, heapsFromCallers);
2167 return heapsFromCallers;
2170 public ReachGraph getIHMcontribution(Descriptor d,
2173 Hashtable<FlatCall, ReachGraph> heapsFromCallers =
2174 getIHMcontributions(d);
2176 if( !heapsFromCallers.containsKey(fc) ) {
2180 return heapsFromCallers.get(fc);
2184 public void addIHMcontribution(Descriptor d,
2188 Hashtable<FlatCall, ReachGraph> heapsFromCallers =
2189 getIHMcontributions(d);
2191 heapsFromCallers.put(fc, rg);
2195 private AllocSite createParameterAllocSite(ReachGraph rg,
2196 TempDescriptor tempDesc,
2202 flatNew = new FlatNew(tempDesc.getType(), // type
2203 tempDesc, // param temp
2204 false, // global alloc?
2205 "param"+tempDesc // disjoint site ID string
2208 flatNew = new FlatNew(tempDesc.getType(), // type
2209 tempDesc, // param temp
2210 false, // global alloc?
2211 null // disjoint site ID string
2215 // create allocation site
2216 AllocSite as = AllocSite.factory(allocationDepth,
2218 flatNew.getDisjointId(),
2221 for (int i = 0; i < allocationDepth; ++i) {
2222 Integer id = generateUniqueHeapRegionNodeID();
2223 as.setIthOldest(i, id);
2224 mapHrnIdToAllocSite.put(id, as);
2226 // the oldest node is a summary node
2227 as.setSummary(generateUniqueHeapRegionNodeID() );
2235 private Set<FieldDescriptor> getFieldSetTobeAnalyzed(TypeDescriptor typeDesc) {
2237 Set<FieldDescriptor> fieldSet=new HashSet<FieldDescriptor>();
2238 if(!typeDesc.isImmutable()) {
2239 ClassDescriptor classDesc = typeDesc.getClassDesc();
2240 for (Iterator it = classDesc.getFields(); it.hasNext(); ) {
2241 FieldDescriptor field = (FieldDescriptor) it.next();
2242 TypeDescriptor fieldType = field.getType();
2243 if (shouldAnalysisTrack(fieldType)) {
2244 fieldSet.add(field);
2252 private HeapRegionNode createMultiDeimensionalArrayHRN(ReachGraph rg, AllocSite alloc, HeapRegionNode srcHRN, FieldDescriptor fd, Hashtable<HeapRegionNode, HeapRegionNode> map, Hashtable<TypeDescriptor, HeapRegionNode> mapToExistingNode, ReachSet alpha) {
2254 int dimCount=fd.getType().getArrayCount();
2255 HeapRegionNode prevNode=null;
2256 HeapRegionNode arrayEntryNode=null;
2257 for(int i=dimCount; i>0; i--) {
2258 TypeDescriptor typeDesc=fd.getType().dereference(); //hack to get instance of type desc
2259 typeDesc.setArrayCount(i);
2260 TempDescriptor tempDesc=new TempDescriptor(typeDesc.getSymbol(),typeDesc);
2261 HeapRegionNode hrnSummary;
2262 if(!mapToExistingNode.containsKey(typeDesc)) {
2267 as = createParameterAllocSite(rg, tempDesc, false);
2269 // make a new reference to allocated node
2271 rg.createNewHeapRegionNode(as.getSummary(), // id or null to generate a new one
2272 false, // single object?
2274 false, // out-of-context?
2275 as.getType(), // type
2276 as, // allocation site
2277 alpha, // inherent reach
2278 alpha, // current reach
2279 ExistPredSet.factory(rg.predTrue), // predicates
2280 tempDesc.toString() // description
2282 rg.id2hrn.put(as.getSummary(),hrnSummary);
2284 mapToExistingNode.put(typeDesc, hrnSummary);
2286 hrnSummary=mapToExistingNode.get(typeDesc);
2289 if(prevNode==null) {
2290 // make a new reference between new summary node and source
2291 RefEdge edgeToSummary = new RefEdge(srcHRN, // source
2294 fd.getSymbol(), // field name
2296 ExistPredSet.factory(rg.predTrue), // predicates
2300 rg.addRefEdge(srcHRN, hrnSummary, edgeToSummary);
2301 prevNode=hrnSummary;
2302 arrayEntryNode=hrnSummary;
2304 // make a new reference between summary nodes of array
2305 RefEdge edgeToSummary = new RefEdge(prevNode, // source
2308 arrayElementFieldName, // field name
2310 ExistPredSet.factory(rg.predTrue), // predicates
2314 rg.addRefEdge(prevNode, hrnSummary, edgeToSummary);
2315 prevNode=hrnSummary;
2320 // create a new obj node if obj has at least one non-primitive field
2321 TypeDescriptor type=fd.getType();
2322 if(getFieldSetTobeAnalyzed(type).size()>0) {
2323 TypeDescriptor typeDesc=type.dereference();
2324 typeDesc.setArrayCount(0);
2325 if(!mapToExistingNode.containsKey(typeDesc)) {
2326 TempDescriptor tempDesc=new TempDescriptor(type.getSymbol(),typeDesc);
2327 AllocSite as = createParameterAllocSite(rg, tempDesc, false);
2328 // make a new reference to allocated node
2329 HeapRegionNode hrnSummary =
2330 rg.createNewHeapRegionNode(as.getSummary(), // id or null to generate a new one
2331 false, // single object?
2333 false, // out-of-context?
2335 as, // allocation site
2336 alpha, // inherent reach
2337 alpha, // current reach
2338 ExistPredSet.factory(rg.predTrue), // predicates
2339 tempDesc.toString() // description
2341 rg.id2hrn.put(as.getSummary(),hrnSummary);
2342 mapToExistingNode.put(typeDesc, hrnSummary);
2343 RefEdge edgeToSummary = new RefEdge(prevNode, // source
2346 arrayElementFieldName, // field name
2348 ExistPredSet.factory(rg.predTrue), // predicates
2351 rg.addRefEdge(prevNode, hrnSummary, edgeToSummary);
2352 prevNode=hrnSummary;
2354 HeapRegionNode hrnSummary=mapToExistingNode.get(typeDesc);
2355 if(prevNode.getReferenceTo(hrnSummary, typeDesc, arrayElementFieldName)==null) {
2356 RefEdge edgeToSummary = new RefEdge(prevNode, // source
2359 arrayElementFieldName, // field name
2361 ExistPredSet.factory(rg.predTrue), // predicates
2364 rg.addRefEdge(prevNode, hrnSummary, edgeToSummary);
2366 prevNode=hrnSummary;
2370 map.put(arrayEntryNode, prevNode);
2371 return arrayEntryNode;
2374 private ReachGraph createInitialTaskReachGraph(FlatMethod fm) {
2375 ReachGraph rg = new ReachGraph();
2376 TaskDescriptor taskDesc = fm.getTask();
2378 for (int idx = 0; idx < taskDesc.numParameters(); idx++) {
2379 Descriptor paramDesc = taskDesc.getParameter(idx);
2380 TypeDescriptor paramTypeDesc = taskDesc.getParamType(idx);
2382 // setup data structure
2383 Set<HashMap<HeapRegionNode, FieldDescriptor>> workSet =
2384 new HashSet<HashMap<HeapRegionNode, FieldDescriptor>>();
2385 Hashtable<TypeDescriptor, HeapRegionNode> mapTypeToExistingSummaryNode =
2386 new Hashtable<TypeDescriptor, HeapRegionNode>();
2387 Hashtable<HeapRegionNode, HeapRegionNode> mapToFirstDimensionArrayNode =
2388 new Hashtable<HeapRegionNode, HeapRegionNode>();
2389 Set<String> doneSet = new HashSet<String>();
2391 TempDescriptor tempDesc = fm.getParameter(idx);
2393 AllocSite as = createParameterAllocSite(rg, tempDesc, true);
2394 VariableNode lnX = rg.getVariableNodeFromTemp(tempDesc);
2395 Integer idNewest = as.getIthOldest(0);
2396 HeapRegionNode hrnNewest = rg.id2hrn.get(idNewest);
2398 // make a new reference to allocated node
2399 RefEdge edgeNew = new RefEdge(lnX, // source
2401 taskDesc.getParamType(idx), // type
2403 hrnNewest.getAlpha(), // beta
2404 ExistPredSet.factory(rg.predTrue), // predicates
2407 rg.addRefEdge(lnX, hrnNewest, edgeNew);
2409 // set-up a work set for class field
2410 ClassDescriptor classDesc = paramTypeDesc.getClassDesc();
2411 for (Iterator it = classDesc.getFields(); it.hasNext(); ) {
2412 FieldDescriptor fd = (FieldDescriptor) it.next();
2413 TypeDescriptor fieldType = fd.getType();
2414 if (shouldAnalysisTrack(fieldType)) {
2415 HashMap<HeapRegionNode, FieldDescriptor> newMap = new HashMap<HeapRegionNode, FieldDescriptor>();
2416 newMap.put(hrnNewest, fd);
2417 workSet.add(newMap);
2421 int uniqueIdentifier = 0;
2422 while (!workSet.isEmpty()) {
2423 HashMap<HeapRegionNode, FieldDescriptor> map = workSet
2425 workSet.remove(map);
2427 Set<HeapRegionNode> key = map.keySet();
2428 HeapRegionNode srcHRN = key.iterator().next();
2429 FieldDescriptor fd = map.get(srcHRN);
2430 TypeDescriptor type = fd.getType();
2431 String doneSetIdentifier = srcHRN.getIDString() + "_" + fd;
2433 if (!doneSet.contains(doneSetIdentifier)) {
2434 doneSet.add(doneSetIdentifier);
2435 if (!mapTypeToExistingSummaryNode.containsKey(type)) {
2436 // create new summary Node
2437 TempDescriptor td = new TempDescriptor("temp"
2438 + uniqueIdentifier, type);
2440 AllocSite allocSite;
2441 if(type.equals(paramTypeDesc)) {
2442 //corresponding allocsite has already been created for a parameter variable.
2445 allocSite = createParameterAllocSite(rg, td, false);
2447 String strDesc = allocSite.toStringForDOT()
2449 TypeDescriptor allocType=allocSite.getType();
2451 HeapRegionNode hrnSummary;
2452 if(allocType.isArray() && allocType.getArrayCount()>0) {
2453 hrnSummary=createMultiDeimensionalArrayHRN(rg,allocSite,srcHRN,fd,mapToFirstDimensionArrayNode,mapTypeToExistingSummaryNode,hrnNewest.getAlpha());
2456 rg.createNewHeapRegionNode(allocSite.getSummary(), // id or null to generate a new one
2457 false, // single object?
2459 false, // out-of-context?
2460 allocSite.getType(), // type
2461 allocSite, // allocation site
2462 hrnNewest.getAlpha(), // inherent reach
2463 hrnNewest.getAlpha(), // current reach
2464 ExistPredSet.factory(rg.predTrue), // predicates
2465 strDesc // description
2467 rg.id2hrn.put(allocSite.getSummary(),hrnSummary);
2469 // make a new reference to summary node
2470 RefEdge edgeToSummary = new RefEdge(srcHRN, // source
2473 fd.getSymbol(), // field name
2474 hrnNewest.getAlpha(), // beta
2475 ExistPredSet.factory(rg.predTrue), // predicates
2479 rg.addRefEdge(srcHRN, hrnSummary, edgeToSummary);
2483 mapTypeToExistingSummaryNode.put(type, hrnSummary);
2485 // set-up a work set for fields of the class
2486 Set<FieldDescriptor> fieldTobeAnalyzed=getFieldSetTobeAnalyzed(type);
2487 for (Iterator iterator = fieldTobeAnalyzed.iterator(); iterator
2489 FieldDescriptor fieldDescriptor = (FieldDescriptor) iterator
2491 HeapRegionNode newDstHRN;
2492 if(mapToFirstDimensionArrayNode.containsKey(hrnSummary)) {
2493 //related heap region node is already exsited.
2494 newDstHRN=mapToFirstDimensionArrayNode.get(hrnSummary);
2496 newDstHRN=hrnSummary;
2498 doneSetIdentifier = newDstHRN.getIDString() + "_" + fieldDescriptor;
2499 if(!doneSet.contains(doneSetIdentifier)) {
2500 // add new work item
2501 HashMap<HeapRegionNode, FieldDescriptor> newMap =
2502 new HashMap<HeapRegionNode, FieldDescriptor>();
2503 newMap.put(newDstHRN, fieldDescriptor);
2504 workSet.add(newMap);
2509 // if there exists corresponding summary node
2510 HeapRegionNode hrnDst=mapTypeToExistingSummaryNode.get(type);
2512 RefEdge edgeToSummary = new RefEdge(srcHRN, // source
2514 fd.getType(), // type
2515 fd.getSymbol(), // field name
2516 srcHRN.getAlpha(), // beta
2517 ExistPredSet.factory(rg.predTrue), // predicates
2520 rg.addRefEdge(srcHRN, hrnDst, edgeToSummary);
2530 // return all allocation sites in the method (there is one allocation
2531 // site per FlatNew node in a method)
2532 private HashSet<AllocSite> getAllocationSiteSet(Descriptor d) {
2533 if( !mapDescriptorToAllocSiteSet.containsKey(d) ) {
2534 buildAllocationSiteSet(d);
2537 return mapDescriptorToAllocSiteSet.get(d);
2541 private void buildAllocationSiteSet(Descriptor d) {
2542 HashSet<AllocSite> s = new HashSet<AllocSite>();
2545 if( d instanceof MethodDescriptor ) {
2546 fm = state.getMethodFlat( (MethodDescriptor) d);
2548 assert d instanceof TaskDescriptor;
2549 fm = state.getMethodFlat( (TaskDescriptor) d);
2551 pm.analyzeMethod(fm);
2553 // visit every node in this FlatMethod's IR graph
2554 // and make a set of the allocation sites from the
2555 // FlatNew node's visited
2556 HashSet<FlatNode> visited = new HashSet<FlatNode>();
2557 HashSet<FlatNode> toVisit = new HashSet<FlatNode>();
2560 while( !toVisit.isEmpty() ) {
2561 FlatNode n = toVisit.iterator().next();
2563 if( n instanceof FlatNew ) {
2564 s.add(getAllocSiteFromFlatNewPRIVATE( (FlatNew) n) );
2570 for( int i = 0; i < pm.numNext(n); ++i ) {
2571 FlatNode child = pm.getNext(n, i);
2572 if( !visited.contains(child) ) {
2578 mapDescriptorToAllocSiteSet.put(d, s);
2581 private HashSet<AllocSite> getFlaggedAllocationSites(Descriptor dIn) {
2583 HashSet<AllocSite> out = new HashSet<AllocSite>();
2584 HashSet<Descriptor> toVisit = new HashSet<Descriptor>();
2585 HashSet<Descriptor> visited = new HashSet<Descriptor>();
2589 while (!toVisit.isEmpty()) {
2590 Descriptor d = toVisit.iterator().next();
2594 HashSet<AllocSite> asSet = getAllocationSiteSet(d);
2595 Iterator asItr = asSet.iterator();
2596 while (asItr.hasNext()) {
2597 AllocSite as = (AllocSite) asItr.next();
2598 if (as.getDisjointAnalysisId() != null) {
2603 // enqueue callees of this method to be searched for
2604 // allocation sites also
2605 Set callees = callGraph.getCalleeSet(d);
2606 if (callees != null) {
2607 Iterator methItr = callees.iterator();
2608 while (methItr.hasNext()) {
2609 MethodDescriptor md = (MethodDescriptor) methItr.next();
2611 if (!visited.contains(md)) {
2622 private HashSet<AllocSite>
2623 getFlaggedAllocationSitesReachableFromTaskPRIVATE(TaskDescriptor td) {
2625 HashSet<AllocSite> asSetTotal = new HashSet<AllocSite>();
2626 HashSet<Descriptor> toVisit = new HashSet<Descriptor>();
2627 HashSet<Descriptor> visited = new HashSet<Descriptor>();
2631 // traverse this task and all methods reachable from this task
2632 while( !toVisit.isEmpty() ) {
2633 Descriptor d = toVisit.iterator().next();
2637 HashSet<AllocSite> asSet = getAllocationSiteSet(d);
2638 Iterator asItr = asSet.iterator();
2639 while( asItr.hasNext() ) {
2640 AllocSite as = (AllocSite) asItr.next();
2641 TypeDescriptor typed = as.getType();
2642 if( typed != null ) {
2643 ClassDescriptor cd = typed.getClassDesc();
2644 if( cd != null && cd.hasFlags() ) {
2650 // enqueue callees of this method to be searched for
2651 // allocation sites also
2652 Set callees = callGraph.getCalleeSet(d);
2653 if( callees != null ) {
2654 Iterator methItr = callees.iterator();
2655 while( methItr.hasNext() ) {
2656 MethodDescriptor md = (MethodDescriptor) methItr.next();
2658 if( !visited.contains(md) ) {
2668 public Set<Descriptor> getDescriptorsToAnalyze() {
2669 return descriptorsToAnalyze;
2672 public EffectsAnalysis getEffectsAnalysis() {
2673 return effectsAnalysis;
2676 public ReachGraph getReachGraph(Descriptor d) {
2677 return mapDescriptorToCompleteReachGraph.get(d);
2680 public ReachGraph getEnterReachGraph(FlatNode fn) {
2681 return fn2rgAtEnter.get(fn);
2684 // get successive captures of the analysis state, use compiler
2686 boolean takeDebugSnapshots = false;
2687 String descSymbolDebug = null;
2688 boolean stopAfterCapture = false;
2689 int snapVisitCounter = 0;
2690 int snapNodeCounter = 0;
2691 int visitStartCapture = 0;
2692 int numVisitsToCapture = 0;
2695 void debugSnapshot(ReachGraph rg, FlatNode fn, boolean in) {
2696 if( snapVisitCounter > visitStartCapture + numVisitsToCapture ) {
2704 if( snapVisitCounter >= visitStartCapture ) {
2705 System.out.println(" @@@ snapping visit="+snapVisitCounter+
2706 ", node="+snapNodeCounter+
2710 graphName = String.format("snap%03d_%04din",
2714 graphName = String.format("snap%03d_%04dout",
2719 graphName = graphName + fn;
2721 rg.writeGraph(graphName,
2722 true, // write labels (variables)
2723 true, // selectively hide intermediate temp vars
2724 true, // prune unreachable heap regions
2725 false, // hide reachability
2726 false, // hide subset reachability states
2727 true, // hide predicates
2728 true); // hide edge taints
2735 public Set<Alloc> canPointToAt( TempDescriptor x,
2736 FlatNode programPoint ) {
2738 ReachGraph rgAtEnter = fn2rgAtEnter.get( programPoint );
2739 if( rgAtEnter == null ) {
2743 return rgAtEnter.canPointTo( x );
2747 public Set<Alloc> canPointToAfter( TempDescriptor x,
2748 FlatNode programPoint ) {
2750 ReachGraph rgAtExit = fn2rgAtExit.get( programPoint );
2751 if( rgAtExit == null ) {
2755 return rgAtExit.canPointTo( x );
2759 public Hashtable< Alloc, Set<Alloc> > canPointToAt( TempDescriptor x,
2761 FlatNode programPoint ) {
2763 ReachGraph rgAtEnter = fn2rgAtEnter.get( programPoint );
2764 if( rgAtEnter == null ) {
2768 return rgAtEnter.canPointTo( x, f.getSymbol() );
2772 public Hashtable< Alloc, Set<Alloc> > canPointToAtElement( TempDescriptor x,
2773 FlatNode programPoint ) {
2775 ReachGraph rgAtEnter = fn2rgAtEnter.get( programPoint );
2776 if( rgAtEnter == null ) {
2780 assert x.getType() != null;
2781 assert x.getType().isArray();
2783 return rgAtEnter.canPointTo( x, arrayElementFieldName );