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;
8 import Analysis.FlatIRGraph.*;
11 import IR.Tree.Modifiers;
16 public class DisjointAnalysis implements HeapAnalysis {
18 ///////////////////////////////////////////
20 // Public interface to discover possible
21 // sharing in the program under analysis
23 ///////////////////////////////////////////
25 // if an object allocated at the target site may be
26 // reachable from both an object from root1 and an
27 // object allocated at root2, return TRUE
28 public boolean mayBothReachTarget(FlatMethod fm,
33 AllocSite asr1 = getAllocationSiteFromFlatNew(fnRoot1);
34 AllocSite asr2 = getAllocationSiteFromFlatNew(fnRoot2);
35 assert asr1.isFlagged();
36 assert asr2.isFlagged();
38 AllocSite ast = getAllocationSiteFromFlatNew(fnTarget);
39 ReachGraph rg = getPartial(fm.getMethod() );
41 return rg.mayBothReachTarget(asr1, asr2, ast);
44 // similar to the method above, return TRUE if ever
45 // more than one object from the root allocation site
46 // may reach an object from the target site
47 public boolean mayManyReachTarget(FlatMethod fm,
51 AllocSite asr = getAllocationSiteFromFlatNew(fnRoot);
52 assert asr.isFlagged();
54 AllocSite ast = getAllocationSiteFromFlatNew(fnTarget);
55 ReachGraph rg = getPartial(fm.getMethod() );
57 return rg.mayManyReachTarget(asr, ast);
63 public HashSet<AllocSite>
64 getFlaggedAllocationSitesReachableFromTask(TaskDescriptor td) {
65 checkAnalysisComplete();
66 return getFlaggedAllocationSitesReachableFromTaskPRIVATE(td);
69 public AllocSite getAllocationSiteFromFlatNew(FlatNew fn) {
70 checkAnalysisComplete();
71 return getAllocSiteFromFlatNewPRIVATE(fn);
74 public AllocSite getAllocationSiteFromHeapRegionNodeID(Integer id) {
75 checkAnalysisComplete();
76 return mapHrnIdToAllocSite.get(id);
79 public Set<HeapRegionNode> hasPotentialSharing(Descriptor taskOrMethod,
82 checkAnalysisComplete();
83 ReachGraph rg=mapDescriptorToCompleteReachGraph.get(taskOrMethod);
84 FlatMethod fm=state.getMethodFlat(taskOrMethod);
86 return rg.mayReachSharedObjects(fm, paramIndex1, paramIndex2);
89 public Set<HeapRegionNode> hasPotentialSharing(Descriptor taskOrMethod,
90 int paramIndex, AllocSite alloc) {
91 checkAnalysisComplete();
92 ReachGraph rg = mapDescriptorToCompleteReachGraph.get(taskOrMethod);
93 FlatMethod fm=state.getMethodFlat(taskOrMethod);
95 return rg.mayReachSharedObjects(fm, paramIndex, alloc);
98 public Set<HeapRegionNode> hasPotentialSharing(Descriptor taskOrMethod,
99 AllocSite alloc, int paramIndex) {
100 checkAnalysisComplete();
101 ReachGraph rg = mapDescriptorToCompleteReachGraph.get(taskOrMethod);
102 FlatMethod fm=state.getMethodFlat(taskOrMethod);
104 return rg.mayReachSharedObjects(fm, paramIndex, alloc);
107 public Set<HeapRegionNode> hasPotentialSharing(Descriptor taskOrMethod,
108 AllocSite alloc1, AllocSite alloc2) {
109 checkAnalysisComplete();
110 ReachGraph rg = mapDescriptorToCompleteReachGraph.get(taskOrMethod);
112 return rg.mayReachSharedObjects(alloc1, alloc2);
115 public String prettyPrintNodeSet(Set<HeapRegionNode> s) {
116 checkAnalysisComplete();
120 Iterator<HeapRegionNode> i = s.iterator();
121 while (i.hasNext()) {
122 HeapRegionNode n = i.next();
124 AllocSite as = n.getAllocSite();
126 out += " " + n.toString() + ",\n";
128 out += " " + n.toString() + ": " + as.toStringVerbose()
137 // use the methods given above to check every possible sharing class
138 // between task parameters and flagged allocation sites reachable
140 public void writeAllSharing(String outputFile,
143 boolean tabularOutput,
146 throws java.io.IOException {
147 checkAnalysisComplete();
149 BufferedWriter bw = new BufferedWriter(new FileWriter(outputFile));
151 if (!tabularOutput) {
152 bw.write("Conducting ownership analysis with allocation depth = "
153 + allocationDepth + "\n");
154 bw.write(timeReport + "\n");
159 // look through every task for potential sharing
160 Iterator taskItr = state.getTaskSymbolTable().getDescriptorsIterator();
161 while (taskItr.hasNext()) {
162 TaskDescriptor td = (TaskDescriptor) taskItr.next();
164 if (!tabularOutput) {
165 bw.write("\n---------" + td + "--------\n");
168 HashSet<AllocSite> allocSites = getFlaggedAllocationSitesReachableFromTask(td);
170 Set<HeapRegionNode> common;
172 // for each task parameter, check for sharing classes with
173 // other task parameters and every allocation site
174 // reachable from this task
175 boolean foundSomeSharing = false;
177 FlatMethod fm = state.getMethodFlat(td);
178 for (int i = 0; i < fm.numParameters(); ++i) {
180 // skip parameters with types that cannot reference
182 if( !shouldAnalysisTrack(fm.getParameter(i).getType() ) ) {
186 // for the ith parameter check for sharing classes to all
187 // higher numbered parameters
188 for (int j = i + 1; j < fm.numParameters(); ++j) {
190 // skip parameters with types that cannot reference
192 if( !shouldAnalysisTrack(fm.getParameter(j).getType() ) ) {
197 common = hasPotentialSharing(td, i, j);
198 if (!common.isEmpty()) {
199 foundSomeSharing = true;
201 if (!tabularOutput) {
202 bw.write("Potential sharing between parameters " + i
203 + " and " + j + ".\n");
204 bw.write(prettyPrintNodeSet(common) + "\n");
209 // for the ith parameter, check for sharing classes against
210 // the set of allocation sites reachable from this
212 Iterator allocItr = allocSites.iterator();
213 while (allocItr.hasNext()) {
214 AllocSite as = (AllocSite) allocItr.next();
215 common = hasPotentialSharing(td, i, as);
216 if (!common.isEmpty()) {
217 foundSomeSharing = true;
219 if (!tabularOutput) {
220 bw.write("Potential sharing between parameter " + i
221 + " and " + as.getFlatNew() + ".\n");
222 bw.write(prettyPrintNodeSet(common) + "\n");
228 // for each allocation site check for sharing classes with
229 // other allocation sites in the context of execution
231 HashSet<AllocSite> outerChecked = new HashSet<AllocSite>();
232 Iterator allocItr1 = allocSites.iterator();
233 while (allocItr1.hasNext()) {
234 AllocSite as1 = (AllocSite) allocItr1.next();
236 Iterator allocItr2 = allocSites.iterator();
237 while (allocItr2.hasNext()) {
238 AllocSite as2 = (AllocSite) allocItr2.next();
240 if (!outerChecked.contains(as2)) {
241 common = hasPotentialSharing(td, as1, as2);
243 if (!common.isEmpty()) {
244 foundSomeSharing = true;
246 if (!tabularOutput) {
247 bw.write("Potential sharing between "
248 + as1.getFlatNew() + " and "
249 + as2.getFlatNew() + ".\n");
250 bw.write(prettyPrintNodeSet(common) + "\n");
256 outerChecked.add(as1);
259 if (!foundSomeSharing) {
260 if (!tabularOutput) {
261 bw.write("No sharing between flagged objects in Task " + td
269 bw.write(" & " + numSharing + " & " + justTime + " & " + numLines
270 + " & " + numMethodsAnalyzed() + " \\\\\n");
272 bw.write("\nNumber sharing classes: "+numSharing);
280 // this version of writeAllSharing is for Java programs that have no tasks
281 // ***********************************
282 // WARNING: THIS DOES NOT DO THE RIGHT THING, REPORTS 0 ALWAYS!
283 // It should use mayBothReachTarget and mayManyReachTarget like
284 // OoOJava does to query analysis results
285 // ***********************************
286 public void writeAllSharingJava(String outputFile,
289 boolean tabularOutput,
292 throws java.io.IOException {
293 checkAnalysisComplete();
299 BufferedWriter bw = new BufferedWriter(new FileWriter(outputFile));
301 bw.write("Conducting disjoint reachability analysis with allocation depth = "
302 + allocationDepth + "\n");
303 bw.write(timeReport + "\n\n");
305 boolean foundSomeSharing = false;
307 Descriptor d = typeUtil.getMain();
308 HashSet<AllocSite> allocSites = getFlaggedAllocationSites(d);
310 // for each allocation site check for sharing classes with
311 // other allocation sites in the context of execution
313 HashSet<AllocSite> outerChecked = new HashSet<AllocSite>();
314 Iterator allocItr1 = allocSites.iterator();
315 while (allocItr1.hasNext()) {
316 AllocSite as1 = (AllocSite) allocItr1.next();
318 Iterator allocItr2 = allocSites.iterator();
319 while (allocItr2.hasNext()) {
320 AllocSite as2 = (AllocSite) allocItr2.next();
322 if (!outerChecked.contains(as2)) {
323 Set<HeapRegionNode> common = hasPotentialSharing(d,
326 if (!common.isEmpty()) {
327 foundSomeSharing = true;
328 bw.write("Potential sharing between "
329 + as1.getDisjointAnalysisId() + " and "
330 + as2.getDisjointAnalysisId() + ".\n");
331 bw.write(prettyPrintNodeSet(common) + "\n");
337 outerChecked.add(as1);
340 if (!foundSomeSharing) {
341 bw.write("No sharing classes between flagged objects found.\n");
343 bw.write("\nNumber sharing classes: "+numSharing);
346 bw.write("Number of methods analyzed: "+numMethodsAnalyzed()+"\n");
353 public Alloc getCmdLineArgsAlloc() {
354 return getAllocationSiteFromFlatNew( constructedCmdLineArgsNew );
356 public Alloc getCmdLineArgAlloc() {
357 return getAllocationSiteFromFlatNew( constructedCmdLineArgNew );
359 public Alloc getCmdLineArgBytesAlloc() {
360 return getAllocationSiteFromFlatNew( constructedCmdLineArgBytesNew );
362 public Alloc getNewStringLiteralAlloc() {
363 return newStringLiteralAlloc;
365 public Alloc getNewStringLiteralBytesAlloc() {
366 return newStringLiteralBytesAlloc;
369 ///////////////////////////////////////////
371 // end public interface
373 ///////////////////////////////////////////
377 protected void checkAnalysisComplete() {
378 if( !analysisComplete ) {
379 throw new Error("Warning: public interface method called while analysis is running.");
388 // run in faster mode, only when bugs wrung out!
389 public static boolean releaseMode;
391 // use command line option to set this, analysis
392 // should attempt to be deterministic
393 public static boolean determinismDesired;
395 // when we want to enforce determinism in the
396 // analysis we need to sort descriptors rather
397 // than toss them in efficient sets, use this
398 public static DescriptorComparator dComp =
399 new DescriptorComparator();
402 // data from the compiler
404 public CallGraph callGraph;
405 public Liveness liveness;
406 public ArrayReferencees arrayReferencees;
407 public RBlockRelationAnalysis rblockRel;
408 public TypeUtil typeUtil;
409 public int allocationDepth;
411 protected boolean doEffectsAnalysis = false;
412 protected EffectsAnalysis effectsAnalysis;
413 protected BuildStateMachines buildStateMachines;
416 // data structure for public interface
417 private Hashtable< Descriptor, HashSet<AllocSite> >
418 mapDescriptorToAllocSiteSet;
421 // for public interface methods to warn that they
422 // are grabbing results during analysis
423 private boolean analysisComplete;
426 // used to identify HeapRegionNode objects
427 // A unique ID equates an object in one
428 // ownership graph with an object in another
429 // graph that logically represents the same
431 // start at 10 and increment to reserve some
432 // IDs for special purposes
433 static protected int uniqueIDcount = 10;
436 // An out-of-scope method created by the
437 // analysis that has no parameters, and
438 // appears to allocate the command line
439 // arguments, then invoke the source code's
440 // main method. The purpose of this is to
441 // provide the analysis with an explicit
442 // top-level context with no parameters
443 protected MethodDescriptor mdAnalysisEntry;
444 protected FlatMethod fmAnalysisEntry;
446 // main method defined by source program
447 protected MethodDescriptor mdSourceEntry;
449 // the set of task and/or method descriptors
450 // reachable in call graph
451 protected Set<Descriptor>
452 descriptorsToAnalyze;
454 // current descriptors to visit in fixed-point
455 // interprocedural analysis, prioritized by
456 // dependency in the call graph
457 protected Stack<Descriptor>
458 descriptorsToVisitStack;
459 protected PriorityQueue<DescriptorQWrapper>
462 // a duplication of the above structure, but
463 // for efficient testing of inclusion
464 protected HashSet<Descriptor>
465 descriptorsToVisitSet;
467 // storage for priorities (doesn't make sense)
468 // to add it to the Descriptor class, just in
470 protected Hashtable<Descriptor, Integer>
471 mapDescriptorToPriority;
473 // when analyzing a method and scheduling more:
474 // remember set of callee's enqueued for analysis
475 // so they can be put on top of the callers in
476 // the stack-visit mode
477 protected Set<Descriptor>
480 // maps a descriptor to its current partial result
481 // from the intraprocedural fixed-point analysis--
482 // then the interprocedural analysis settles, this
483 // mapping will have the final results for each
485 protected Hashtable<Descriptor, ReachGraph>
486 mapDescriptorToCompleteReachGraph;
488 // maps a descriptor to its known dependents: namely
489 // methods or tasks that call the descriptor's method
490 // AND are part of this analysis (reachable from main)
491 protected Hashtable< Descriptor, Set<Descriptor> >
492 mapDescriptorToSetDependents;
494 // if the analysis client wants to flag allocation sites
495 // programmatically, it should provide a set of FlatNew
496 // statements--this may be null if unneeded
497 protected Set<FlatNew> sitesToFlag;
499 // maps each flat new to one analysis abstraction
500 // allocate site object, these exist outside reach graphs
501 protected Hashtable<FlatNew, AllocSite>
502 mapFlatNewToAllocSite;
504 // maps intergraph heap region IDs to intergraph
505 // allocation sites that created them, a redundant
506 // structure for efficiency in some operations
507 protected Hashtable<Integer, AllocSite>
510 // maps a method to its initial heap model (IHM) that
511 // is the set of reachability graphs from every caller
512 // site, all merged together. The reason that we keep
513 // them separate is that any one call site's contribution
514 // to the IHM may changed along the path to the fixed point
515 protected Hashtable< Descriptor, Hashtable< FlatCall, ReachGraph > >
516 mapDescriptorToIHMcontributions;
518 // additionally, keep a mapping from descriptors to the
519 // merged in-coming initial context, because we want this
520 // initial context to be STRICTLY MONOTONIC
521 protected Hashtable<Descriptor, ReachGraph>
522 mapDescriptorToInitialContext;
524 // make the result for back edges analysis-wide STRICTLY
525 // MONOTONIC as well, but notice we use FlatNode as the
526 // key for this map: in case we want to consider other
527 // nodes as back edge's in future implementations
528 protected Hashtable<FlatNode, ReachGraph>
529 mapBackEdgeToMonotone;
532 public static final String arrayElementFieldName = "___element_";
533 static protected Hashtable<TypeDescriptor, FieldDescriptor>
537 protected boolean suppressOutput;
539 // for controlling DOT file output
540 protected boolean writeFinalDOTs;
541 protected boolean writeAllIncrementalDOTs;
543 // supporting DOT output--when we want to write every
544 // partial method result, keep a tally for generating
546 protected Hashtable<Descriptor, Integer>
547 mapDescriptorToNumUpdates;
549 //map task descriptor to initial task parameter
550 protected Hashtable<Descriptor, ReachGraph>
551 mapDescriptorToReachGraph;
553 protected PointerMethod pm;
555 //Keeps track of all the reach graphs at every program point
556 //DO NOT USE UNLESS YOU REALLY NEED IT
557 static protected Hashtable<FlatNode, ReachGraph> fn2rgAtEnter =
558 new Hashtable<FlatNode, ReachGraph>();
560 static protected Hashtable<FlatNode, ReachGraph> fn2rgAtExit =
561 new Hashtable<FlatNode, ReachGraph>();
564 private Hashtable<FlatCall, Descriptor> fc2enclosing;
566 Accessible accessible;
569 // we construct an entry method of flat nodes complete
570 // with a new allocation site to model the command line
571 // args creation just for the analysis, so remember that
572 // allocation site. Later in code gen we might want to
573 // know if something is pointing-to to the cmd line args
574 // and we can verify by checking the allocation site field.
575 protected FlatNew constructedCmdLineArgsNew;
576 protected FlatNew constructedCmdLineArgNew;
577 protected FlatNew constructedCmdLineArgBytesNew;
579 // similar to above, the runtime allocates new strings
580 // for literal nodes, so make up an alloc to model that
581 protected AllocSite newStringLiteralAlloc;
582 protected AllocSite newStringLiteralBytesAlloc;
584 // both of the above need the descriptor of the field
585 // for the String's value field to reference by the
586 // byte array from the string object
587 protected TypeDescriptor stringType;
588 protected TypeDescriptor stringBytesType;
589 protected FieldDescriptor stringBytesField;
592 protected void initImplicitStringsModel() {
594 ClassDescriptor cdString = typeUtil.getClass( typeUtil.StringClass );
595 assert cdString != null;
599 new TypeDescriptor( cdString );
602 new TypeDescriptor(TypeDescriptor.CHAR).makeArray( state );
605 stringBytesField = null;
606 Iterator sFieldsItr = cdString.getFields();
607 while( sFieldsItr.hasNext() ) {
608 FieldDescriptor fd = (FieldDescriptor) sFieldsItr.next();
609 if( fd.getSymbol().equals( typeUtil.StringClassValueField ) ) {
610 stringBytesField = fd;
614 assert stringBytesField != null;
617 TempDescriptor throwAway1 =
618 new TempDescriptor("stringLiteralTemp_dummy1",
621 FlatNew fnStringLiteral =
622 new FlatNew(stringType,
626 newStringLiteralAlloc
627 = getAllocSiteFromFlatNewPRIVATE( fnStringLiteral );
630 TempDescriptor throwAway2 =
631 new TempDescriptor("stringLiteralTemp_dummy2",
634 FlatNew fnStringLiteralBytes =
635 new FlatNew(stringBytesType,
639 newStringLiteralBytesAlloc
640 = getAllocSiteFromFlatNewPRIVATE( fnStringLiteralBytes );
646 // allocate various structures that are not local
647 // to a single class method--should be done once
648 protected void allocateStructures() {
650 if( determinismDesired ) {
651 // use an ordered set
652 descriptorsToAnalyze = new TreeSet<Descriptor>(dComp);
654 // otherwise use a speedy hashset
655 descriptorsToAnalyze = new HashSet<Descriptor>();
658 mapDescriptorToCompleteReachGraph =
659 new Hashtable<Descriptor, ReachGraph>();
661 mapDescriptorToNumUpdates =
662 new Hashtable<Descriptor, Integer>();
664 mapDescriptorToSetDependents =
665 new Hashtable< Descriptor, Set<Descriptor> >();
667 mapFlatNewToAllocSite =
668 new Hashtable<FlatNew, AllocSite>();
670 mapDescriptorToIHMcontributions =
671 new Hashtable< Descriptor, Hashtable< FlatCall, ReachGraph > >();
673 mapDescriptorToInitialContext =
674 new Hashtable<Descriptor, ReachGraph>();
676 mapBackEdgeToMonotone =
677 new Hashtable<FlatNode, ReachGraph>();
679 mapHrnIdToAllocSite =
680 new Hashtable<Integer, AllocSite>();
682 mapTypeToArrayField =
683 new Hashtable <TypeDescriptor, FieldDescriptor>();
685 if( state.DISJOINTDVISITSTACK ||
686 state.DISJOINTDVISITSTACKEESONTOP
688 descriptorsToVisitStack =
689 new Stack<Descriptor>();
692 if( state.DISJOINTDVISITPQUE ) {
693 descriptorsToVisitQ =
694 new PriorityQueue<DescriptorQWrapper>();
697 descriptorsToVisitSet =
698 new HashSet<Descriptor>();
700 mapDescriptorToPriority =
701 new Hashtable<Descriptor, Integer>();
704 new HashSet<Descriptor>();
706 mapDescriptorToAllocSiteSet =
707 new Hashtable<Descriptor, HashSet<AllocSite> >();
709 mapDescriptorToReachGraph =
710 new Hashtable<Descriptor, ReachGraph>();
712 pm = new PointerMethod();
714 fc2enclosing = new Hashtable<FlatCall, Descriptor>();
719 // this analysis generates a disjoint reachability
720 // graph for every reachable method in the program
721 public DisjointAnalysis(State s,
726 Set<FlatNew> sitesToFlag,
727 RBlockRelationAnalysis rra
729 init(s, tu, cg, l, ar, sitesToFlag, rra, null, false);
732 public DisjointAnalysis(State s,
737 Set<FlatNew> sitesToFlag,
738 RBlockRelationAnalysis rra,
739 boolean suppressOutput
741 init(s, tu, cg, l, ar, sitesToFlag, rra, null, suppressOutput);
744 public DisjointAnalysis(State s,
749 Set<FlatNew> sitesToFlag,
750 RBlockRelationAnalysis rra,
751 BuildStateMachines bsm,
752 boolean suppressOutput
754 init(s, tu, cg, l, ar, sitesToFlag, rra, bsm, suppressOutput);
757 protected void init(State state,
761 ArrayReferencees arrayReferencees,
762 Set<FlatNew> sitesToFlag,
763 RBlockRelationAnalysis rra,
764 BuildStateMachines bsm,
765 boolean suppressOutput
768 analysisComplete = false;
771 this.typeUtil = typeUtil;
772 this.callGraph = callGraph;
773 this.liveness = liveness;
774 this.arrayReferencees = arrayReferencees;
775 this.sitesToFlag = sitesToFlag;
776 this.rblockRel = rra;
777 this.suppressOutput = suppressOutput;
778 this.buildStateMachines = bsm;
780 if( rblockRel != null ) {
781 doEffectsAnalysis = true;
782 effectsAnalysis = new EffectsAnalysis();
784 EffectsAnalysis.state = state;
785 EffectsAnalysis.buildStateMachines = buildStateMachines;
787 //note: instead of reachgraph's isAccessible, using the result of accessible analysis
788 //since accessible gives us more accurate results
789 accessible=new Accessible(state, callGraph, rra, liveness);
790 accessible.doAnalysis();
793 this.allocationDepth = state.DISJOINTALLOCDEPTH;
794 this.releaseMode = state.DISJOINTRELEASEMODE;
795 this.determinismDesired = state.DISJOINTDETERMINISM;
797 this.writeFinalDOTs = state.DISJOINTWRITEDOTS && !state.DISJOINTWRITEALL;
798 this.writeAllIncrementalDOTs = state.DISJOINTWRITEDOTS && state.DISJOINTWRITEALL;
800 this.takeDebugSnapshots = state.DISJOINTSNAPSYMBOL != null;
801 this.descSymbolDebug = state.DISJOINTSNAPSYMBOL;
802 this.visitStartCapture = state.DISJOINTSNAPVISITTOSTART;
803 this.numVisitsToCapture = state.DISJOINTSNAPNUMVISITS;
804 this.stopAfterCapture = state.DISJOINTSNAPSTOPAFTER;
805 this.snapVisitCounter = 1; // count visits from 1 (user will write 1, means 1st visit)
806 this.snapNodeCounter = 0; // count nodes from 0
809 state.DISJOINTDVISITSTACK ||
810 state.DISJOINTDVISITPQUE ||
811 state.DISJOINTDVISITSTACKEESONTOP;
812 assert !(state.DISJOINTDVISITSTACK && state.DISJOINTDVISITPQUE);
813 assert !(state.DISJOINTDVISITSTACK && state.DISJOINTDVISITSTACKEESONTOP);
814 assert !(state.DISJOINTDVISITPQUE && state.DISJOINTDVISITSTACKEESONTOP);
816 // set some static configuration for ReachGraphs
817 ReachGraph.allocationDepth = allocationDepth;
818 ReachGraph.typeUtil = typeUtil;
819 ReachGraph.state = state;
821 ReachGraph.initOutOfScopeTemps();
823 ReachGraph.debugCallSiteVisitStartCapture
824 = state.DISJOINTDEBUGCALLVISITTOSTART;
826 ReachGraph.debugCallSiteNumVisitsToCapture
827 = state.DISJOINTDEBUGCALLNUMVISITS;
829 ReachGraph.debugCallSiteStopAfter
830 = state.DISJOINTDEBUGCALLSTOPAFTER;
832 ReachGraph.debugCallSiteVisitCounter
833 = 0; // count visits from 1, is incremented before first visit
837 if( suppressOutput ) {
838 System.out.println("* Running disjoint reachability analysis with output suppressed! *");
842 allocateStructures();
844 initImplicitStringsModel();
848 double timeStartAnalysis = (double) System.nanoTime();
850 // start interprocedural fixed-point computation
853 } catch( IOException e ) {
854 throw new Error("IO Exception while writing disjointness analysis output.");
857 analysisComplete=true;
859 double timeEndAnalysis = (double) System.nanoTime();
860 double dt = (timeEndAnalysis - timeStartAnalysis)/(Math.pow(10.0, 9.0) );
863 if( sitesToFlag != null ) {
864 treport = String.format("Disjoint reachability analysis flagged %d sites and took %.3f sec.", sitesToFlag.size(), dt);
865 if(sitesToFlag.size()>0) {
866 treport+="\nFlagged sites:"+"\n"+sitesToFlag.toString();
869 treport = String.format("Disjoint reachability analysis took %.3f sec.", dt);
871 String justtime = String.format("%.2f", dt);
872 System.out.println(treport);
876 if( writeFinalDOTs && !writeAllIncrementalDOTs ) {
880 if( state.DISJOINTWRITEIHMS && !suppressOutput ) {
884 if( state.DISJOINTWRITEINITCONTEXTS && !suppressOutput ) {
885 writeInitialContexts();
888 if( state.DISJOINTALIASFILE != null && !suppressOutput ) {
890 writeAllSharing(state.DISJOINTALIASFILE, treport, justtime, state.DISJOINTALIASTAB, state.lines);
892 writeAllSharingJava(state.DISJOINTALIASFILE,
895 state.DISJOINTALIASTAB,
902 buildStateMachines.writeStateMachines();
905 } catch( IOException e ) {
906 throw new Error("IO Exception while writing disjointness analysis output.");
911 protected boolean moreDescriptorsToVisit() {
912 if( state.DISJOINTDVISITSTACK ||
913 state.DISJOINTDVISITSTACKEESONTOP
915 return !descriptorsToVisitStack.isEmpty();
917 } else if( state.DISJOINTDVISITPQUE ) {
918 return !descriptorsToVisitQ.isEmpty();
921 throw new Error("Neither descriptor visiting mode set");
925 // fixed-point computation over the call graph--when a
926 // method's callees are updated, it must be reanalyzed
927 protected void analyzeMethods() throws java.io.IOException {
929 // task or non-task (java) mode determines what the roots
930 // of the call chain are, and establishes the set of methods
931 // reachable from the roots that will be analyzed
934 if( !suppressOutput ) {
935 System.out.println("Bamboo mode...");
938 Iterator taskItr = state.getTaskSymbolTable().getDescriptorsIterator();
939 while( taskItr.hasNext() ) {
940 TaskDescriptor td = (TaskDescriptor) taskItr.next();
941 if( !descriptorsToAnalyze.contains(td) ) {
942 // add all methods transitively reachable from the
944 descriptorsToAnalyze.add(td);
945 descriptorsToAnalyze.addAll(callGraph.getAllMethods(td) );
950 if( !suppressOutput ) {
951 System.out.println("Java mode...");
954 // add all methods transitively reachable from the
955 // source's main to set for analysis
956 mdSourceEntry = typeUtil.getMain();
957 descriptorsToAnalyze.add(mdSourceEntry);
958 descriptorsToAnalyze.addAll(callGraph.getAllMethods(mdSourceEntry) );
960 // fabricate an empty calling context that will call
961 // the source's main, but call graph doesn't know
962 // about it, so explicitly add it
963 makeAnalysisEntryMethod(mdSourceEntry);
964 descriptorsToAnalyze.add(mdAnalysisEntry);
969 // now, depending on the interprocedural mode for visiting
970 // methods, set up the needed data structures
972 if( state.DISJOINTDVISITPQUE ) {
974 // topologically sort according to the call graph so
975 // leaf calls are last, helps build contexts up first
976 LinkedList<Descriptor> sortedDescriptors =
977 topologicalSort(descriptorsToAnalyze);
979 // add sorted descriptors to priority queue, and duplicate
980 // the queue as a set for efficiently testing whether some
981 // method is marked for analysis
983 Iterator<Descriptor> dItr;
985 // for the priority queue, give items at the head
986 // of the sorted list a low number (highest priority)
987 while( !sortedDescriptors.isEmpty() ) {
988 Descriptor d = sortedDescriptors.removeFirst();
989 mapDescriptorToPriority.put(d, new Integer(p) );
990 descriptorsToVisitQ.add(new DescriptorQWrapper(p, d) );
991 descriptorsToVisitSet.add(d);
995 } else if( state.DISJOINTDVISITSTACK ||
996 state.DISJOINTDVISITSTACKEESONTOP
998 // if we're doing the stack scheme, just throw the root
999 // method or tasks on the stack
1001 Iterator taskItr = state.getTaskSymbolTable().getDescriptorsIterator();
1002 while( taskItr.hasNext() ) {
1003 TaskDescriptor td = (TaskDescriptor) taskItr.next();
1004 descriptorsToVisitStack.add(td);
1005 descriptorsToVisitSet.add(td);
1009 descriptorsToVisitStack.add(mdAnalysisEntry);
1010 descriptorsToVisitSet.add(mdAnalysisEntry);
1014 throw new Error("Unknown method scheduling mode");
1018 // analyze scheduled methods until there are no more to visit
1019 while( moreDescriptorsToVisit() ) {
1020 Descriptor d = null;
1022 if( state.DISJOINTDVISITSTACK ||
1023 state.DISJOINTDVISITSTACKEESONTOP
1025 d = descriptorsToVisitStack.pop();
1027 } else if( state.DISJOINTDVISITPQUE ) {
1028 d = descriptorsToVisitQ.poll().getDescriptor();
1031 assert descriptorsToVisitSet.contains(d);
1032 descriptorsToVisitSet.remove(d);
1034 // because the task or method descriptor just extracted
1035 // was in the "to visit" set it either hasn't been analyzed
1036 // yet, or some method that it depends on has been
1037 // updated. Recompute a complete reachability graph for
1038 // this task/method and compare it to any previous result.
1039 // If there is a change detected, add any methods/tasks
1040 // that depend on this one to the "to visit" set.
1042 if( !suppressOutput ) {
1043 System.out.println("Analyzing " + d);
1046 if( state.DISJOINTDVISITSTACKEESONTOP ) {
1047 assert calleesToEnqueue.isEmpty();
1050 ReachGraph rg = analyzeMethod(d);
1051 ReachGraph rgPrev = getPartial(d);
1053 if( !rg.equals(rgPrev) ) {
1056 if( state.DISJOINTDEBUGSCHEDULING ) {
1057 System.out.println(" complete graph changed, scheduling callers for analysis:");
1060 // results for d changed, so enqueue dependents
1061 // of d for further analysis
1062 Iterator<Descriptor> depsItr = getDependents(d).iterator();
1063 while( depsItr.hasNext() ) {
1064 Descriptor dNext = depsItr.next();
1067 if( state.DISJOINTDEBUGSCHEDULING ) {
1068 System.out.println(" "+dNext);
1073 // whether or not the method under analysis changed,
1074 // we may have some callees that are scheduled for
1075 // more analysis, and they should go on the top of
1076 // the stack now (in other method-visiting modes they
1077 // are already enqueued at this point
1078 if( state.DISJOINTDVISITSTACKEESONTOP ) {
1079 Iterator<Descriptor> depsItr = calleesToEnqueue.iterator();
1080 while( depsItr.hasNext() ) {
1081 Descriptor dNext = depsItr.next();
1084 calleesToEnqueue.clear();
1090 protected ReachGraph analyzeMethod(Descriptor d)
1091 throws java.io.IOException {
1093 // get the flat code for this descriptor
1095 if( d == mdAnalysisEntry ) {
1096 fm = fmAnalysisEntry;
1098 fm = state.getMethodFlat(d);
1100 pm.analyzeMethod(fm);
1102 // intraprocedural work set
1103 Set<FlatNode> flatNodesToVisit = new HashSet<FlatNode>();
1104 flatNodesToVisit.add(fm);
1106 // if determinism is desired by client, shadow the
1107 // set with a queue to make visit order deterministic
1108 Queue<FlatNode> flatNodesToVisitQ = null;
1109 if( determinismDesired ) {
1110 flatNodesToVisitQ = new LinkedList<FlatNode>();
1111 flatNodesToVisitQ.add(fm);
1114 // mapping of current partial results
1115 Hashtable<FlatNode, ReachGraph> mapFlatNodeToReachGraph =
1116 new Hashtable<FlatNode, ReachGraph>();
1118 // the set of return nodes partial results that will be combined as
1119 // the final, conservative approximation of the entire method
1120 HashSet<FlatReturnNode> setReturns = new HashSet<FlatReturnNode>();
1124 boolean snapThisMethod = false;
1125 if( takeDebugSnapshots && d instanceof MethodDescriptor ) {
1126 MethodDescriptor mdThisMethod = (MethodDescriptor)d;
1127 ClassDescriptor cdThisMethod = mdThisMethod.getClassDesc();
1128 if( cdThisMethod != null ) {
1130 descSymbolDebug.equals( cdThisMethod.getSymbol()+
1132 mdThisMethod.getSymbol()
1139 while( !flatNodesToVisit.isEmpty() ) {
1142 if( determinismDesired ) {
1143 assert !flatNodesToVisitQ.isEmpty();
1144 fn = flatNodesToVisitQ.remove();
1146 fn = flatNodesToVisit.iterator().next();
1148 flatNodesToVisit.remove(fn);
1150 // effect transfer function defined by this node,
1151 // then compare it to the old graph at this node
1152 // to see if anything was updated.
1154 ReachGraph rg = new ReachGraph();
1155 TaskDescriptor taskDesc;
1156 if(fn instanceof FlatMethod && (taskDesc=((FlatMethod)fn).getTask())!=null) {
1157 if(mapDescriptorToReachGraph.containsKey(taskDesc)) {
1158 // retrieve existing reach graph if it is not first time
1159 rg=mapDescriptorToReachGraph.get(taskDesc);
1161 // create initial reach graph for a task
1162 rg=createInitialTaskReachGraph((FlatMethod)fn);
1164 mapDescriptorToReachGraph.put(taskDesc, rg);
1168 // start by merging all node's parents' graphs
1169 for( int i = 0; i < pm.numPrev(fn); ++i ) {
1170 FlatNode pn = pm.getPrev(fn,i);
1171 if( mapFlatNodeToReachGraph.containsKey(pn) ) {
1172 ReachGraph rgParent = mapFlatNodeToReachGraph.get(pn);
1178 if( snapThisMethod ) {
1179 debugSnapshot(rg, fn, true);
1183 // modify rg with appropriate transfer function
1184 rg = analyzeFlatNode(d, fm, fn, setReturns, rg);
1187 if( snapThisMethod ) {
1188 debugSnapshot(rg, fn, false);
1193 // if the results of the new graph are different from
1194 // the current graph at this node, replace the graph
1195 // with the update and enqueue the children
1196 ReachGraph rgPrev = mapFlatNodeToReachGraph.get(fn);
1197 if( !rg.equals(rgPrev) ) {
1198 mapFlatNodeToReachGraph.put(fn, rg);
1200 for( int i = 0; i < pm.numNext(fn); i++ ) {
1201 FlatNode nn = pm.getNext(fn, i);
1203 flatNodesToVisit.add(nn);
1204 if( determinismDesired ) {
1205 flatNodesToVisitQ.add(nn);
1212 // end by merging all return nodes into a complete
1213 // reach graph that represents all possible heap
1214 // states after the flat method returns
1215 ReachGraph completeGraph = new ReachGraph();
1217 assert !setReturns.isEmpty();
1218 Iterator retItr = setReturns.iterator();
1219 while( retItr.hasNext() ) {
1220 FlatReturnNode frn = (FlatReturnNode) retItr.next();
1222 assert mapFlatNodeToReachGraph.containsKey(frn);
1223 ReachGraph rgRet = mapFlatNodeToReachGraph.get(frn);
1225 completeGraph.merge(rgRet);
1229 if( snapThisMethod ) {
1230 // increment that we've visited the debug snap
1231 // method, and reset the node counter
1232 System.out.println(" @@@ debug snap at visit "+snapVisitCounter);
1234 snapNodeCounter = 0;
1236 if( snapVisitCounter == visitStartCapture + numVisitsToCapture &&
1239 System.out.println("!!! Stopping analysis after debug snap captures. !!!");
1245 return completeGraph;
1249 protected ReachGraph
1250 analyzeFlatNode(Descriptor d,
1251 FlatMethod fmContaining,
1253 HashSet<FlatReturnNode> setRetNodes,
1255 ) throws java.io.IOException {
1258 // any variables that are no longer live should be
1259 // nullified in the graph to reduce edges
1260 //rg.nullifyDeadVars( liveness.getLiveInTemps( fmContaining, fn ) );
1264 FieldDescriptor fld;
1265 TypeDescriptor tdElement;
1266 FieldDescriptor fdElement;
1267 FlatSESEEnterNode sese;
1268 FlatSESEExitNode fsexn;
1270 //Stores the flatnode's reach graph at enter
1271 ReachGraph rgOnEnter = new ReachGraph();
1272 rgOnEnter.merge(rg);
1273 fn2rgAtEnter.put(fn, rgOnEnter);
1277 // use node type to decide what transfer function
1278 // to apply to the reachability graph
1279 switch( fn.kind() ) {
1281 case FKind.FlatGenReachNode: {
1282 FlatGenReachNode fgrn = (FlatGenReachNode) fn;
1284 System.out.println(" Generating reach graph for program point: "+fgrn.getGraphName() );
1287 rg.writeGraph("genReach"+fgrn.getGraphName(),
1288 true, // write labels (variables)
1289 false, //true, // selectively hide intermediate temp vars
1290 false, //true, // prune unreachable heap regions
1291 true, // hide reachability altogether
1292 true, // hide subset reachability states
1293 true, // hide predicates
1294 true); //false); // hide edge taints
1298 case FKind.FlatMethod: {
1299 // construct this method's initial heap model (IHM)
1300 // since we're working on the FlatMethod, we know
1301 // the incoming ReachGraph 'rg' is empty
1303 Hashtable<FlatCall, ReachGraph> heapsFromCallers =
1304 getIHMcontributions(d);
1306 Set entrySet = heapsFromCallers.entrySet();
1307 Iterator itr = entrySet.iterator();
1308 while( itr.hasNext() ) {
1309 Map.Entry me = (Map.Entry)itr.next();
1310 FlatCall fc = (FlatCall) me.getKey();
1311 ReachGraph rgContrib = (ReachGraph) me.getValue();
1313 assert fc.getMethod().equals(d);
1315 rg.merge(rgContrib);
1318 // additionally, we are enforcing STRICT MONOTONICITY for the
1319 // method's initial context, so grow the context by whatever
1320 // the previously computed context was, and put the most
1321 // up-to-date context back in the map
1322 ReachGraph rgPrevContext = mapDescriptorToInitialContext.get(d);
1323 rg.merge(rgPrevContext);
1324 mapDescriptorToInitialContext.put(d, rg);
1328 case FKind.FlatOpNode:
1329 FlatOpNode fon = (FlatOpNode) fn;
1330 if( fon.getOp().getOp() == Operation.ASSIGN ) {
1331 lhs = fon.getDest();
1332 rhs = fon.getLeft();
1334 // before transfer, do effects analysis support
1335 if( doEffectsAnalysis && fmContaining != fmAnalysisEntry ) {
1336 if(rblockRel.isPotentialStallSite(fn)) {
1337 // x gets status of y
1338 // if(!rg.isAccessible(rhs)){
1339 if(!accessible.isAccessible(fn, rhs)) {
1340 rg.makeInaccessible(lhs);
1346 rg.assignTempXEqualToTempY(lhs, rhs);
1350 case FKind.FlatCastNode:
1351 FlatCastNode fcn = (FlatCastNode) fn;
1355 TypeDescriptor td = fcn.getType();
1358 // before transfer, do effects analysis support
1359 if( doEffectsAnalysis && fmContaining != fmAnalysisEntry ) {
1360 if(rblockRel.isPotentialStallSite(fn)) {
1361 // x gets status of y
1362 // if(!rg.isAccessible(rhs)){
1363 if(!accessible.isAccessible(fn,rhs)) {
1364 rg.makeInaccessible(lhs);
1370 rg.assignTempXEqualToCastedTempY(lhs, rhs, td);
1373 case FKind.FlatFieldNode:
1374 FlatFieldNode ffn = (FlatFieldNode) fn;
1378 fld = ffn.getField();
1380 // before graph transform, possible inject
1381 // a stall-site taint
1382 if( doEffectsAnalysis && fmContaining != fmAnalysisEntry ) {
1384 if(rblockRel.isPotentialStallSite(fn)) {
1385 // x=y.f, stall y if not accessible
1386 // contributes read effects on stall site of y
1387 // if(!rg.isAccessible(rhs)) {
1388 if(!accessible.isAccessible(fn,rhs)) {
1389 rg.taintStallSite(fn, rhs);
1392 // after this, x and y are accessbile.
1393 rg.makeAccessible(lhs);
1394 rg.makeAccessible(rhs);
1398 if( shouldAnalysisTrack(fld.getType() ) ) {
1400 rg.assignTempXEqualToTempYFieldF(lhs, rhs, fld, fn);
1403 // after transfer, use updated graph to
1404 // do effects analysis
1405 if( doEffectsAnalysis && fmContaining != fmAnalysisEntry ) {
1406 effectsAnalysis.analyzeFlatFieldNode(rg, rhs, fld, fn);
1410 case FKind.FlatSetFieldNode:
1411 FlatSetFieldNode fsfn = (FlatSetFieldNode) fn;
1413 lhs = fsfn.getDst();
1414 fld = fsfn.getField();
1415 rhs = fsfn.getSrc();
1417 boolean strongUpdate = false;
1419 // before transfer func, possibly inject
1420 // stall-site taints
1421 if( doEffectsAnalysis && fmContaining != fmAnalysisEntry ) {
1423 if(rblockRel.isPotentialStallSite(fn)) {
1424 // x.y=f , stall x and y if they are not accessible
1425 // also contribute write effects on stall site of x
1426 // if(!rg.isAccessible(lhs)) {
1427 if(!accessible.isAccessible(fn,lhs)) {
1428 rg.taintStallSite(fn, lhs);
1431 // if(!rg.isAccessible(rhs)) {
1432 if(!accessible.isAccessible(fn,rhs)) {
1433 rg.taintStallSite(fn, rhs);
1436 // accessible status update
1437 rg.makeAccessible(lhs);
1438 rg.makeAccessible(rhs);
1442 if( shouldAnalysisTrack(fld.getType() ) ) {
1444 strongUpdate = rg.assignTempXFieldFEqualToTempY(lhs, fld, rhs, fn);
1447 // use transformed graph to do effects analysis
1448 if( doEffectsAnalysis && fmContaining != fmAnalysisEntry ) {
1449 effectsAnalysis.analyzeFlatSetFieldNode(rg, lhs, fld, fn, strongUpdate);
1453 case FKind.FlatElementNode:
1454 FlatElementNode fen = (FlatElementNode) fn;
1459 assert rhs.getType() != null;
1460 assert rhs.getType().isArray();
1462 tdElement = rhs.getType().dereference();
1463 fdElement = getArrayField(tdElement);
1465 // before transfer func, possibly inject
1467 if( doEffectsAnalysis && fmContaining != fmAnalysisEntry ) {
1468 if(rblockRel.isPotentialStallSite(fn)) {
1469 // x=y.f, stall y if not accessible
1470 // contributes read effects on stall site of y
1471 // after this, x and y are accessbile.
1472 // if(!rg.isAccessible(rhs)) {
1473 if(!accessible.isAccessible(fn,rhs)) {
1474 rg.taintStallSite(fn, rhs);
1477 rg.makeAccessible(lhs);
1478 rg.makeAccessible(rhs);
1482 if( shouldAnalysisTrack(lhs.getType() ) ) {
1484 rg.assignTempXEqualToTempYFieldF(lhs, rhs, fdElement, fn);
1487 // use transformed graph to do effects analysis
1488 if( doEffectsAnalysis && fmContaining != fmAnalysisEntry ) {
1489 effectsAnalysis.analyzeFlatFieldNode(rg, rhs, fdElement, fn);
1493 case FKind.FlatSetElementNode:
1494 FlatSetElementNode fsen = (FlatSetElementNode) fn;
1496 lhs = fsen.getDst();
1497 rhs = fsen.getSrc();
1499 assert lhs.getType() != null;
1500 assert lhs.getType().isArray();
1502 tdElement = lhs.getType().dereference();
1503 fdElement = getArrayField(tdElement);
1505 // before transfer func, possibly inject
1506 // stall-site taints
1507 if( doEffectsAnalysis && fmContaining != fmAnalysisEntry ) {
1509 if(rblockRel.isPotentialStallSite(fn)) {
1510 // x.y=f , stall x and y if they are not accessible
1511 // also contribute write effects on stall site of x
1512 // if(!rg.isAccessible(lhs)) {
1513 if(!accessible.isAccessible(fn,lhs)) {
1514 rg.taintStallSite(fn, lhs);
1517 // if(!rg.isAccessible(rhs)) {
1518 if(!accessible.isAccessible(fn,rhs)) {
1519 rg.taintStallSite(fn, rhs);
1522 // accessible status update
1523 rg.makeAccessible(lhs);
1524 rg.makeAccessible(rhs);
1528 if( shouldAnalysisTrack(rhs.getType() ) ) {
1529 // transfer func, BUT
1530 // skip this node if it cannot create new reachability paths
1531 if( !arrayReferencees.doesNotCreateNewReaching(fsen) ) {
1532 rg.assignTempXFieldFEqualToTempY(lhs, fdElement, rhs, fn);
1536 // use transformed graph to do effects analysis
1537 if( doEffectsAnalysis && fmContaining != fmAnalysisEntry ) {
1538 effectsAnalysis.analyzeFlatSetFieldNode(rg, lhs, fdElement, fn,
1544 FlatNew fnn = (FlatNew) fn;
1546 if( shouldAnalysisTrack(lhs.getType() ) ) {
1547 AllocSite as = getAllocSiteFromFlatNewPRIVATE(fnn);
1549 // before transform, support effects analysis
1550 if (doEffectsAnalysis && fmContaining != fmAnalysisEntry) {
1551 if (rblockRel.isPotentialStallSite(fn)) {
1552 // after creating new object, lhs is accessible
1553 rg.makeAccessible(lhs);
1558 rg.assignTempEqualToNewAlloc(lhs, as);
1563 case FKind.FlatLiteralNode:
1564 // BIG NOTE: this transfer function is only here for
1565 // points-to information for String literals. That's it.
1566 // Effects and disjoint reachability and all of that don't
1567 // care about references to literals.
1568 FlatLiteralNode fln = (FlatLiteralNode) fn;
1570 if( fln.getType().equals( stringType ) ) {
1571 rg.assignTempEqualToStringLiteral( fln.getDst(),
1572 newStringLiteralAlloc,
1573 newStringLiteralBytesAlloc,
1579 case FKind.FlatSESEEnterNode:
1580 sese = (FlatSESEEnterNode) fn;
1582 if( doEffectsAnalysis && fmContaining != fmAnalysisEntry ) {
1584 // always remove ALL stall site taints at enter
1585 rg.removeAllStallSiteTaints();
1587 // inject taints for in-set vars
1588 rg.taintInSetVars(sese);
1593 case FKind.FlatSESEExitNode:
1594 fsexn = (FlatSESEExitNode) fn;
1595 sese = fsexn.getFlatEnter();
1597 if( doEffectsAnalysis && fmContaining != fmAnalysisEntry ) {
1599 // @ sese exit make all live variables
1600 // inaccessible to later parent statements
1601 rg.makeInaccessible(liveness.getLiveInTemps(fmContaining, fn) );
1603 // always remove ALL stall site taints at exit
1604 rg.removeAllStallSiteTaints();
1606 // remove in-set var taints for the exiting rblock
1607 rg.removeInContextTaints(sese);
1612 case FKind.FlatCall: {
1613 Descriptor mdCaller;
1614 if( fmContaining.getMethod() != null ) {
1615 mdCaller = fmContaining.getMethod();
1617 mdCaller = fmContaining.getTask();
1619 FlatCall fc = (FlatCall) fn;
1620 MethodDescriptor mdCallee = fc.getMethod();
1621 FlatMethod fmCallee = state.getMethodFlat(mdCallee);
1625 // all this jimma jamma to debug call sites is WELL WORTH the
1626 // effort, so so so many bugs or buggy info appears through call
1628 boolean debugCallSite = false;
1629 if( state.DISJOINTDEBUGCALLEE != null &&
1630 state.DISJOINTDEBUGCALLER != null ) {
1632 boolean debugCalleeMatches = false;
1633 boolean debugCallerMatches = false;
1635 ClassDescriptor cdCallee = mdCallee.getClassDesc();
1636 if( cdCallee != null ) {
1637 debugCalleeMatches =
1638 state.DISJOINTDEBUGCALLEE.equals( cdCallee.getSymbol()+
1640 mdCallee.getSymbol()
1645 if( mdCaller instanceof MethodDescriptor ) {
1646 ClassDescriptor cdCaller = ((MethodDescriptor)mdCaller).getClassDesc();
1647 if( cdCaller != null ) {
1648 debugCallerMatches =
1649 state.DISJOINTDEBUGCALLER.equals( cdCaller.getSymbol()+
1651 mdCaller.getSymbol()
1655 // for bristlecone style tasks
1656 debugCallerMatches =
1657 state.DISJOINTDEBUGCALLER.equals( mdCaller.getSymbol() );
1660 debugCallSite = debugCalleeMatches && debugCallerMatches;
1666 boolean writeDebugDOTs = false;
1667 boolean stopAfter = false;
1668 if( debugCallSite ) {
1669 ++ReachGraph.debugCallSiteVisitCounter;
1670 System.out.println(" $$$ Debug call site visit "+
1671 ReachGraph.debugCallSiteVisitCounter+
1675 (ReachGraph.debugCallSiteVisitCounter >=
1676 ReachGraph.debugCallSiteVisitStartCapture) &&
1678 (ReachGraph.debugCallSiteVisitCounter <
1679 ReachGraph.debugCallSiteVisitStartCapture +
1680 ReachGraph.debugCallSiteNumVisitsToCapture)
1682 writeDebugDOTs = true;
1683 System.out.println(" $$$ Capturing this call site visit $$$");
1684 if( ReachGraph.debugCallSiteStopAfter &&
1685 (ReachGraph.debugCallSiteVisitCounter ==
1686 ReachGraph.debugCallSiteVisitStartCapture +
1687 ReachGraph.debugCallSiteNumVisitsToCapture - 1)
1695 // calculate the heap this call site can reach--note this is
1696 // not used for the current call site transform, we are
1697 // grabbing this heap model for future analysis of the callees,
1698 // so if different results emerge we will return to this site
1699 ReachGraph heapForThisCall_old =
1700 getIHMcontribution(mdCallee, fc);
1702 // the computation of the callee-reachable heap
1703 // is useful for making the callee starting point
1704 // and for applying the call site transfer function
1705 Set<Integer> callerNodeIDsCopiedToCallee =
1706 new HashSet<Integer>();
1708 ReachGraph heapForThisCall_cur =
1709 rg.makeCalleeView(fc,
1711 callerNodeIDsCopiedToCallee,
1715 // enforce that a call site contribution can only
1716 // monotonically increase
1717 heapForThisCall_cur.merge(heapForThisCall_old);
1719 if( !heapForThisCall_cur.equals(heapForThisCall_old) ) {
1720 // if heap at call site changed, update the contribution,
1721 // and reschedule the callee for analysis
1722 addIHMcontribution(mdCallee, fc, heapForThisCall_cur);
1724 // map a FlatCall to its enclosing method/task descriptor
1725 // so we can write that info out later
1726 fc2enclosing.put(fc, mdCaller);
1728 if( state.DISJOINTDEBUGSCHEDULING ) {
1729 System.out.println(" context changed, scheduling callee: "+mdCallee);
1732 if( state.DISJOINTDVISITSTACKEESONTOP ) {
1733 calleesToEnqueue.add(mdCallee);
1740 // the transformation for a call site should update the
1741 // current heap abstraction with any effects from the callee,
1742 // or if the method is virtual, the effects from any possible
1743 // callees, so find the set of callees...
1744 Set<MethodDescriptor> setPossibleCallees;
1745 if( determinismDesired ) {
1746 // use an ordered set
1747 setPossibleCallees = new TreeSet<MethodDescriptor>(dComp);
1749 // otherwise use a speedy hashset
1750 setPossibleCallees = new HashSet<MethodDescriptor>();
1753 if( mdCallee.isStatic() ) {
1754 setPossibleCallees.add(mdCallee);
1756 TypeDescriptor typeDesc = fc.getThis().getType();
1757 setPossibleCallees.addAll(callGraph.getMethods(mdCallee,
1764 ReachGraph rgMergeOfPossibleCallers = new ReachGraph();
1766 Iterator<MethodDescriptor> mdItr = setPossibleCallees.iterator();
1767 while( mdItr.hasNext() ) {
1768 MethodDescriptor mdPossible = mdItr.next();
1769 FlatMethod fmPossible = state.getMethodFlat(mdPossible);
1771 addDependent(mdPossible, // callee
1774 // don't alter the working graph (rg) until we compute a
1775 // result for every possible callee, merge them all together,
1776 // then set rg to that
1777 ReachGraph rgPossibleCaller = new ReachGraph();
1778 rgPossibleCaller.merge(rg);
1780 ReachGraph rgPossibleCallee = getPartial(mdPossible);
1782 if( rgPossibleCallee == null ) {
1783 // if this method has never been analyzed just schedule it
1784 // for analysis and skip over this call site for now
1785 if( state.DISJOINTDVISITSTACKEESONTOP ) {
1786 calleesToEnqueue.add(mdPossible);
1788 enqueue(mdPossible);
1791 if( state.DISJOINTDEBUGSCHEDULING ) {
1792 System.out.println(" callee hasn't been analyzed, scheduling: "+mdPossible);
1796 // calculate the method call transform
1797 rgPossibleCaller.resolveMethodCall(fc,
1800 callerNodeIDsCopiedToCallee,
1804 if( doEffectsAnalysis && fmContaining != fmAnalysisEntry ) {
1805 // if( !rgPossibleCallee.isAccessible( ReachGraph.tdReturn ) ) {
1806 if( !accessible.isAccessible(fn, ReachGraph.tdReturn) ) {
1807 rgPossibleCaller.makeInaccessible(fc.getReturnTemp() );
1813 rgMergeOfPossibleCallers.merge(rgPossibleCaller);
1818 System.out.println("$$$ Exiting after requested captures of call site. $$$");
1823 // now that we've taken care of building heap models for
1824 // callee analysis, finish this transformation
1825 rg = rgMergeOfPossibleCallers;
1828 // jjenista: what is this? It breaks compilation
1829 // of programs with no tasks/SESEs/rblocks...
1830 //XXXXXXXXXXXXXXXXXXXXXXXXX
1831 //need to consider more
1832 if( state.OOOJAVA ) {
1833 FlatNode nextFN=fmCallee.getNext(0);
1834 if( nextFN instanceof FlatSESEEnterNode ) {
1835 FlatSESEEnterNode calleeSESE=(FlatSESEEnterNode)nextFN;
1836 if(!calleeSESE.getIsLeafSESE()) {
1837 rg.makeInaccessible(liveness.getLiveInTemps(fmContaining, fn) );
1845 case FKind.FlatReturnNode:
1846 FlatReturnNode frn = (FlatReturnNode) fn;
1847 rhs = frn.getReturnTemp();
1849 // before transfer, do effects analysis support
1850 if( doEffectsAnalysis && fmContaining != fmAnalysisEntry ) {
1851 // if(!rg.isAccessible(rhs)){
1852 if(!accessible.isAccessible(fn,rhs)) {
1853 rg.makeInaccessible(ReachGraph.tdReturn);
1857 if( rhs != null && shouldAnalysisTrack(rhs.getType() ) ) {
1858 rg.assignReturnEqualToTemp(rhs);
1861 setRetNodes.add(frn);
1867 // dead variables were removed before the above transfer function
1868 // was applied, so eliminate heap regions and edges that are no
1869 // longer part of the abstractly-live heap graph, and sweep up
1870 // and reachability effects that are altered by the reduction
1871 //rg.abstractGarbageCollect();
1875 // back edges are strictly monotonic
1876 if( pm.isBackEdge(fn) ) {
1877 ReachGraph rgPrevResult = mapBackEdgeToMonotone.get(fn);
1878 rg.merge(rgPrevResult);
1879 mapBackEdgeToMonotone.put(fn, rg);
1883 ReachGraph rgOnExit = new ReachGraph();
1885 fn2rgAtExit.put(fn, rgOnExit);
1888 // at this point rg should be the correct update
1889 // by an above transfer function, or untouched if
1890 // the flat node type doesn't affect the heap
1896 // this method should generate integers strictly greater than zero!
1897 // special "shadow" regions are made from a heap region by negating
1899 static public Integer generateUniqueHeapRegionNodeID() {
1901 return new Integer(uniqueIDcount);
1906 static public FieldDescriptor getArrayField(TypeDescriptor tdElement) {
1907 FieldDescriptor fdElement = mapTypeToArrayField.get(tdElement);
1908 if( fdElement == null ) {
1909 fdElement = new FieldDescriptor(new Modifiers(Modifiers.PUBLIC),
1911 arrayElementFieldName,
1914 mapTypeToArrayField.put(tdElement, fdElement);
1921 private void writeFinalGraphs() {
1922 Set entrySet = mapDescriptorToCompleteReachGraph.entrySet();
1923 Iterator itr = entrySet.iterator();
1924 while( itr.hasNext() ) {
1925 Map.Entry me = (Map.Entry)itr.next();
1926 Descriptor d = (Descriptor) me.getKey();
1927 ReachGraph rg = (ReachGraph) me.getValue();
1930 if( d instanceof TaskDescriptor ) {
1931 graphName = "COMPLETEtask"+d;
1933 graphName = "COMPLETE"+d;
1936 rg.writeGraph(graphName,
1937 true, // write labels (variables)
1938 true, // selectively hide intermediate temp vars
1939 true, // prune unreachable heap regions
1940 true, // hide reachability altogether
1941 true, // hide subset reachability states
1942 true, // hide predicates
1943 false); // hide edge taints
1947 private void writeFinalIHMs() {
1948 Iterator d2IHMsItr = mapDescriptorToIHMcontributions.entrySet().iterator();
1949 while( d2IHMsItr.hasNext() ) {
1950 Map.Entry me1 = (Map.Entry)d2IHMsItr.next();
1951 Descriptor d = (Descriptor) me1.getKey();
1952 Hashtable<FlatCall, ReachGraph> IHMs = (Hashtable<FlatCall, ReachGraph>)me1.getValue();
1954 Iterator fc2rgItr = IHMs.entrySet().iterator();
1955 while( fc2rgItr.hasNext() ) {
1956 Map.Entry me2 = (Map.Entry)fc2rgItr.next();
1957 FlatCall fc = (FlatCall) me2.getKey();
1958 ReachGraph rg = (ReachGraph) me2.getValue();
1960 rg.writeGraph("IHMPARTFOR"+d+"FROM"+fc2enclosing.get(fc)+fc,
1961 true, // write labels (variables)
1962 true, // selectively hide intermediate temp vars
1963 true, // hide reachability altogether
1964 true, // prune unreachable heap regions
1965 true, // hide subset reachability states
1966 false, // hide predicates
1967 true); // hide edge taints
1972 private void writeInitialContexts() {
1973 Set entrySet = mapDescriptorToInitialContext.entrySet();
1974 Iterator itr = entrySet.iterator();
1975 while( itr.hasNext() ) {
1976 Map.Entry me = (Map.Entry)itr.next();
1977 Descriptor d = (Descriptor) me.getKey();
1978 ReachGraph rg = (ReachGraph) me.getValue();
1980 rg.writeGraph("INITIAL"+d,
1981 true, // write labels (variables)
1982 true, // selectively hide intermediate temp vars
1983 true, // prune unreachable heap regions
1984 false, // hide all reachability
1985 true, // hide subset reachability states
1986 true, // hide predicates
1987 false); // hide edge taints
1992 protected ReachGraph getPartial(Descriptor d) {
1993 return mapDescriptorToCompleteReachGraph.get(d);
1996 protected void setPartial(Descriptor d, ReachGraph rg) {
1997 mapDescriptorToCompleteReachGraph.put(d, rg);
1999 // when the flag for writing out every partial
2000 // result is set, we should spit out the graph,
2001 // but in order to give it a unique name we need
2002 // to track how many partial results for this
2003 // descriptor we've already written out
2004 if( writeAllIncrementalDOTs ) {
2005 if( !mapDescriptorToNumUpdates.containsKey(d) ) {
2006 mapDescriptorToNumUpdates.put(d, new Integer(0) );
2008 Integer n = mapDescriptorToNumUpdates.get(d);
2011 if( d instanceof TaskDescriptor ) {
2012 graphName = d+"COMPLETEtask"+String.format("%05d", n);
2014 graphName = d+"COMPLETE"+String.format("%05d", n);
2017 rg.writeGraph(graphName,
2018 true, // write labels (variables)
2019 true, // selectively hide intermediate temp vars
2020 true, // prune unreachable heap regions
2021 false, // hide all reachability
2022 true, // hide subset reachability states
2023 false, // hide predicates
2024 false); // hide edge taints
2026 mapDescriptorToNumUpdates.put(d, n + 1);
2032 // return just the allocation site associated with one FlatNew node
2033 protected AllocSite getAllocSiteFromFlatNewPRIVATE(FlatNew fnew) {
2035 boolean flagProgrammatically = false;
2036 if( sitesToFlag != null && sitesToFlag.contains(fnew) ) {
2037 flagProgrammatically = true;
2040 if( !mapFlatNewToAllocSite.containsKey(fnew) ) {
2041 AllocSite as = AllocSite.factory(allocationDepth,
2043 fnew.getDisjointId(),
2044 flagProgrammatically
2047 // the newest nodes are single objects
2048 for( int i = 0; i < allocationDepth; ++i ) {
2049 Integer id = generateUniqueHeapRegionNodeID();
2050 as.setIthOldest(i, id);
2051 mapHrnIdToAllocSite.put(id, as);
2054 // the oldest node is a summary node
2055 as.setSummary(generateUniqueHeapRegionNodeID() );
2057 mapFlatNewToAllocSite.put(fnew, as);
2060 return mapFlatNewToAllocSite.get(fnew);
2064 public static boolean shouldAnalysisTrack(TypeDescriptor type) {
2065 // don't track primitive types, but an array
2066 // of primitives is heap memory
2067 if( type.isImmutable() ) {
2068 return type.isArray();
2071 // everything else is an object
2075 protected int numMethodsAnalyzed() {
2076 return descriptorsToAnalyze.size();
2082 // Take in source entry which is the program's compiled entry and
2083 // create a new analysis entry, a method that takes no parameters
2084 // and appears to allocate the command line arguments and call the
2085 // source entry with them. The purpose of this analysis entry is
2086 // to provide a top-level method context with no parameters left.
2087 protected void makeAnalysisEntryMethod(MethodDescriptor mdSourceEntry) {
2089 Modifiers mods = new Modifiers();
2090 mods.addModifier(Modifiers.PUBLIC);
2091 mods.addModifier(Modifiers.STATIC);
2093 TypeDescriptor returnType = new TypeDescriptor(TypeDescriptor.VOID);
2095 this.mdAnalysisEntry =
2096 new MethodDescriptor(mods,
2098 "analysisEntryMethod"
2101 TypeDescriptor argsType = mdSourceEntry.getParamType(0);
2102 TempDescriptor cmdLineArgs =
2103 new TempDescriptor("analysisEntryTemp_args",
2107 new FlatNew(argsType,
2111 this.constructedCmdLineArgsNew = fnArgs;
2113 TypeDescriptor argType = argsType.dereference();
2114 TempDescriptor anArg =
2115 new TempDescriptor("analysisEntryTemp_arg",
2119 new FlatNew(argType,
2123 this.constructedCmdLineArgNew = fnArg;
2125 TypeDescriptor typeIndex = new TypeDescriptor(TypeDescriptor.INT);
2126 TempDescriptor index =
2127 new TempDescriptor("analysisEntryTemp_index",
2130 FlatLiteralNode fli =
2131 new FlatLiteralNode(typeIndex,
2136 FlatSetElementNode fse =
2137 new FlatSetElementNode(cmdLineArgs,
2142 TypeDescriptor typeSize = new TypeDescriptor(TypeDescriptor.INT);
2143 TempDescriptor sizeBytes =
2144 new TempDescriptor("analysisEntryTemp_size",
2147 FlatLiteralNode fls =
2148 new FlatLiteralNode(typeSize,
2153 TempDescriptor strBytes =
2154 new TempDescriptor("analysisEntryTemp_strBytes",
2158 new FlatNew(stringBytesType,
2163 this.constructedCmdLineArgBytesNew = fnBytes;
2165 FlatSetFieldNode fsf =
2166 new FlatSetFieldNode(anArg,
2171 // throw this in so you can always see what the initial heap context
2172 // looks like if you want to, its cheap
2173 FlatGenReachNode fgen = new FlatGenReachNode( "argContext" );
2175 TempDescriptor[] sourceEntryArgs = new TempDescriptor[1];
2176 sourceEntryArgs[0] = cmdLineArgs;
2178 new FlatCall(mdSourceEntry,
2184 FlatReturnNode frn = new FlatReturnNode(null);
2186 FlatExit fe = new FlatExit();
2188 this.fmAnalysisEntry =
2189 new FlatMethod(mdAnalysisEntry,
2193 List<FlatNode> nodes = new LinkedList<FlatNode>();
2194 nodes.add( fnArgs );
2199 nodes.add( fnBytes );
2206 FlatNode current = this.fmAnalysisEntry;
2207 for( FlatNode next: nodes ) {
2208 current.addNext( next );
2213 // jjenista - this is useful for looking at the FlatIRGraph of the
2214 // analysis entry method constructed above if you have to modify it.
2215 // The usual method of writing FlatIRGraphs out doesn't work because
2216 // this flat method is private to the model of this analysis only.
2218 // FlatIRGraph flatMethodWriter =
2219 // new FlatIRGraph( state, false, false, false );
2220 // flatMethodWriter.writeFlatIRGraph( fmAnalysisEntry, "analysisEntry" );
2221 //} catch( IOException e ) {}
2225 protected LinkedList<Descriptor> topologicalSort(Set<Descriptor> toSort) {
2227 Set<Descriptor> discovered;
2229 if( determinismDesired ) {
2230 // use an ordered set
2231 discovered = new TreeSet<Descriptor>(dComp);
2233 // otherwise use a speedy hashset
2234 discovered = new HashSet<Descriptor>();
2237 LinkedList<Descriptor> sorted = new LinkedList<Descriptor>();
2239 Iterator<Descriptor> itr = toSort.iterator();
2240 while( itr.hasNext() ) {
2241 Descriptor d = itr.next();
2243 if( !discovered.contains(d) ) {
2244 dfsVisit(d, toSort, sorted, discovered);
2251 // While we're doing DFS on call graph, remember
2252 // dependencies for efficient queuing of methods
2253 // during interprocedural analysis:
2255 // a dependent of a method decriptor d for this analysis is:
2256 // 1) a method or task that invokes d
2257 // 2) in the descriptorsToAnalyze set
2258 protected void dfsVisit(Descriptor d,
2259 Set <Descriptor> toSort,
2260 LinkedList<Descriptor> sorted,
2261 Set <Descriptor> discovered) {
2264 // only methods have callers, tasks never do
2265 if( d instanceof MethodDescriptor ) {
2267 MethodDescriptor md = (MethodDescriptor) d;
2269 // the call graph is not aware that we have a fabricated
2270 // analysis entry that calls the program source's entry
2271 if( md == mdSourceEntry ) {
2272 if( !discovered.contains(mdAnalysisEntry) ) {
2273 addDependent(mdSourceEntry, // callee
2274 mdAnalysisEntry // caller
2276 dfsVisit(mdAnalysisEntry, toSort, sorted, discovered);
2280 // otherwise call graph guides DFS
2281 Iterator itr = callGraph.getCallerSet(md).iterator();
2282 while( itr.hasNext() ) {
2283 Descriptor dCaller = (Descriptor) itr.next();
2285 // only consider callers in the original set to analyze
2286 if( !toSort.contains(dCaller) ) {
2290 if( !discovered.contains(dCaller) ) {
2291 addDependent(md, // callee
2295 dfsVisit(dCaller, toSort, sorted, discovered);
2300 // for leaf-nodes last now!
2305 protected void enqueue(Descriptor d) {
2307 if( !descriptorsToVisitSet.contains(d) ) {
2309 if( state.DISJOINTDVISITSTACK ||
2310 state.DISJOINTDVISITSTACKEESONTOP
2312 descriptorsToVisitStack.add(d);
2314 } else if( state.DISJOINTDVISITPQUE ) {
2315 Integer priority = mapDescriptorToPriority.get(d);
2316 descriptorsToVisitQ.add(new DescriptorQWrapper(priority,
2321 descriptorsToVisitSet.add(d);
2326 // a dependent of a method decriptor d for this analysis is:
2327 // 1) a method or task that invokes d
2328 // 2) in the descriptorsToAnalyze set
2329 protected void addDependent(Descriptor callee, Descriptor caller) {
2330 Set<Descriptor> deps = mapDescriptorToSetDependents.get(callee);
2331 if( deps == null ) {
2332 deps = new HashSet<Descriptor>();
2335 mapDescriptorToSetDependents.put(callee, deps);
2338 protected Set<Descriptor> getDependents(Descriptor callee) {
2339 Set<Descriptor> deps = mapDescriptorToSetDependents.get(callee);
2340 if( deps == null ) {
2341 deps = new HashSet<Descriptor>();
2342 mapDescriptorToSetDependents.put(callee, deps);
2348 public Hashtable<FlatCall, ReachGraph> getIHMcontributions(Descriptor d) {
2350 Hashtable<FlatCall, ReachGraph> heapsFromCallers =
2351 mapDescriptorToIHMcontributions.get(d);
2353 if( heapsFromCallers == null ) {
2354 heapsFromCallers = new Hashtable<FlatCall, ReachGraph>();
2355 mapDescriptorToIHMcontributions.put(d, heapsFromCallers);
2358 return heapsFromCallers;
2361 public ReachGraph getIHMcontribution(Descriptor d,
2364 Hashtable<FlatCall, ReachGraph> heapsFromCallers =
2365 getIHMcontributions(d);
2367 if( !heapsFromCallers.containsKey(fc) ) {
2371 return heapsFromCallers.get(fc);
2375 public void addIHMcontribution(Descriptor d,
2379 Hashtable<FlatCall, ReachGraph> heapsFromCallers =
2380 getIHMcontributions(d);
2382 heapsFromCallers.put(fc, rg);
2386 private AllocSite createParameterAllocSite(ReachGraph rg,
2387 TempDescriptor tempDesc,
2393 flatNew = new FlatNew(tempDesc.getType(), // type
2394 tempDesc, // param temp
2395 false, // global alloc?
2396 "param"+tempDesc // disjoint site ID string
2399 flatNew = new FlatNew(tempDesc.getType(), // type
2400 tempDesc, // param temp
2401 false, // global alloc?
2402 null // disjoint site ID string
2406 // create allocation site
2407 AllocSite as = AllocSite.factory(allocationDepth,
2409 flatNew.getDisjointId(),
2412 for (int i = 0; i < allocationDepth; ++i) {
2413 Integer id = generateUniqueHeapRegionNodeID();
2414 as.setIthOldest(i, id);
2415 mapHrnIdToAllocSite.put(id, as);
2417 // the oldest node is a summary node
2418 as.setSummary(generateUniqueHeapRegionNodeID() );
2426 private Set<FieldDescriptor> getFieldSetTobeAnalyzed(TypeDescriptor typeDesc) {
2428 Set<FieldDescriptor> fieldSet=new HashSet<FieldDescriptor>();
2429 if(!typeDesc.isImmutable()) {
2430 ClassDescriptor classDesc = typeDesc.getClassDesc();
2431 for (Iterator it = classDesc.getFields(); it.hasNext(); ) {
2432 FieldDescriptor field = (FieldDescriptor) it.next();
2433 TypeDescriptor fieldType = field.getType();
2434 if (shouldAnalysisTrack(fieldType)) {
2435 fieldSet.add(field);
2443 private HeapRegionNode createMultiDeimensionalArrayHRN(ReachGraph rg, AllocSite alloc, HeapRegionNode srcHRN, FieldDescriptor fd, Hashtable<HeapRegionNode, HeapRegionNode> map, Hashtable<TypeDescriptor, HeapRegionNode> mapToExistingNode, ReachSet alpha) {
2445 int dimCount=fd.getType().getArrayCount();
2446 HeapRegionNode prevNode=null;
2447 HeapRegionNode arrayEntryNode=null;
2448 for(int i=dimCount; i>0; i--) {
2449 TypeDescriptor typeDesc=fd.getType().dereference(); //hack to get instance of type desc
2450 typeDesc.setArrayCount(i);
2451 TempDescriptor tempDesc=new TempDescriptor(typeDesc.getSymbol(),typeDesc);
2452 HeapRegionNode hrnSummary;
2453 if(!mapToExistingNode.containsKey(typeDesc)) {
2458 as = createParameterAllocSite(rg, tempDesc, false);
2460 // make a new reference to allocated node
2462 rg.createNewHeapRegionNode(as.getSummary(), // id or null to generate a new one
2463 false, // single object?
2465 false, // out-of-context?
2466 as.getType(), // type
2467 as, // allocation site
2468 alpha, // inherent reach
2469 alpha, // current reach
2470 ExistPredSet.factory(rg.predTrue), // predicates
2471 tempDesc.toString() // description
2473 rg.id2hrn.put(as.getSummary(),hrnSummary);
2475 mapToExistingNode.put(typeDesc, hrnSummary);
2477 hrnSummary=mapToExistingNode.get(typeDesc);
2480 if(prevNode==null) {
2481 // make a new reference between new summary node and source
2482 RefEdge edgeToSummary = new RefEdge(srcHRN, // source
2485 fd.getSymbol(), // field name
2487 ExistPredSet.factory(rg.predTrue), // predicates
2491 rg.addRefEdge(srcHRN, hrnSummary, edgeToSummary);
2492 prevNode=hrnSummary;
2493 arrayEntryNode=hrnSummary;
2495 // make a new reference between summary nodes of array
2496 RefEdge edgeToSummary = new RefEdge(prevNode, // source
2499 arrayElementFieldName, // field name
2501 ExistPredSet.factory(rg.predTrue), // predicates
2505 rg.addRefEdge(prevNode, hrnSummary, edgeToSummary);
2506 prevNode=hrnSummary;
2511 // create a new obj node if obj has at least one non-primitive field
2512 TypeDescriptor type=fd.getType();
2513 if(getFieldSetTobeAnalyzed(type).size()>0) {
2514 TypeDescriptor typeDesc=type.dereference();
2515 typeDesc.setArrayCount(0);
2516 if(!mapToExistingNode.containsKey(typeDesc)) {
2517 TempDescriptor tempDesc=new TempDescriptor(type.getSymbol(),typeDesc);
2518 AllocSite as = createParameterAllocSite(rg, tempDesc, false);
2519 // make a new reference to allocated node
2520 HeapRegionNode hrnSummary =
2521 rg.createNewHeapRegionNode(as.getSummary(), // id or null to generate a new one
2522 false, // single object?
2524 false, // out-of-context?
2526 as, // allocation site
2527 alpha, // inherent reach
2528 alpha, // current reach
2529 ExistPredSet.factory(rg.predTrue), // predicates
2530 tempDesc.toString() // description
2532 rg.id2hrn.put(as.getSummary(),hrnSummary);
2533 mapToExistingNode.put(typeDesc, hrnSummary);
2534 RefEdge edgeToSummary = new RefEdge(prevNode, // source
2537 arrayElementFieldName, // field name
2539 ExistPredSet.factory(rg.predTrue), // predicates
2542 rg.addRefEdge(prevNode, hrnSummary, edgeToSummary);
2543 prevNode=hrnSummary;
2545 HeapRegionNode hrnSummary=mapToExistingNode.get(typeDesc);
2546 if(prevNode.getReferenceTo(hrnSummary, typeDesc, arrayElementFieldName)==null) {
2547 RefEdge edgeToSummary = new RefEdge(prevNode, // source
2550 arrayElementFieldName, // field name
2552 ExistPredSet.factory(rg.predTrue), // predicates
2555 rg.addRefEdge(prevNode, hrnSummary, edgeToSummary);
2557 prevNode=hrnSummary;
2561 map.put(arrayEntryNode, prevNode);
2562 return arrayEntryNode;
2565 private ReachGraph createInitialTaskReachGraph(FlatMethod fm) {
2566 ReachGraph rg = new ReachGraph();
2567 TaskDescriptor taskDesc = fm.getTask();
2569 for (int idx = 0; idx < taskDesc.numParameters(); idx++) {
2570 Descriptor paramDesc = taskDesc.getParameter(idx);
2571 TypeDescriptor paramTypeDesc = taskDesc.getParamType(idx);
2573 // setup data structure
2574 Set<HashMap<HeapRegionNode, FieldDescriptor>> workSet =
2575 new HashSet<HashMap<HeapRegionNode, FieldDescriptor>>();
2576 Hashtable<TypeDescriptor, HeapRegionNode> mapTypeToExistingSummaryNode =
2577 new Hashtable<TypeDescriptor, HeapRegionNode>();
2578 Hashtable<HeapRegionNode, HeapRegionNode> mapToFirstDimensionArrayNode =
2579 new Hashtable<HeapRegionNode, HeapRegionNode>();
2580 Set<String> doneSet = new HashSet<String>();
2582 TempDescriptor tempDesc = fm.getParameter(idx);
2584 AllocSite as = createParameterAllocSite(rg, tempDesc, true);
2585 VariableNode lnX = rg.getVariableNodeFromTemp(tempDesc);
2586 Integer idNewest = as.getIthOldest(0);
2587 HeapRegionNode hrnNewest = rg.id2hrn.get(idNewest);
2589 // make a new reference to allocated node
2590 RefEdge edgeNew = new RefEdge(lnX, // source
2592 taskDesc.getParamType(idx), // type
2594 hrnNewest.getAlpha(), // beta
2595 ExistPredSet.factory(rg.predTrue), // predicates
2598 rg.addRefEdge(lnX, hrnNewest, edgeNew);
2600 // set-up a work set for class field
2601 ClassDescriptor classDesc = paramTypeDesc.getClassDesc();
2602 for (Iterator it = classDesc.getFields(); it.hasNext(); ) {
2603 FieldDescriptor fd = (FieldDescriptor) it.next();
2604 TypeDescriptor fieldType = fd.getType();
2605 if (shouldAnalysisTrack(fieldType)) {
2606 HashMap<HeapRegionNode, FieldDescriptor> newMap = new HashMap<HeapRegionNode, FieldDescriptor>();
2607 newMap.put(hrnNewest, fd);
2608 workSet.add(newMap);
2612 int uniqueIdentifier = 0;
2613 while (!workSet.isEmpty()) {
2614 HashMap<HeapRegionNode, FieldDescriptor> map = workSet
2616 workSet.remove(map);
2618 Set<HeapRegionNode> key = map.keySet();
2619 HeapRegionNode srcHRN = key.iterator().next();
2620 FieldDescriptor fd = map.get(srcHRN);
2621 TypeDescriptor type = fd.getType();
2622 String doneSetIdentifier = srcHRN.getIDString() + "_" + fd;
2624 if (!doneSet.contains(doneSetIdentifier)) {
2625 doneSet.add(doneSetIdentifier);
2626 if (!mapTypeToExistingSummaryNode.containsKey(type)) {
2627 // create new summary Node
2628 TempDescriptor td = new TempDescriptor("temp"
2629 + uniqueIdentifier, type);
2631 AllocSite allocSite;
2632 if(type.equals(paramTypeDesc)) {
2633 //corresponding allocsite has already been created for a parameter variable.
2636 allocSite = createParameterAllocSite(rg, td, false);
2638 String strDesc = allocSite.toStringForDOT()
2640 TypeDescriptor allocType=allocSite.getType();
2642 HeapRegionNode hrnSummary;
2643 if(allocType.isArray() && allocType.getArrayCount()>0) {
2644 hrnSummary=createMultiDeimensionalArrayHRN(rg,allocSite,srcHRN,fd,mapToFirstDimensionArrayNode,mapTypeToExistingSummaryNode,hrnNewest.getAlpha());
2647 rg.createNewHeapRegionNode(allocSite.getSummary(), // id or null to generate a new one
2648 false, // single object?
2650 false, // out-of-context?
2651 allocSite.getType(), // type
2652 allocSite, // allocation site
2653 hrnNewest.getAlpha(), // inherent reach
2654 hrnNewest.getAlpha(), // current reach
2655 ExistPredSet.factory(rg.predTrue), // predicates
2656 strDesc // description
2658 rg.id2hrn.put(allocSite.getSummary(),hrnSummary);
2660 // make a new reference to summary node
2661 RefEdge edgeToSummary = new RefEdge(srcHRN, // source
2664 fd.getSymbol(), // field name
2665 hrnNewest.getAlpha(), // beta
2666 ExistPredSet.factory(rg.predTrue), // predicates
2670 rg.addRefEdge(srcHRN, hrnSummary, edgeToSummary);
2674 mapTypeToExistingSummaryNode.put(type, hrnSummary);
2676 // set-up a work set for fields of the class
2677 Set<FieldDescriptor> fieldTobeAnalyzed=getFieldSetTobeAnalyzed(type);
2678 for (Iterator iterator = fieldTobeAnalyzed.iterator(); iterator
2680 FieldDescriptor fieldDescriptor = (FieldDescriptor) iterator
2682 HeapRegionNode newDstHRN;
2683 if(mapToFirstDimensionArrayNode.containsKey(hrnSummary)) {
2684 //related heap region node is already exsited.
2685 newDstHRN=mapToFirstDimensionArrayNode.get(hrnSummary);
2687 newDstHRN=hrnSummary;
2689 doneSetIdentifier = newDstHRN.getIDString() + "_" + fieldDescriptor;
2690 if(!doneSet.contains(doneSetIdentifier)) {
2691 // add new work item
2692 HashMap<HeapRegionNode, FieldDescriptor> newMap =
2693 new HashMap<HeapRegionNode, FieldDescriptor>();
2694 newMap.put(newDstHRN, fieldDescriptor);
2695 workSet.add(newMap);
2700 // if there exists corresponding summary node
2701 HeapRegionNode hrnDst=mapTypeToExistingSummaryNode.get(type);
2703 RefEdge edgeToSummary = new RefEdge(srcHRN, // source
2705 fd.getType(), // type
2706 fd.getSymbol(), // field name
2707 srcHRN.getAlpha(), // beta
2708 ExistPredSet.factory(rg.predTrue), // predicates
2711 rg.addRefEdge(srcHRN, hrnDst, edgeToSummary);
2721 // return all allocation sites in the method (there is one allocation
2722 // site per FlatNew node in a method)
2723 private HashSet<AllocSite> getAllocationSiteSet(Descriptor d) {
2724 if( !mapDescriptorToAllocSiteSet.containsKey(d) ) {
2725 buildAllocationSiteSet(d);
2728 return mapDescriptorToAllocSiteSet.get(d);
2732 private void buildAllocationSiteSet(Descriptor d) {
2733 HashSet<AllocSite> s = new HashSet<AllocSite>();
2736 if( d instanceof MethodDescriptor ) {
2737 fm = state.getMethodFlat( (MethodDescriptor) d);
2739 assert d instanceof TaskDescriptor;
2740 fm = state.getMethodFlat( (TaskDescriptor) d);
2742 pm.analyzeMethod(fm);
2744 // visit every node in this FlatMethod's IR graph
2745 // and make a set of the allocation sites from the
2746 // FlatNew node's visited
2747 HashSet<FlatNode> visited = new HashSet<FlatNode>();
2748 HashSet<FlatNode> toVisit = new HashSet<FlatNode>();
2751 while( !toVisit.isEmpty() ) {
2752 FlatNode n = toVisit.iterator().next();
2754 if( n instanceof FlatNew ) {
2755 s.add(getAllocSiteFromFlatNewPRIVATE( (FlatNew) n) );
2761 for( int i = 0; i < pm.numNext(n); ++i ) {
2762 FlatNode child = pm.getNext(n, i);
2763 if( !visited.contains(child) ) {
2769 mapDescriptorToAllocSiteSet.put(d, s);
2772 private HashSet<AllocSite> getFlaggedAllocationSites(Descriptor dIn) {
2774 HashSet<AllocSite> out = new HashSet<AllocSite>();
2775 HashSet<Descriptor> toVisit = new HashSet<Descriptor>();
2776 HashSet<Descriptor> visited = new HashSet<Descriptor>();
2780 while (!toVisit.isEmpty()) {
2781 Descriptor d = toVisit.iterator().next();
2785 HashSet<AllocSite> asSet = getAllocationSiteSet(d);
2786 Iterator asItr = asSet.iterator();
2787 while (asItr.hasNext()) {
2788 AllocSite as = (AllocSite) asItr.next();
2789 if (as.getDisjointAnalysisId() != null) {
2794 // enqueue callees of this method to be searched for
2795 // allocation sites also
2796 Set callees = callGraph.getCalleeSet(d);
2797 if (callees != null) {
2798 Iterator methItr = callees.iterator();
2799 while (methItr.hasNext()) {
2800 MethodDescriptor md = (MethodDescriptor) methItr.next();
2802 if (!visited.contains(md)) {
2813 private HashSet<AllocSite>
2814 getFlaggedAllocationSitesReachableFromTaskPRIVATE(TaskDescriptor td) {
2816 HashSet<AllocSite> asSetTotal = new HashSet<AllocSite>();
2817 HashSet<Descriptor> toVisit = new HashSet<Descriptor>();
2818 HashSet<Descriptor> visited = new HashSet<Descriptor>();
2822 // traverse this task and all methods reachable from this task
2823 while( !toVisit.isEmpty() ) {
2824 Descriptor d = toVisit.iterator().next();
2828 HashSet<AllocSite> asSet = getAllocationSiteSet(d);
2829 Iterator asItr = asSet.iterator();
2830 while( asItr.hasNext() ) {
2831 AllocSite as = (AllocSite) asItr.next();
2832 TypeDescriptor typed = as.getType();
2833 if( typed != null ) {
2834 ClassDescriptor cd = typed.getClassDesc();
2835 if( cd != null && cd.hasFlags() ) {
2841 // enqueue callees of this method to be searched for
2842 // allocation sites also
2843 Set callees = callGraph.getCalleeSet(d);
2844 if( callees != null ) {
2845 Iterator methItr = callees.iterator();
2846 while( methItr.hasNext() ) {
2847 MethodDescriptor md = (MethodDescriptor) methItr.next();
2849 if( !visited.contains(md) ) {
2859 public Set<Descriptor> getDescriptorsToAnalyze() {
2860 return descriptorsToAnalyze;
2863 public EffectsAnalysis getEffectsAnalysis() {
2864 return effectsAnalysis;
2867 public ReachGraph getReachGraph(Descriptor d) {
2868 return mapDescriptorToCompleteReachGraph.get(d);
2871 public ReachGraph getEnterReachGraph(FlatNode fn) {
2872 return fn2rgAtEnter.get(fn);
2875 // get successive captures of the analysis state, use compiler
2877 boolean takeDebugSnapshots = false;
2878 String descSymbolDebug = null;
2879 boolean stopAfterCapture = false;
2880 int snapVisitCounter = 0;
2881 int snapNodeCounter = 0;
2882 int visitStartCapture = 0;
2883 int numVisitsToCapture = 0;
2886 void debugSnapshot(ReachGraph rg, FlatNode fn, boolean in) {
2887 if( snapVisitCounter > visitStartCapture + numVisitsToCapture ) {
2895 if( snapVisitCounter >= visitStartCapture ) {
2896 System.out.println(" @@@ snapping visit="+snapVisitCounter+
2897 ", node="+snapNodeCounter+
2901 graphName = String.format("snap%03d_%04din",
2905 graphName = String.format("snap%03d_%04dout",
2910 graphName = graphName + fn;
2912 rg.writeGraph(graphName,
2913 true, // write labels (variables)
2914 true, // selectively hide intermediate temp vars
2915 true, // prune unreachable heap regions
2916 false, // hide reachability
2917 false, // hide subset reachability states
2918 true, // hide predicates
2919 true); // hide edge taints
2926 public Set<Alloc> canPointToAt( TempDescriptor x,
2927 FlatNode programPoint ) {
2929 ReachGraph rgAtEnter = fn2rgAtEnter.get( programPoint );
2930 if( rgAtEnter == null ) {
2934 return rgAtEnter.canPointTo( x );
2938 public Set<Alloc> canPointToAfter( TempDescriptor x,
2939 FlatNode programPoint ) {
2941 ReachGraph rgAtExit = fn2rgAtExit.get( programPoint );
2942 if( rgAtExit == null ) {
2946 return rgAtExit.canPointTo( x );
2950 public Hashtable< Alloc, Set<Alloc> > canPointToAt( TempDescriptor x,
2952 FlatNode programPoint ) {
2954 ReachGraph rgAtEnter = fn2rgAtEnter.get( programPoint );
2955 if( rgAtEnter == null ) {
2959 return rgAtEnter.canPointTo( x, f.getSymbol(), f.getType() );
2963 public Hashtable< Alloc, Set<Alloc> > canPointToAtElement( TempDescriptor x,
2964 FlatNode programPoint ) {
2966 ReachGraph rgAtEnter = fn2rgAtEnter.get( programPoint );
2967 if( rgAtEnter == null ) {
2971 assert x.getType() != null;
2972 assert x.getType().isArray();
2974 return rgAtEnter.canPointTo( x, arrayElementFieldName, x.getType().dereference() );