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 FlatNode nextFN=fmCallee.getNext(0);
1727 if( nextFN instanceof FlatSESEEnterNode ) {
1728 FlatSESEEnterNode calleeSESE=(FlatSESEEnterNode)nextFN;
1729 if(!calleeSESE.getIsLeafSESE()) {
1730 rg.makeInaccessible(liveness.getLiveInTemps(fmContaining, fn) );
1737 case FKind.FlatReturnNode:
1738 FlatReturnNode frn = (FlatReturnNode) fn;
1739 rhs = frn.getReturnTemp();
1741 // before transfer, do effects analysis support
1742 if( doEffectsAnalysis && fmContaining != fmAnalysisEntry ) {
1743 // if(!rg.isAccessible(rhs)){
1744 if(!accessible.isAccessible(fn,rhs)) {
1745 rg.makeInaccessible(ReachGraph.tdReturn);
1749 if( rhs != null && shouldAnalysisTrack(rhs.getType() ) ) {
1750 rg.assignReturnEqualToTemp(rhs);
1753 setRetNodes.add(frn);
1759 // dead variables were removed before the above transfer function
1760 // was applied, so eliminate heap regions and edges that are no
1761 // longer part of the abstractly-live heap graph, and sweep up
1762 // and reachability effects that are altered by the reduction
1763 //rg.abstractGarbageCollect();
1767 // back edges are strictly monotonic
1768 if( pm.isBackEdge(fn) ) {
1769 ReachGraph rgPrevResult = mapBackEdgeToMonotone.get(fn);
1770 rg.merge(rgPrevResult);
1771 mapBackEdgeToMonotone.put(fn, rg);
1775 ReachGraph rgOnExit = new ReachGraph();
1777 fn2rgAtExit.put(fn, rgOnExit);
1780 // at this point rg should be the correct update
1781 // by an above transfer function, or untouched if
1782 // the flat node type doesn't affect the heap
1788 // this method should generate integers strictly greater than zero!
1789 // special "shadow" regions are made from a heap region by negating
1791 static public Integer generateUniqueHeapRegionNodeID() {
1793 return new Integer(uniqueIDcount);
1798 static public FieldDescriptor getArrayField(TypeDescriptor tdElement) {
1799 FieldDescriptor fdElement = mapTypeToArrayField.get(tdElement);
1800 if( fdElement == null ) {
1801 fdElement = new FieldDescriptor(new Modifiers(Modifiers.PUBLIC),
1803 arrayElementFieldName,
1806 mapTypeToArrayField.put(tdElement, fdElement);
1813 private void writeFinalGraphs() {
1814 Set entrySet = mapDescriptorToCompleteReachGraph.entrySet();
1815 Iterator itr = entrySet.iterator();
1816 while( itr.hasNext() ) {
1817 Map.Entry me = (Map.Entry)itr.next();
1818 Descriptor d = (Descriptor) me.getKey();
1819 ReachGraph rg = (ReachGraph) me.getValue();
1822 if( d instanceof TaskDescriptor ) {
1823 graphName = "COMPLETEtask"+d;
1825 graphName = "COMPLETE"+d;
1828 rg.writeGraph(graphName,
1829 true, // write labels (variables)
1830 true, // selectively hide intermediate temp vars
1831 true, // prune unreachable heap regions
1832 true, // hide reachability altogether
1833 true, // hide subset reachability states
1834 true, // hide predicates
1835 false); // hide edge taints
1839 private void writeFinalIHMs() {
1840 Iterator d2IHMsItr = mapDescriptorToIHMcontributions.entrySet().iterator();
1841 while( d2IHMsItr.hasNext() ) {
1842 Map.Entry me1 = (Map.Entry)d2IHMsItr.next();
1843 Descriptor d = (Descriptor) me1.getKey();
1844 Hashtable<FlatCall, ReachGraph> IHMs = (Hashtable<FlatCall, ReachGraph>)me1.getValue();
1846 Iterator fc2rgItr = IHMs.entrySet().iterator();
1847 while( fc2rgItr.hasNext() ) {
1848 Map.Entry me2 = (Map.Entry)fc2rgItr.next();
1849 FlatCall fc = (FlatCall) me2.getKey();
1850 ReachGraph rg = (ReachGraph) me2.getValue();
1852 rg.writeGraph("IHMPARTFOR"+d+"FROM"+fc2enclosing.get(fc)+fc,
1853 true, // write labels (variables)
1854 true, // selectively hide intermediate temp vars
1855 true, // hide reachability altogether
1856 true, // prune unreachable heap regions
1857 true, // hide subset reachability states
1858 false, // hide predicates
1859 true); // hide edge taints
1864 private void writeInitialContexts() {
1865 Set entrySet = mapDescriptorToInitialContext.entrySet();
1866 Iterator itr = entrySet.iterator();
1867 while( itr.hasNext() ) {
1868 Map.Entry me = (Map.Entry)itr.next();
1869 Descriptor d = (Descriptor) me.getKey();
1870 ReachGraph rg = (ReachGraph) me.getValue();
1872 rg.writeGraph("INITIAL"+d,
1873 true, // write labels (variables)
1874 true, // selectively hide intermediate temp vars
1875 true, // prune unreachable heap regions
1876 false, // hide all reachability
1877 true, // hide subset reachability states
1878 true, // hide predicates
1879 false); // hide edge taints
1884 protected ReachGraph getPartial(Descriptor d) {
1885 return mapDescriptorToCompleteReachGraph.get(d);
1888 protected void setPartial(Descriptor d, ReachGraph rg) {
1889 mapDescriptorToCompleteReachGraph.put(d, rg);
1891 // when the flag for writing out every partial
1892 // result is set, we should spit out the graph,
1893 // but in order to give it a unique name we need
1894 // to track how many partial results for this
1895 // descriptor we've already written out
1896 if( writeAllIncrementalDOTs ) {
1897 if( !mapDescriptorToNumUpdates.containsKey(d) ) {
1898 mapDescriptorToNumUpdates.put(d, new Integer(0) );
1900 Integer n = mapDescriptorToNumUpdates.get(d);
1903 if( d instanceof TaskDescriptor ) {
1904 graphName = d+"COMPLETEtask"+String.format("%05d", n);
1906 graphName = d+"COMPLETE"+String.format("%05d", n);
1909 rg.writeGraph(graphName,
1910 true, // write labels (variables)
1911 true, // selectively hide intermediate temp vars
1912 true, // prune unreachable heap regions
1913 false, // hide all reachability
1914 true, // hide subset reachability states
1915 false, // hide predicates
1916 false); // hide edge taints
1918 mapDescriptorToNumUpdates.put(d, n + 1);
1924 // return just the allocation site associated with one FlatNew node
1925 protected AllocSite getAllocSiteFromFlatNewPRIVATE(FlatNew fnew) {
1927 boolean flagProgrammatically = false;
1928 if( sitesToFlag != null && sitesToFlag.contains(fnew) ) {
1929 flagProgrammatically = true;
1932 if( !mapFlatNewToAllocSite.containsKey(fnew) ) {
1933 AllocSite as = AllocSite.factory(allocationDepth,
1935 fnew.getDisjointId(),
1936 flagProgrammatically
1939 // the newest nodes are single objects
1940 for( int i = 0; i < allocationDepth; ++i ) {
1941 Integer id = generateUniqueHeapRegionNodeID();
1942 as.setIthOldest(i, id);
1943 mapHrnIdToAllocSite.put(id, as);
1946 // the oldest node is a summary node
1947 as.setSummary(generateUniqueHeapRegionNodeID() );
1949 mapFlatNewToAllocSite.put(fnew, as);
1952 return mapFlatNewToAllocSite.get(fnew);
1956 public static boolean shouldAnalysisTrack(TypeDescriptor type) {
1957 // don't track primitive types, but an array
1958 // of primitives is heap memory
1959 if( type.isImmutable() ) {
1960 return type.isArray();
1963 // everything else is an object
1967 protected int numMethodsAnalyzed() {
1968 return descriptorsToAnalyze.size();
1974 // Take in source entry which is the program's compiled entry and
1975 // create a new analysis entry, a method that takes no parameters
1976 // and appears to allocate the command line arguments and call the
1977 // source entry with them. The purpose of this analysis entry is
1978 // to provide a top-level method context with no parameters left.
1979 protected void makeAnalysisEntryMethod(MethodDescriptor mdSourceEntry) {
1981 Modifiers mods = new Modifiers();
1982 mods.addModifier(Modifiers.PUBLIC);
1983 mods.addModifier(Modifiers.STATIC);
1985 TypeDescriptor returnType =
1986 new TypeDescriptor(TypeDescriptor.VOID);
1988 this.mdAnalysisEntry =
1989 new MethodDescriptor(mods,
1991 "analysisEntryMethod"
1994 TempDescriptor cmdLineArgs =
1995 new TempDescriptor("args",
1996 mdSourceEntry.getParamType(0)
2000 new FlatNew(mdSourceEntry.getParamType(0),
2004 this.constructedCmdLineArgsNew = fn;
2006 TempDescriptor[] sourceEntryArgs = new TempDescriptor[1];
2007 sourceEntryArgs[0] = cmdLineArgs;
2010 new FlatCall(mdSourceEntry,
2016 FlatReturnNode frn = new FlatReturnNode(null);
2018 FlatExit fe = new FlatExit();
2020 this.fmAnalysisEntry =
2021 new FlatMethod(mdAnalysisEntry,
2025 this.fmAnalysisEntry.addNext(fn);
2032 protected LinkedList<Descriptor> topologicalSort(Set<Descriptor> toSort) {
2034 Set<Descriptor> discovered;
2036 if( determinismDesired ) {
2037 // use an ordered set
2038 discovered = new TreeSet<Descriptor>(dComp);
2040 // otherwise use a speedy hashset
2041 discovered = new HashSet<Descriptor>();
2044 LinkedList<Descriptor> sorted = new LinkedList<Descriptor>();
2046 Iterator<Descriptor> itr = toSort.iterator();
2047 while( itr.hasNext() ) {
2048 Descriptor d = itr.next();
2050 if( !discovered.contains(d) ) {
2051 dfsVisit(d, toSort, sorted, discovered);
2058 // While we're doing DFS on call graph, remember
2059 // dependencies for efficient queuing of methods
2060 // during interprocedural analysis:
2062 // a dependent of a method decriptor d for this analysis is:
2063 // 1) a method or task that invokes d
2064 // 2) in the descriptorsToAnalyze set
2065 protected void dfsVisit(Descriptor d,
2066 Set <Descriptor> toSort,
2067 LinkedList<Descriptor> sorted,
2068 Set <Descriptor> discovered) {
2071 // only methods have callers, tasks never do
2072 if( d instanceof MethodDescriptor ) {
2074 MethodDescriptor md = (MethodDescriptor) d;
2076 // the call graph is not aware that we have a fabricated
2077 // analysis entry that calls the program source's entry
2078 if( md == mdSourceEntry ) {
2079 if( !discovered.contains(mdAnalysisEntry) ) {
2080 addDependent(mdSourceEntry, // callee
2081 mdAnalysisEntry // caller
2083 dfsVisit(mdAnalysisEntry, toSort, sorted, discovered);
2087 // otherwise call graph guides DFS
2088 Iterator itr = callGraph.getCallerSet(md).iterator();
2089 while( itr.hasNext() ) {
2090 Descriptor dCaller = (Descriptor) itr.next();
2092 // only consider callers in the original set to analyze
2093 if( !toSort.contains(dCaller) ) {
2097 if( !discovered.contains(dCaller) ) {
2098 addDependent(md, // callee
2102 dfsVisit(dCaller, toSort, sorted, discovered);
2107 // for leaf-nodes last now!
2112 protected void enqueue(Descriptor d) {
2114 if( !descriptorsToVisitSet.contains(d) ) {
2116 if( state.DISJOINTDVISITSTACK ||
2117 state.DISJOINTDVISITSTACKEESONTOP
2119 descriptorsToVisitStack.add(d);
2121 } else if( state.DISJOINTDVISITPQUE ) {
2122 Integer priority = mapDescriptorToPriority.get(d);
2123 descriptorsToVisitQ.add(new DescriptorQWrapper(priority,
2128 descriptorsToVisitSet.add(d);
2133 // a dependent of a method decriptor d for this analysis is:
2134 // 1) a method or task that invokes d
2135 // 2) in the descriptorsToAnalyze set
2136 protected void addDependent(Descriptor callee, Descriptor caller) {
2137 Set<Descriptor> deps = mapDescriptorToSetDependents.get(callee);
2138 if( deps == null ) {
2139 deps = new HashSet<Descriptor>();
2142 mapDescriptorToSetDependents.put(callee, deps);
2145 protected Set<Descriptor> getDependents(Descriptor callee) {
2146 Set<Descriptor> deps = mapDescriptorToSetDependents.get(callee);
2147 if( deps == null ) {
2148 deps = new HashSet<Descriptor>();
2149 mapDescriptorToSetDependents.put(callee, deps);
2155 public Hashtable<FlatCall, ReachGraph> getIHMcontributions(Descriptor d) {
2157 Hashtable<FlatCall, ReachGraph> heapsFromCallers =
2158 mapDescriptorToIHMcontributions.get(d);
2160 if( heapsFromCallers == null ) {
2161 heapsFromCallers = new Hashtable<FlatCall, ReachGraph>();
2162 mapDescriptorToIHMcontributions.put(d, heapsFromCallers);
2165 return heapsFromCallers;
2168 public ReachGraph getIHMcontribution(Descriptor d,
2171 Hashtable<FlatCall, ReachGraph> heapsFromCallers =
2172 getIHMcontributions(d);
2174 if( !heapsFromCallers.containsKey(fc) ) {
2178 return heapsFromCallers.get(fc);
2182 public void addIHMcontribution(Descriptor d,
2186 Hashtable<FlatCall, ReachGraph> heapsFromCallers =
2187 getIHMcontributions(d);
2189 heapsFromCallers.put(fc, rg);
2193 private AllocSite createParameterAllocSite(ReachGraph rg,
2194 TempDescriptor tempDesc,
2200 flatNew = new FlatNew(tempDesc.getType(), // type
2201 tempDesc, // param temp
2202 false, // global alloc?
2203 "param"+tempDesc // disjoint site ID string
2206 flatNew = new FlatNew(tempDesc.getType(), // type
2207 tempDesc, // param temp
2208 false, // global alloc?
2209 null // disjoint site ID string
2213 // create allocation site
2214 AllocSite as = AllocSite.factory(allocationDepth,
2216 flatNew.getDisjointId(),
2219 for (int i = 0; i < allocationDepth; ++i) {
2220 Integer id = generateUniqueHeapRegionNodeID();
2221 as.setIthOldest(i, id);
2222 mapHrnIdToAllocSite.put(id, as);
2224 // the oldest node is a summary node
2225 as.setSummary(generateUniqueHeapRegionNodeID() );
2233 private Set<FieldDescriptor> getFieldSetTobeAnalyzed(TypeDescriptor typeDesc) {
2235 Set<FieldDescriptor> fieldSet=new HashSet<FieldDescriptor>();
2236 if(!typeDesc.isImmutable()) {
2237 ClassDescriptor classDesc = typeDesc.getClassDesc();
2238 for (Iterator it = classDesc.getFields(); it.hasNext(); ) {
2239 FieldDescriptor field = (FieldDescriptor) it.next();
2240 TypeDescriptor fieldType = field.getType();
2241 if (shouldAnalysisTrack(fieldType)) {
2242 fieldSet.add(field);
2250 private HeapRegionNode createMultiDeimensionalArrayHRN(ReachGraph rg, AllocSite alloc, HeapRegionNode srcHRN, FieldDescriptor fd, Hashtable<HeapRegionNode, HeapRegionNode> map, Hashtable<TypeDescriptor, HeapRegionNode> mapToExistingNode, ReachSet alpha) {
2252 int dimCount=fd.getType().getArrayCount();
2253 HeapRegionNode prevNode=null;
2254 HeapRegionNode arrayEntryNode=null;
2255 for(int i=dimCount; i>0; i--) {
2256 TypeDescriptor typeDesc=fd.getType().dereference(); //hack to get instance of type desc
2257 typeDesc.setArrayCount(i);
2258 TempDescriptor tempDesc=new TempDescriptor(typeDesc.getSymbol(),typeDesc);
2259 HeapRegionNode hrnSummary;
2260 if(!mapToExistingNode.containsKey(typeDesc)) {
2265 as = createParameterAllocSite(rg, tempDesc, false);
2267 // make a new reference to allocated node
2269 rg.createNewHeapRegionNode(as.getSummary(), // id or null to generate a new one
2270 false, // single object?
2272 false, // out-of-context?
2273 as.getType(), // type
2274 as, // allocation site
2275 alpha, // inherent reach
2276 alpha, // current reach
2277 ExistPredSet.factory(rg.predTrue), // predicates
2278 tempDesc.toString() // description
2280 rg.id2hrn.put(as.getSummary(),hrnSummary);
2282 mapToExistingNode.put(typeDesc, hrnSummary);
2284 hrnSummary=mapToExistingNode.get(typeDesc);
2287 if(prevNode==null) {
2288 // make a new reference between new summary node and source
2289 RefEdge edgeToSummary = new RefEdge(srcHRN, // source
2292 fd.getSymbol(), // field name
2294 ExistPredSet.factory(rg.predTrue), // predicates
2298 rg.addRefEdge(srcHRN, hrnSummary, edgeToSummary);
2299 prevNode=hrnSummary;
2300 arrayEntryNode=hrnSummary;
2302 // make a new reference between summary nodes of array
2303 RefEdge edgeToSummary = new RefEdge(prevNode, // source
2306 arrayElementFieldName, // field name
2308 ExistPredSet.factory(rg.predTrue), // predicates
2312 rg.addRefEdge(prevNode, hrnSummary, edgeToSummary);
2313 prevNode=hrnSummary;
2318 // create a new obj node if obj has at least one non-primitive field
2319 TypeDescriptor type=fd.getType();
2320 if(getFieldSetTobeAnalyzed(type).size()>0) {
2321 TypeDescriptor typeDesc=type.dereference();
2322 typeDesc.setArrayCount(0);
2323 if(!mapToExistingNode.containsKey(typeDesc)) {
2324 TempDescriptor tempDesc=new TempDescriptor(type.getSymbol(),typeDesc);
2325 AllocSite as = createParameterAllocSite(rg, tempDesc, false);
2326 // make a new reference to allocated node
2327 HeapRegionNode hrnSummary =
2328 rg.createNewHeapRegionNode(as.getSummary(), // id or null to generate a new one
2329 false, // single object?
2331 false, // out-of-context?
2333 as, // allocation site
2334 alpha, // inherent reach
2335 alpha, // current reach
2336 ExistPredSet.factory(rg.predTrue), // predicates
2337 tempDesc.toString() // description
2339 rg.id2hrn.put(as.getSummary(),hrnSummary);
2340 mapToExistingNode.put(typeDesc, hrnSummary);
2341 RefEdge edgeToSummary = new RefEdge(prevNode, // source
2344 arrayElementFieldName, // field name
2346 ExistPredSet.factory(rg.predTrue), // predicates
2349 rg.addRefEdge(prevNode, hrnSummary, edgeToSummary);
2350 prevNode=hrnSummary;
2352 HeapRegionNode hrnSummary=mapToExistingNode.get(typeDesc);
2353 if(prevNode.getReferenceTo(hrnSummary, typeDesc, arrayElementFieldName)==null) {
2354 RefEdge edgeToSummary = new RefEdge(prevNode, // source
2357 arrayElementFieldName, // field name
2359 ExistPredSet.factory(rg.predTrue), // predicates
2362 rg.addRefEdge(prevNode, hrnSummary, edgeToSummary);
2364 prevNode=hrnSummary;
2368 map.put(arrayEntryNode, prevNode);
2369 return arrayEntryNode;
2372 private ReachGraph createInitialTaskReachGraph(FlatMethod fm) {
2373 ReachGraph rg = new ReachGraph();
2374 TaskDescriptor taskDesc = fm.getTask();
2376 for (int idx = 0; idx < taskDesc.numParameters(); idx++) {
2377 Descriptor paramDesc = taskDesc.getParameter(idx);
2378 TypeDescriptor paramTypeDesc = taskDesc.getParamType(idx);
2380 // setup data structure
2381 Set<HashMap<HeapRegionNode, FieldDescriptor>> workSet =
2382 new HashSet<HashMap<HeapRegionNode, FieldDescriptor>>();
2383 Hashtable<TypeDescriptor, HeapRegionNode> mapTypeToExistingSummaryNode =
2384 new Hashtable<TypeDescriptor, HeapRegionNode>();
2385 Hashtable<HeapRegionNode, HeapRegionNode> mapToFirstDimensionArrayNode =
2386 new Hashtable<HeapRegionNode, HeapRegionNode>();
2387 Set<String> doneSet = new HashSet<String>();
2389 TempDescriptor tempDesc = fm.getParameter(idx);
2391 AllocSite as = createParameterAllocSite(rg, tempDesc, true);
2392 VariableNode lnX = rg.getVariableNodeFromTemp(tempDesc);
2393 Integer idNewest = as.getIthOldest(0);
2394 HeapRegionNode hrnNewest = rg.id2hrn.get(idNewest);
2396 // make a new reference to allocated node
2397 RefEdge edgeNew = new RefEdge(lnX, // source
2399 taskDesc.getParamType(idx), // type
2401 hrnNewest.getAlpha(), // beta
2402 ExistPredSet.factory(rg.predTrue), // predicates
2405 rg.addRefEdge(lnX, hrnNewest, edgeNew);
2407 // set-up a work set for class field
2408 ClassDescriptor classDesc = paramTypeDesc.getClassDesc();
2409 for (Iterator it = classDesc.getFields(); it.hasNext(); ) {
2410 FieldDescriptor fd = (FieldDescriptor) it.next();
2411 TypeDescriptor fieldType = fd.getType();
2412 if (shouldAnalysisTrack(fieldType)) {
2413 HashMap<HeapRegionNode, FieldDescriptor> newMap = new HashMap<HeapRegionNode, FieldDescriptor>();
2414 newMap.put(hrnNewest, fd);
2415 workSet.add(newMap);
2419 int uniqueIdentifier = 0;
2420 while (!workSet.isEmpty()) {
2421 HashMap<HeapRegionNode, FieldDescriptor> map = workSet
2423 workSet.remove(map);
2425 Set<HeapRegionNode> key = map.keySet();
2426 HeapRegionNode srcHRN = key.iterator().next();
2427 FieldDescriptor fd = map.get(srcHRN);
2428 TypeDescriptor type = fd.getType();
2429 String doneSetIdentifier = srcHRN.getIDString() + "_" + fd;
2431 if (!doneSet.contains(doneSetIdentifier)) {
2432 doneSet.add(doneSetIdentifier);
2433 if (!mapTypeToExistingSummaryNode.containsKey(type)) {
2434 // create new summary Node
2435 TempDescriptor td = new TempDescriptor("temp"
2436 + uniqueIdentifier, type);
2438 AllocSite allocSite;
2439 if(type.equals(paramTypeDesc)) {
2440 //corresponding allocsite has already been created for a parameter variable.
2443 allocSite = createParameterAllocSite(rg, td, false);
2445 String strDesc = allocSite.toStringForDOT()
2447 TypeDescriptor allocType=allocSite.getType();
2449 HeapRegionNode hrnSummary;
2450 if(allocType.isArray() && allocType.getArrayCount()>0) {
2451 hrnSummary=createMultiDeimensionalArrayHRN(rg,allocSite,srcHRN,fd,mapToFirstDimensionArrayNode,mapTypeToExistingSummaryNode,hrnNewest.getAlpha());
2454 rg.createNewHeapRegionNode(allocSite.getSummary(), // id or null to generate a new one
2455 false, // single object?
2457 false, // out-of-context?
2458 allocSite.getType(), // type
2459 allocSite, // allocation site
2460 hrnNewest.getAlpha(), // inherent reach
2461 hrnNewest.getAlpha(), // current reach
2462 ExistPredSet.factory(rg.predTrue), // predicates
2463 strDesc // description
2465 rg.id2hrn.put(allocSite.getSummary(),hrnSummary);
2467 // make a new reference to summary node
2468 RefEdge edgeToSummary = new RefEdge(srcHRN, // source
2471 fd.getSymbol(), // field name
2472 hrnNewest.getAlpha(), // beta
2473 ExistPredSet.factory(rg.predTrue), // predicates
2477 rg.addRefEdge(srcHRN, hrnSummary, edgeToSummary);
2481 mapTypeToExistingSummaryNode.put(type, hrnSummary);
2483 // set-up a work set for fields of the class
2484 Set<FieldDescriptor> fieldTobeAnalyzed=getFieldSetTobeAnalyzed(type);
2485 for (Iterator iterator = fieldTobeAnalyzed.iterator(); iterator
2487 FieldDescriptor fieldDescriptor = (FieldDescriptor) iterator
2489 HeapRegionNode newDstHRN;
2490 if(mapToFirstDimensionArrayNode.containsKey(hrnSummary)) {
2491 //related heap region node is already exsited.
2492 newDstHRN=mapToFirstDimensionArrayNode.get(hrnSummary);
2494 newDstHRN=hrnSummary;
2496 doneSetIdentifier = newDstHRN.getIDString() + "_" + fieldDescriptor;
2497 if(!doneSet.contains(doneSetIdentifier)) {
2498 // add new work item
2499 HashMap<HeapRegionNode, FieldDescriptor> newMap =
2500 new HashMap<HeapRegionNode, FieldDescriptor>();
2501 newMap.put(newDstHRN, fieldDescriptor);
2502 workSet.add(newMap);
2507 // if there exists corresponding summary node
2508 HeapRegionNode hrnDst=mapTypeToExistingSummaryNode.get(type);
2510 RefEdge edgeToSummary = new RefEdge(srcHRN, // source
2512 fd.getType(), // type
2513 fd.getSymbol(), // field name
2514 srcHRN.getAlpha(), // beta
2515 ExistPredSet.factory(rg.predTrue), // predicates
2518 rg.addRefEdge(srcHRN, hrnDst, edgeToSummary);
2528 // return all allocation sites in the method (there is one allocation
2529 // site per FlatNew node in a method)
2530 private HashSet<AllocSite> getAllocationSiteSet(Descriptor d) {
2531 if( !mapDescriptorToAllocSiteSet.containsKey(d) ) {
2532 buildAllocationSiteSet(d);
2535 return mapDescriptorToAllocSiteSet.get(d);
2539 private void buildAllocationSiteSet(Descriptor d) {
2540 HashSet<AllocSite> s = new HashSet<AllocSite>();
2543 if( d instanceof MethodDescriptor ) {
2544 fm = state.getMethodFlat( (MethodDescriptor) d);
2546 assert d instanceof TaskDescriptor;
2547 fm = state.getMethodFlat( (TaskDescriptor) d);
2549 pm.analyzeMethod(fm);
2551 // visit every node in this FlatMethod's IR graph
2552 // and make a set of the allocation sites from the
2553 // FlatNew node's visited
2554 HashSet<FlatNode> visited = new HashSet<FlatNode>();
2555 HashSet<FlatNode> toVisit = new HashSet<FlatNode>();
2558 while( !toVisit.isEmpty() ) {
2559 FlatNode n = toVisit.iterator().next();
2561 if( n instanceof FlatNew ) {
2562 s.add(getAllocSiteFromFlatNewPRIVATE( (FlatNew) n) );
2568 for( int i = 0; i < pm.numNext(n); ++i ) {
2569 FlatNode child = pm.getNext(n, i);
2570 if( !visited.contains(child) ) {
2576 mapDescriptorToAllocSiteSet.put(d, s);
2579 private HashSet<AllocSite> getFlaggedAllocationSites(Descriptor dIn) {
2581 HashSet<AllocSite> out = new HashSet<AllocSite>();
2582 HashSet<Descriptor> toVisit = new HashSet<Descriptor>();
2583 HashSet<Descriptor> visited = new HashSet<Descriptor>();
2587 while (!toVisit.isEmpty()) {
2588 Descriptor d = toVisit.iterator().next();
2592 HashSet<AllocSite> asSet = getAllocationSiteSet(d);
2593 Iterator asItr = asSet.iterator();
2594 while (asItr.hasNext()) {
2595 AllocSite as = (AllocSite) asItr.next();
2596 if (as.getDisjointAnalysisId() != null) {
2601 // enqueue callees of this method to be searched for
2602 // allocation sites also
2603 Set callees = callGraph.getCalleeSet(d);
2604 if (callees != null) {
2605 Iterator methItr = callees.iterator();
2606 while (methItr.hasNext()) {
2607 MethodDescriptor md = (MethodDescriptor) methItr.next();
2609 if (!visited.contains(md)) {
2620 private HashSet<AllocSite>
2621 getFlaggedAllocationSitesReachableFromTaskPRIVATE(TaskDescriptor td) {
2623 HashSet<AllocSite> asSetTotal = new HashSet<AllocSite>();
2624 HashSet<Descriptor> toVisit = new HashSet<Descriptor>();
2625 HashSet<Descriptor> visited = new HashSet<Descriptor>();
2629 // traverse this task and all methods reachable from this task
2630 while( !toVisit.isEmpty() ) {
2631 Descriptor d = toVisit.iterator().next();
2635 HashSet<AllocSite> asSet = getAllocationSiteSet(d);
2636 Iterator asItr = asSet.iterator();
2637 while( asItr.hasNext() ) {
2638 AllocSite as = (AllocSite) asItr.next();
2639 TypeDescriptor typed = as.getType();
2640 if( typed != null ) {
2641 ClassDescriptor cd = typed.getClassDesc();
2642 if( cd != null && cd.hasFlags() ) {
2648 // enqueue callees of this method to be searched for
2649 // allocation sites also
2650 Set callees = callGraph.getCalleeSet(d);
2651 if( callees != null ) {
2652 Iterator methItr = callees.iterator();
2653 while( methItr.hasNext() ) {
2654 MethodDescriptor md = (MethodDescriptor) methItr.next();
2656 if( !visited.contains(md) ) {
2666 public Set<Descriptor> getDescriptorsToAnalyze() {
2667 return descriptorsToAnalyze;
2670 public EffectsAnalysis getEffectsAnalysis() {
2671 return effectsAnalysis;
2674 public ReachGraph getReachGraph(Descriptor d) {
2675 return mapDescriptorToCompleteReachGraph.get(d);
2678 public ReachGraph getEnterReachGraph(FlatNode fn) {
2679 return fn2rgAtEnter.get(fn);
2682 // get successive captures of the analysis state, use compiler
2684 boolean takeDebugSnapshots = false;
2685 String descSymbolDebug = null;
2686 boolean stopAfterCapture = false;
2687 int snapVisitCounter = 0;
2688 int snapNodeCounter = 0;
2689 int visitStartCapture = 0;
2690 int numVisitsToCapture = 0;
2693 void debugSnapshot(ReachGraph rg, FlatNode fn, boolean in) {
2694 if( snapVisitCounter > visitStartCapture + numVisitsToCapture ) {
2702 if( snapVisitCounter >= visitStartCapture ) {
2703 System.out.println(" @@@ snapping visit="+snapVisitCounter+
2704 ", node="+snapNodeCounter+
2708 graphName = String.format("snap%03d_%04din",
2712 graphName = String.format("snap%03d_%04dout",
2717 graphName = graphName + fn;
2719 rg.writeGraph(graphName,
2720 true, // write labels (variables)
2721 true, // selectively hide intermediate temp vars
2722 true, // prune unreachable heap regions
2723 false, // hide reachability
2724 false, // hide subset reachability states
2725 true, // hide predicates
2726 true); // hide edge taints
2733 public Set<Alloc> canPointToAt( TempDescriptor x,
2734 FlatNode programPoint ) {
2736 ReachGraph rgAtEnter = fn2rgAtEnter.get( programPoint );
2737 if( rgAtEnter == null ) {
2741 return rgAtEnter.canPointTo( x );
2745 public Set<Alloc> canPointToAfter( TempDescriptor x,
2746 FlatNode programPoint ) {
2748 ReachGraph rgAtExit = fn2rgAtExit.get( programPoint );
2749 if( rgAtExit == null ) {
2753 return rgAtExit.canPointTo( x );
2757 public Hashtable< Alloc, Set<Alloc> > canPointToAt( TempDescriptor x,
2759 FlatNode programPoint ) {
2761 ReachGraph rgAtEnter = fn2rgAtEnter.get( programPoint );
2762 if( rgAtEnter == null ) {
2766 return rgAtEnter.canPointTo( x, f.getSymbol() );
2770 public Hashtable< Alloc, Set<Alloc> > canPointToAtElement( TempDescriptor x,
2771 FlatNode programPoint ) {
2773 ReachGraph rgAtEnter = fn2rgAtEnter.get( programPoint );
2774 if( rgAtEnter == null ) {
2778 assert x.getType() != null;
2779 assert x.getType().isArray();
2781 return rgAtEnter.canPointTo( x, arrayElementFieldName );