Build EC's for globals twice. The first is after constructing the initial
[oota-llvm.git] / lib / Analysis / DataStructure / Local.cpp
1 //===- Local.cpp - Compute a local data structure graph for a function ----===//
2 // 
3 //                     The LLVM Compiler Infrastructure
4 //
5 // This file was developed by the LLVM research group and is distributed under
6 // the University of Illinois Open Source License. See LICENSE.TXT for details.
7 // 
8 //===----------------------------------------------------------------------===//
9 //
10 // Compute the local version of the data structure graph for a function.  The
11 // external interface to this file is the DSGraph constructor.
12 //
13 //===----------------------------------------------------------------------===//
14
15 #include "llvm/Analysis/DataStructure/DataStructure.h"
16 #include "llvm/Analysis/DataStructure/DSGraph.h"
17 #include "llvm/Constants.h"
18 #include "llvm/DerivedTypes.h"
19 #include "llvm/Instructions.h"
20 #include "llvm/Intrinsics.h"
21 #include "llvm/Support/GetElementPtrTypeIterator.h"
22 #include "llvm/Support/InstVisitor.h"
23 #include "llvm/Target/TargetData.h"
24 #include "llvm/Support/CommandLine.h"
25 #include "llvm/Support/Debug.h"
26 #include "llvm/Support/Timer.h"
27
28 // FIXME: This should eventually be a FunctionPass that is automatically
29 // aggregated into a Pass.
30 //
31 #include "llvm/Module.h"
32
33 using namespace llvm;
34
35 static RegisterAnalysis<LocalDataStructures>
36 X("datastructure", "Local Data Structure Analysis");
37
38 static cl::opt<bool>
39 TrackIntegersAsPointers("dsa-track-integers", cl::Hidden,
40          cl::desc("If this is set, track integers as potential pointers"));
41
42 namespace llvm {
43 namespace DS {
44   // isPointerType - Return true if this type is big enough to hold a pointer.
45   bool isPointerType(const Type *Ty) {
46     if (isa<PointerType>(Ty))
47       return true;
48     else if (TrackIntegersAsPointers && Ty->isPrimitiveType() &&Ty->isInteger())
49       return Ty->getPrimitiveSize() >= PointerSize;
50     return false;
51   }
52 }}
53
54 using namespace DS;
55
56 namespace {
57   cl::opt<bool>
58   DisableDirectCallOpt("disable-direct-call-dsopt", cl::Hidden,
59                        cl::desc("Disable direct call optimization in "
60                                 "DSGraph construction"));
61   cl::opt<bool>
62   DisableFieldSensitivity("disable-ds-field-sensitivity", cl::Hidden,
63                           cl::desc("Disable field sensitivity in DSGraphs"));
64
65   //===--------------------------------------------------------------------===//
66   //  GraphBuilder Class
67   //===--------------------------------------------------------------------===//
68   //
69   /// This class is the builder class that constructs the local data structure
70   /// graph by performing a single pass over the function in question.
71   ///
72   class GraphBuilder : InstVisitor<GraphBuilder> {
73     DSGraph &G;
74     DSNodeHandle *RetNode;               // Node that gets returned...
75     DSScalarMap &ScalarMap;
76     std::list<DSCallSite> *FunctionCalls;
77
78   public:
79     GraphBuilder(Function &f, DSGraph &g, DSNodeHandle &retNode, 
80                  std::list<DSCallSite> &fc)
81       : G(g), RetNode(&retNode), ScalarMap(G.getScalarMap()),
82         FunctionCalls(&fc) {
83
84       // Create scalar nodes for all pointer arguments...
85       for (Function::arg_iterator I = f.arg_begin(), E = f.arg_end(); I != E; ++I)
86         if (isPointerType(I->getType()))
87           getValueDest(*I);
88
89       visit(f);  // Single pass over the function
90     }
91
92     // GraphBuilder ctor for working on the globals graph
93     GraphBuilder(DSGraph &g)
94       : G(g), RetNode(0), ScalarMap(G.getScalarMap()), FunctionCalls(0) {
95     }
96
97     void mergeInGlobalInitializer(GlobalVariable *GV);
98
99   private:
100     // Visitor functions, used to handle each instruction type we encounter...
101     friend class InstVisitor<GraphBuilder>;
102     void visitMallocInst(MallocInst &MI) { handleAlloc(MI, true); }
103     void visitAllocaInst(AllocaInst &AI) { handleAlloc(AI, false); }
104     void handleAlloc(AllocationInst &AI, bool isHeap);
105
106     void visitPHINode(PHINode &PN);
107     void visitSelectInst(SelectInst &SI);
108
109     void visitGetElementPtrInst(User &GEP);
110     void visitReturnInst(ReturnInst &RI);
111     void visitLoadInst(LoadInst &LI);
112     void visitStoreInst(StoreInst &SI);
113     void visitCallInst(CallInst &CI);
114     void visitInvokeInst(InvokeInst &II);
115     void visitSetCondInst(SetCondInst &SCI);
116     void visitFreeInst(FreeInst &FI);
117     void visitCastInst(CastInst &CI);
118     void visitInstruction(Instruction &I);
119
120     void visitCallSite(CallSite CS);
121     void visitVANextInst(VANextInst &I);
122     void visitVAArgInst(VAArgInst   &I);
123
124     void MergeConstantInitIntoNode(DSNodeHandle &NH, Constant *C);
125   private:
126     // Helper functions used to implement the visitation functions...
127
128     /// createNode - Create a new DSNode, ensuring that it is properly added to
129     /// the graph.
130     ///
131     DSNode *createNode(const Type *Ty = 0) {
132       DSNode *N = new DSNode(Ty, &G);   // Create the node
133       if (DisableFieldSensitivity) {
134         // Create node handle referring to the old node so that it is
135         // immediately removed from the graph when the node handle is destroyed.
136         DSNodeHandle OldNNH = N;
137         N->foldNodeCompletely();
138         if (DSNode *FN = N->getForwardNode())
139           N = FN;
140       }
141       return N;
142     }
143
144     /// setDestTo - Set the ScalarMap entry for the specified value to point to
145     /// the specified destination.  If the Value already points to a node, make
146     /// sure to merge the two destinations together.
147     ///
148     void setDestTo(Value &V, const DSNodeHandle &NH);
149
150     /// getValueDest - Return the DSNode that the actual value points to. 
151     ///
152     DSNodeHandle getValueDest(Value &V);
153
154     /// getLink - This method is used to return the specified link in the
155     /// specified node if one exists.  If a link does not already exist (it's
156     /// null), then we create a new node, link it, then return it.
157     ///
158     DSNodeHandle &getLink(const DSNodeHandle &Node, unsigned Link = 0);
159   };
160 }
161
162 using namespace DS;
163
164 //===----------------------------------------------------------------------===//
165 // DSGraph constructor - Simply use the GraphBuilder to construct the local
166 // graph.
167 DSGraph::DSGraph(EquivalenceClasses<GlobalValue*> &ECs, const TargetData &td,
168                  Function &F, DSGraph *GG)
169   : GlobalsGraph(GG), ScalarMap(ECs), TD(td) {
170   PrintAuxCalls = false;
171
172   DEBUG(std::cerr << "  [Loc] Calculating graph for: " << F.getName() << "\n");
173
174   // Use the graph builder to construct the local version of the graph
175   GraphBuilder B(F, *this, ReturnNodes[&F], FunctionCalls);
176 #ifndef NDEBUG
177   Timer::addPeakMemoryMeasurement();
178 #endif
179
180   // Remove all integral constants from the scalarmap!
181   for (DSScalarMap::iterator I = ScalarMap.begin(); I != ScalarMap.end();)
182     if (isa<ConstantIntegral>(I->first))
183       ScalarMap.erase(I++);
184     else
185       ++I;
186
187   // If there are any constant globals referenced in this function, merge their
188   // initializers into the local graph from the globals graph.
189   if (ScalarMap.global_begin() != ScalarMap.global_end()) {
190     ReachabilityCloner RC(*this, *GG, 0);
191     
192     for (DSScalarMap::global_iterator I = ScalarMap.global_begin();
193          I != ScalarMap.global_end(); ++I)
194       if (GlobalVariable *GV = dyn_cast<GlobalVariable>(*I))
195         if (!GV->isExternal() && GV->isConstant())
196           RC.merge(ScalarMap[GV], GG->ScalarMap[GV]);
197   }
198
199   markIncompleteNodes(DSGraph::MarkFormalArgs);
200
201   // Remove any nodes made dead due to merging...
202   removeDeadNodes(DSGraph::KeepUnreachableGlobals);
203 }
204
205
206 //===----------------------------------------------------------------------===//
207 // Helper method implementations...
208 //
209
210 /// getValueDest - Return the DSNode that the actual value points to.
211 ///
212 DSNodeHandle GraphBuilder::getValueDest(Value &Val) {
213   Value *V = &Val;
214   if (isa<Constant>(V) && cast<Constant>(V)->isNullValue())
215     return 0;  // Null doesn't point to anything, don't add to ScalarMap!
216
217   DSNodeHandle &NH = ScalarMap[V];
218   if (!NH.isNull())
219     return NH;     // Already have a node?  Just return it...
220
221   // Otherwise we need to create a new node to point to.
222   // Check first for constant expressions that must be traversed to
223   // extract the actual value.
224   DSNode* N;
225   if (GlobalValue* GV = dyn_cast<GlobalValue>(V)) {
226     // Create a new global node for this global variable.
227     N = createNode(GV->getType()->getElementType());
228     N->addGlobal(GV);
229   } else if (Constant *C = dyn_cast<Constant>(V)) {
230     if (ConstantExpr *CE = dyn_cast<ConstantExpr>(C)) {
231       if (CE->getOpcode() == Instruction::Cast)
232         NH = getValueDest(*CE->getOperand(0));
233       else if (CE->getOpcode() == Instruction::GetElementPtr) {
234         visitGetElementPtrInst(*CE);
235         DSScalarMap::iterator I = ScalarMap.find(CE);
236         assert(I != ScalarMap.end() && "GEP didn't get processed right?");
237         NH = I->second;
238       } else {
239         // This returns a conservative unknown node for any unhandled ConstExpr
240         return NH = createNode()->setUnknownNodeMarker();
241       }
242       if (NH.isNull()) {  // (getelementptr null, X) returns null
243         ScalarMap.erase(V);
244         return 0;
245       }
246       return NH;
247
248     } else if (ConstantIntegral *CI = dyn_cast<ConstantIntegral>(C)) {
249       // Random constants are unknown mem
250       return NH = createNode()->setUnknownNodeMarker();
251     } else if (isa<UndefValue>(C)) {
252       ScalarMap.erase(V);
253       return 0;
254     } else {
255       assert(0 && "Unknown constant type!");
256     }
257     N = createNode(); // just create a shadow node
258   } else {
259     // Otherwise just create a shadow node
260     N = createNode();
261   }
262
263   NH.setTo(N, 0);      // Remember that we are pointing to it...
264   return NH;
265 }
266
267
268 /// getLink - This method is used to return the specified link in the
269 /// specified node if one exists.  If a link does not already exist (it's
270 /// null), then we create a new node, link it, then return it.  We must
271 /// specify the type of the Node field we are accessing so that we know what
272 /// type should be linked to if we need to create a new node.
273 ///
274 DSNodeHandle &GraphBuilder::getLink(const DSNodeHandle &node, unsigned LinkNo) {
275   DSNodeHandle &Node = const_cast<DSNodeHandle&>(node);
276   DSNodeHandle &Link = Node.getLink(LinkNo);
277   if (Link.isNull()) {
278     // If the link hasn't been created yet, make and return a new shadow node
279     Link = createNode();
280   }
281   return Link;
282 }
283
284
285 /// setDestTo - Set the ScalarMap entry for the specified value to point to the
286 /// specified destination.  If the Value already points to a node, make sure to
287 /// merge the two destinations together.
288 ///
289 void GraphBuilder::setDestTo(Value &V, const DSNodeHandle &NH) {
290   ScalarMap[&V].mergeWith(NH);
291 }
292
293
294 //===----------------------------------------------------------------------===//
295 // Specific instruction type handler implementations...
296 //
297
298 /// Alloca & Malloc instruction implementation - Simply create a new memory
299 /// object, pointing the scalar to it.
300 ///
301 void GraphBuilder::handleAlloc(AllocationInst &AI, bool isHeap) {
302   DSNode *N = createNode();
303   if (isHeap)
304     N->setHeapNodeMarker();
305   else
306     N->setAllocaNodeMarker();
307   setDestTo(AI, N);
308 }
309
310 // PHINode - Make the scalar for the PHI node point to all of the things the
311 // incoming values point to... which effectively causes them to be merged.
312 //
313 void GraphBuilder::visitPHINode(PHINode &PN) {
314   if (!isPointerType(PN.getType())) return; // Only pointer PHIs
315
316   DSNodeHandle &PNDest = ScalarMap[&PN];
317   for (unsigned i = 0, e = PN.getNumIncomingValues(); i != e; ++i)
318     PNDest.mergeWith(getValueDest(*PN.getIncomingValue(i)));
319 }
320
321 void GraphBuilder::visitSelectInst(SelectInst &SI) {
322   if (!isPointerType(SI.getType())) return; // Only pointer Selects
323   
324   DSNodeHandle &Dest = ScalarMap[&SI];
325   Dest.mergeWith(getValueDest(*SI.getOperand(1)));
326   Dest.mergeWith(getValueDest(*SI.getOperand(2)));
327 }
328
329 void GraphBuilder::visitSetCondInst(SetCondInst &SCI) {
330   if (!isPointerType(SCI.getOperand(0)->getType()) ||
331       isa<ConstantPointerNull>(SCI.getOperand(1))) return; // Only pointers
332   ScalarMap[SCI.getOperand(0)].mergeWith(getValueDest(*SCI.getOperand(1)));
333 }
334
335
336 void GraphBuilder::visitGetElementPtrInst(User &GEP) {
337   DSNodeHandle Value = getValueDest(*GEP.getOperand(0));
338   if (Value.isNull())
339     Value = createNode();
340
341   // As a special case, if all of the index operands of GEP are constant zeros,
342   // handle this just like we handle casts (ie, don't do much).
343   bool AllZeros = true;
344   for (unsigned i = 1, e = GEP.getNumOperands(); i != e; ++i)
345     if (GEP.getOperand(i) !=
346            Constant::getNullValue(GEP.getOperand(i)->getType())) {
347       AllZeros = false;
348       break;
349     }
350
351   // If all of the indices are zero, the result points to the operand without
352   // applying the type.
353   if (AllZeros || (!Value.isNull() &&
354                    Value.getNode()->isNodeCompletelyFolded())) {
355     setDestTo(GEP, Value);
356     return;
357   }
358
359
360   const PointerType *PTy = cast<PointerType>(GEP.getOperand(0)->getType());
361   const Type *CurTy = PTy->getElementType();
362
363   if (Value.getNode()->mergeTypeInfo(CurTy, Value.getOffset())) {
364     // If the node had to be folded... exit quickly
365     setDestTo(GEP, Value);  // GEP result points to folded node
366     return;
367   }
368
369   const TargetData &TD = Value.getNode()->getTargetData();
370
371 #if 0
372   // Handle the pointer index specially...
373   if (GEP.getNumOperands() > 1 &&
374       (!isa<Constant>(GEP.getOperand(1)) ||
375        !cast<Constant>(GEP.getOperand(1))->isNullValue())) {
376
377     // If we already know this is an array being accessed, don't do anything...
378     if (!TopTypeRec.isArray) {
379       TopTypeRec.isArray = true;
380
381       // If we are treating some inner field pointer as an array, fold the node
382       // up because we cannot handle it right.  This can come because of
383       // something like this:  &((&Pt->X)[1]) == &Pt->Y
384       //
385       if (Value.getOffset()) {
386         // Value is now the pointer we want to GEP to be...
387         Value.getNode()->foldNodeCompletely();
388         setDestTo(GEP, Value);  // GEP result points to folded node
389         return;
390       } else {
391         // This is a pointer to the first byte of the node.  Make sure that we
392         // are pointing to the outter most type in the node.
393         // FIXME: We need to check one more case here...
394       }
395     }
396   }
397 #endif
398
399   // All of these subscripts are indexing INTO the elements we have...
400   unsigned Offset = 0;
401   for (gep_type_iterator I = gep_type_begin(GEP), E = gep_type_end(GEP);
402        I != E; ++I)
403     if (const StructType *STy = dyn_cast<StructType>(*I)) {
404       unsigned FieldNo =
405            (unsigned)cast<ConstantUInt>(I.getOperand())->getValue();
406       Offset += (unsigned)TD.getStructLayout(STy)->MemberOffsets[FieldNo];
407     } else if (const PointerType *PTy = dyn_cast<PointerType>(*I)) {
408       if (!isa<Constant>(I.getOperand()) ||
409           !cast<Constant>(I.getOperand())->isNullValue())
410         Value.getNode()->setArrayMarker();
411     }
412
413
414 #if 0
415     if (const SequentialType *STy = cast<SequentialType>(*I)) {
416       CurTy = STy->getElementType();
417       if (ConstantSInt *CS = dyn_cast<ConstantSInt>(GEP.getOperand(i))) {
418         Offset += CS->getValue()*TD.getTypeSize(CurTy);
419       } else {
420         // Variable index into a node.  We must merge all of the elements of the
421         // sequential type here.
422         if (isa<PointerType>(STy))
423           std::cerr << "Pointer indexing not handled yet!\n";
424         else {
425           const ArrayType *ATy = cast<ArrayType>(STy);
426           unsigned ElSize = TD.getTypeSize(CurTy);
427           DSNode *N = Value.getNode();
428           assert(N && "Value must have a node!");
429           unsigned RawOffset = Offset+Value.getOffset();
430
431           // Loop over all of the elements of the array, merging them into the
432           // zeroth element.
433           for (unsigned i = 1, e = ATy->getNumElements(); i != e; ++i)
434             // Merge all of the byte components of this array element
435             for (unsigned j = 0; j != ElSize; ++j)
436               N->mergeIndexes(RawOffset+j, RawOffset+i*ElSize+j);
437         }
438       }
439     }
440 #endif
441
442   // Add in the offset calculated...
443   Value.setOffset(Value.getOffset()+Offset);
444
445   // Value is now the pointer we want to GEP to be...
446   setDestTo(GEP, Value);
447 }
448
449 void GraphBuilder::visitLoadInst(LoadInst &LI) {
450   DSNodeHandle Ptr = getValueDest(*LI.getOperand(0));
451   if (Ptr.isNull())
452     Ptr = createNode();
453
454   // Make that the node is read from...
455   Ptr.getNode()->setReadMarker();
456
457   // Ensure a typerecord exists...
458   Ptr.getNode()->mergeTypeInfo(LI.getType(), Ptr.getOffset(), false);
459
460   if (isPointerType(LI.getType()))
461     setDestTo(LI, getLink(Ptr));
462 }
463
464 void GraphBuilder::visitStoreInst(StoreInst &SI) {
465   const Type *StoredTy = SI.getOperand(0)->getType();
466   DSNodeHandle Dest = getValueDest(*SI.getOperand(1));
467   if (Dest.isNull()) return;
468
469   // Mark that the node is written to...
470   Dest.getNode()->setModifiedMarker();
471
472   // Ensure a type-record exists...
473   Dest.getNode()->mergeTypeInfo(StoredTy, Dest.getOffset());
474
475   // Avoid adding edges from null, or processing non-"pointer" stores
476   if (isPointerType(StoredTy))
477     Dest.addEdgeTo(getValueDest(*SI.getOperand(0)));
478 }
479
480 void GraphBuilder::visitReturnInst(ReturnInst &RI) {
481   if (RI.getNumOperands() && isPointerType(RI.getOperand(0)->getType()))
482     RetNode->mergeWith(getValueDest(*RI.getOperand(0)));
483 }
484
485 void GraphBuilder::visitVANextInst(VANextInst &I) {
486   getValueDest(*I.getOperand(0)).mergeWith(getValueDest(I));
487 }
488
489 void GraphBuilder::visitVAArgInst(VAArgInst &I) {
490   DSNodeHandle Ptr = getValueDest(*I.getOperand(0));
491   if (Ptr.isNull()) return;
492
493   // Make that the node is read from.
494   Ptr.getNode()->setReadMarker();
495
496   // Ensure a type record exists.
497   DSNode *PtrN = Ptr.getNode();
498   PtrN->mergeTypeInfo(I.getType(), Ptr.getOffset(), false);
499
500   if (isPointerType(I.getType()))
501     setDestTo(I, getLink(Ptr));
502 }
503
504
505 void GraphBuilder::visitCallInst(CallInst &CI) {
506   visitCallSite(&CI);
507 }
508
509 void GraphBuilder::visitInvokeInst(InvokeInst &II) {
510   visitCallSite(&II);
511 }
512
513 void GraphBuilder::visitCallSite(CallSite CS) {
514   Value *Callee = CS.getCalledValue();
515
516   // Special case handling of certain libc allocation functions here.
517   if (Function *F = dyn_cast<Function>(Callee))
518     if (F->isExternal())
519       switch (F->getIntrinsicID()) {
520       case Intrinsic::vastart:
521         getValueDest(*CS.getInstruction()).getNode()->setAllocaNodeMarker();
522         return;
523       case Intrinsic::vacopy:
524         getValueDest(*CS.getInstruction()).
525           mergeWith(getValueDest(**(CS.arg_begin())));
526         return;
527       case Intrinsic::vaend:
528         return;  // noop
529       case Intrinsic::memmove:
530       case Intrinsic::memcpy: {
531         // Merge the first & second arguments, and mark the memory read and
532         // modified.
533         DSNodeHandle RetNH = getValueDest(**CS.arg_begin());
534         RetNH.mergeWith(getValueDest(**(CS.arg_begin()+1)));
535         if (DSNode *N = RetNH.getNode())
536           N->setModifiedMarker()->setReadMarker();
537         return;
538       }
539       case Intrinsic::memset:
540         // Mark the memory modified.
541         if (DSNode *N = getValueDest(**CS.arg_begin()).getNode())
542           N->setModifiedMarker();
543         return;
544       default:
545         if (F->getName() == "calloc" || F->getName() == "posix_memalign" ||
546             F->getName() == "memalign" || F->getName() == "valloc") {
547           setDestTo(*CS.getInstruction(),
548                     createNode()->setHeapNodeMarker()->setModifiedMarker());
549           return;
550         } else if (F->getName() == "realloc") {
551           DSNodeHandle RetNH = getValueDest(*CS.getInstruction());
552           if (CS.arg_begin() != CS.arg_end())
553             RetNH.mergeWith(getValueDest(**CS.arg_begin()));
554           if (DSNode *N = RetNH.getNode())
555             N->setHeapNodeMarker()->setModifiedMarker()->setReadMarker();
556           return;
557         } else if (F->getName() == "memmove") {
558           // Merge the first & second arguments, and mark the memory read and
559           // modified.
560           DSNodeHandle RetNH = getValueDest(**CS.arg_begin());
561           RetNH.mergeWith(getValueDest(**(CS.arg_begin()+1)));
562           if (DSNode *N = RetNH.getNode())
563             N->setModifiedMarker()->setReadMarker();
564           return;
565
566         } else if (F->getName() == "atoi" || F->getName() == "atof" ||
567                    F->getName() == "atol" || F->getName() == "atoll" ||
568                    F->getName() == "remove" || F->getName() == "unlink" ||
569                    F->getName() == "rename" || F->getName() == "memcmp" ||
570                    F->getName() == "strcmp" || F->getName() == "strncmp" ||
571                    F->getName() == "execl" || F->getName() == "execlp" ||
572                    F->getName() == "execle" || F->getName() == "execv" ||
573                    F->getName() == "execvp" || F->getName() == "chmod" ||
574                    F->getName() == "puts" || F->getName() == "write" ||
575                    F->getName() == "open" || F->getName() == "create" ||
576                    F->getName() == "truncate" || F->getName() == "chdir" ||
577                    F->getName() == "mkdir" || F->getName() == "rmdir") {
578           // These functions read all of their pointer operands.
579           for (CallSite::arg_iterator AI = CS.arg_begin(), E = CS.arg_end();
580                AI != E; ++AI) {
581             if (isPointerType((*AI)->getType()))
582               if (DSNode *N = getValueDest(**AI).getNode())
583                 N->setReadMarker();   
584           }
585           return;
586         } else if (F->getName() == "read" || F->getName() == "pipe" ||
587                    F->getName() == "wait" || F->getName() == "time") {
588           // These functions write all of their pointer operands.
589           for (CallSite::arg_iterator AI = CS.arg_begin(), E = CS.arg_end();
590                AI != E; ++AI) {
591             if (isPointerType((*AI)->getType()))
592               if (DSNode *N = getValueDest(**AI).getNode())
593                 N->setModifiedMarker();   
594           }
595           return;
596         } else if (F->getName() == "stat" || F->getName() == "fstat" ||
597                    F->getName() == "lstat") {
598           // These functions read their first operand if its a pointer.
599           CallSite::arg_iterator AI = CS.arg_begin();
600           if (isPointerType((*AI)->getType())) {
601             DSNodeHandle Path = getValueDest(**AI);
602             if (DSNode *N = Path.getNode()) N->setReadMarker();
603           }
604
605           // Then they write into the stat buffer.
606           DSNodeHandle StatBuf = getValueDest(**++AI);
607           if (DSNode *N = StatBuf.getNode()) {
608             N->setModifiedMarker();
609             const Type *StatTy = F->getFunctionType()->getParamType(1);
610             if (const PointerType *PTy = dyn_cast<PointerType>(StatTy))
611               N->mergeTypeInfo(PTy->getElementType(), StatBuf.getOffset());
612           }
613           return;
614         } else if (F->getName() == "strtod" || F->getName() == "strtof" ||
615                    F->getName() == "strtold") {
616           // These functions read the first pointer
617           if (DSNode *Str = getValueDest(**CS.arg_begin()).getNode()) {
618             Str->setReadMarker();
619             // If the second parameter is passed, it will point to the first
620             // argument node.
621             const DSNodeHandle &EndPtrNH = getValueDest(**(CS.arg_begin()+1));
622             if (DSNode *End = EndPtrNH.getNode()) {
623               End->mergeTypeInfo(PointerType::get(Type::SByteTy),
624                                  EndPtrNH.getOffset(), false);
625               End->setModifiedMarker();
626               DSNodeHandle &Link = getLink(EndPtrNH);
627               Link.mergeWith(getValueDest(**CS.arg_begin()));
628             }
629           }
630
631           return;
632         } else if (F->getName() == "fopen" || F->getName() == "fdopen" ||
633                    F->getName() == "freopen") {
634           // These functions read all of their pointer operands.
635           for (CallSite::arg_iterator AI = CS.arg_begin(), E = CS.arg_end();
636                AI != E; ++AI)
637             if (isPointerType((*AI)->getType()))
638               if (DSNode *N = getValueDest(**AI).getNode())
639                 N->setReadMarker();
640           
641           // fopen allocates in an unknown way and writes to the file
642           // descriptor.  Also, merge the allocated type into the node.
643           DSNodeHandle Result = getValueDest(*CS.getInstruction());
644           if (DSNode *N = Result.getNode()) {
645             N->setModifiedMarker()->setUnknownNodeMarker();
646             const Type *RetTy = F->getFunctionType()->getReturnType();
647             if (const PointerType *PTy = dyn_cast<PointerType>(RetTy))
648               N->mergeTypeInfo(PTy->getElementType(), Result.getOffset());
649           }
650
651           // If this is freopen, merge the file descriptor passed in with the
652           // result.
653           if (F->getName() == "freopen") {
654             // ICC doesn't handle getting the iterator, decrementing and
655             // dereferencing it in one operation without error. Do it in 2 steps
656             CallSite::arg_iterator compit = CS.arg_end();
657             Result.mergeWith(getValueDest(**--compit));
658           }
659           return;
660         } else if (F->getName() == "fclose" && CS.arg_end()-CS.arg_begin() ==1){
661           // fclose reads and deallocates the memory in an unknown way for the
662           // file descriptor.  It merges the FILE type into the descriptor.
663           DSNodeHandle H = getValueDest(**CS.arg_begin());
664           if (DSNode *N = H.getNode()) {
665             N->setReadMarker()->setUnknownNodeMarker();
666             const Type *ArgTy = F->getFunctionType()->getParamType(0);
667             if (const PointerType *PTy = dyn_cast<PointerType>(ArgTy))
668               N->mergeTypeInfo(PTy->getElementType(), H.getOffset());
669           }
670           return;
671         } else if (CS.arg_end()-CS.arg_begin() == 1 && 
672                    (F->getName() == "fflush" || F->getName() == "feof" ||
673                     F->getName() == "fileno" || F->getName() == "clearerr" ||
674                     F->getName() == "rewind" || F->getName() == "ftell" ||
675                     F->getName() == "ferror" || F->getName() == "fgetc" ||
676                     F->getName() == "fgetc" || F->getName() == "_IO_getc")) {
677           // fflush reads and writes the memory for the file descriptor.  It
678           // merges the FILE type into the descriptor.
679           DSNodeHandle H = getValueDest(**CS.arg_begin());
680           if (DSNode *N = H.getNode()) {
681             N->setReadMarker()->setModifiedMarker();
682           
683             const Type *ArgTy = F->getFunctionType()->getParamType(0);
684             if (const PointerType *PTy = dyn_cast<PointerType>(ArgTy))
685               N->mergeTypeInfo(PTy->getElementType(), H.getOffset());
686           }
687           return;
688         } else if (CS.arg_end()-CS.arg_begin() == 4 && 
689                    (F->getName() == "fwrite" || F->getName() == "fread")) {
690           // fread writes the first operand, fwrite reads it.  They both
691           // read/write the FILE descriptor, and merges the FILE type.
692           CallSite::arg_iterator compit = CS.arg_end();
693           DSNodeHandle H = getValueDest(**--compit);
694           if (DSNode *N = H.getNode()) {
695             N->setReadMarker()->setModifiedMarker();
696             const Type *ArgTy = F->getFunctionType()->getParamType(3);
697             if (const PointerType *PTy = dyn_cast<PointerType>(ArgTy))
698               N->mergeTypeInfo(PTy->getElementType(), H.getOffset());
699           }
700
701           H = getValueDest(**CS.arg_begin());
702           if (DSNode *N = H.getNode())
703             if (F->getName() == "fwrite")
704               N->setReadMarker();
705             else
706               N->setModifiedMarker();
707           return;
708         } else if (F->getName() == "fgets" && CS.arg_end()-CS.arg_begin() == 3){
709           // fgets reads and writes the memory for the file descriptor.  It
710           // merges the FILE type into the descriptor, and writes to the
711           // argument.  It returns the argument as well.
712           CallSite::arg_iterator AI = CS.arg_begin();
713           DSNodeHandle H = getValueDest(**AI);
714           if (DSNode *N = H.getNode())
715             N->setModifiedMarker();                        // Writes buffer
716           H.mergeWith(getValueDest(*CS.getInstruction())); // Returns buffer
717           ++AI; ++AI;
718
719           // Reads and writes file descriptor, merge in FILE type.
720           H = getValueDest(**AI);
721           if (DSNode *N = H.getNode()) {
722             N->setReadMarker()->setModifiedMarker();
723             const Type *ArgTy = F->getFunctionType()->getParamType(2);
724             if (const PointerType *PTy = dyn_cast<PointerType>(ArgTy))
725               N->mergeTypeInfo(PTy->getElementType(), H.getOffset());
726           }
727           return;
728         } else if (F->getName() == "ungetc" || F->getName() == "fputc" ||
729                    F->getName() == "fputs" || F->getName() == "putc" ||
730                    F->getName() == "ftell" || F->getName() == "rewind" ||
731                    F->getName() == "_IO_putc") {
732           // These functions read and write the memory for the file descriptor,
733           // which is passes as the last argument.
734           CallSite::arg_iterator compit = CS.arg_end();
735           DSNodeHandle H = getValueDest(**--compit);
736           if (DSNode *N = H.getNode()) {
737             N->setReadMarker()->setModifiedMarker();
738             FunctionType::param_iterator compit2 = F->getFunctionType()->param_end();
739             const Type *ArgTy = *--compit2;
740             if (const PointerType *PTy = dyn_cast<PointerType>(ArgTy))
741               N->mergeTypeInfo(PTy->getElementType(), H.getOffset());
742           }
743
744           // Any pointer arguments are read.
745           for (CallSite::arg_iterator AI = CS.arg_begin(), E = CS.arg_end();
746                AI != E; ++AI)
747             if (isPointerType((*AI)->getType()))
748               if (DSNode *N = getValueDest(**AI).getNode())
749                 N->setReadMarker();   
750           return;
751         } else if (F->getName() == "fseek" || F->getName() == "fgetpos" ||
752                    F->getName() == "fsetpos") {
753           // These functions read and write the memory for the file descriptor,
754           // and read/write all other arguments.
755           DSNodeHandle H = getValueDest(**CS.arg_begin());
756           if (DSNode *N = H.getNode()) {
757             FunctionType::param_iterator compit2 = F->getFunctionType()->param_end();
758             const Type *ArgTy = *--compit2;
759             if (const PointerType *PTy = dyn_cast<PointerType>(ArgTy))
760               N->mergeTypeInfo(PTy->getElementType(), H.getOffset());
761           }
762
763           // Any pointer arguments are read.
764           for (CallSite::arg_iterator AI = CS.arg_begin(), E = CS.arg_end();
765                AI != E; ++AI)
766             if (isPointerType((*AI)->getType()))
767               if (DSNode *N = getValueDest(**AI).getNode())
768                 N->setReadMarker()->setModifiedMarker();
769           return;
770         } else if (F->getName() == "printf" || F->getName() == "fprintf" ||
771                    F->getName() == "sprintf") {
772           CallSite::arg_iterator AI = CS.arg_begin(), E = CS.arg_end();
773
774           if (F->getName() == "fprintf") {
775             // fprintf reads and writes the FILE argument, and applies the type
776             // to it.
777             DSNodeHandle H = getValueDest(**AI);
778             if (DSNode *N = H.getNode()) {
779               N->setModifiedMarker();
780               const Type *ArgTy = (*AI)->getType();
781               if (const PointerType *PTy = dyn_cast<PointerType>(ArgTy))
782                 N->mergeTypeInfo(PTy->getElementType(), H.getOffset());
783             }
784           } else if (F->getName() == "sprintf") {
785             // sprintf writes the first string argument.
786             DSNodeHandle H = getValueDest(**AI++);
787             if (DSNode *N = H.getNode()) {
788               N->setModifiedMarker();
789               const Type *ArgTy = (*AI)->getType();
790               if (const PointerType *PTy = dyn_cast<PointerType>(ArgTy))
791                 N->mergeTypeInfo(PTy->getElementType(), H.getOffset());
792             }
793           }
794
795           for (; AI != E; ++AI) {
796             // printf reads all pointer arguments.
797             if (isPointerType((*AI)->getType()))
798               if (DSNode *N = getValueDest(**AI).getNode())
799                 N->setReadMarker();   
800           }
801           return;
802         } else if (F->getName() == "vprintf" || F->getName() == "vfprintf" ||
803                    F->getName() == "vsprintf") {
804           CallSite::arg_iterator AI = CS.arg_begin(), E = CS.arg_end();
805
806           if (F->getName() == "vfprintf") {
807             // ffprintf reads and writes the FILE argument, and applies the type
808             // to it.
809             DSNodeHandle H = getValueDest(**AI);
810             if (DSNode *N = H.getNode()) {
811               N->setModifiedMarker()->setReadMarker();
812               const Type *ArgTy = (*AI)->getType();
813               if (const PointerType *PTy = dyn_cast<PointerType>(ArgTy))
814                 N->mergeTypeInfo(PTy->getElementType(), H.getOffset());
815             }
816             ++AI;
817           } else if (F->getName() == "vsprintf") {
818             // vsprintf writes the first string argument.
819             DSNodeHandle H = getValueDest(**AI++);
820             if (DSNode *N = H.getNode()) {
821               N->setModifiedMarker();
822               const Type *ArgTy = (*AI)->getType();
823               if (const PointerType *PTy = dyn_cast<PointerType>(ArgTy))
824                 N->mergeTypeInfo(PTy->getElementType(), H.getOffset());
825             }
826           }
827
828           // Read the format
829           if (AI != E) {
830             if (isPointerType((*AI)->getType()))
831               if (DSNode *N = getValueDest(**AI).getNode())
832                 N->setReadMarker();
833             ++AI;
834           }
835           
836           // Read the valist, and the pointed-to objects.
837           if (AI != E && isPointerType((*AI)->getType())) {
838             const DSNodeHandle &VAList = getValueDest(**AI);
839             if (DSNode *N = VAList.getNode()) {
840               N->setReadMarker();
841               N->mergeTypeInfo(PointerType::get(Type::SByteTy),
842                                VAList.getOffset(), false);
843
844               DSNodeHandle &VAListObjs = getLink(VAList);
845               VAListObjs.getNode()->setReadMarker();
846             }
847           }
848
849           return;
850         } else if (F->getName() == "scanf" || F->getName() == "fscanf" ||
851                    F->getName() == "sscanf") {
852           CallSite::arg_iterator AI = CS.arg_begin(), E = CS.arg_end();
853
854           if (F->getName() == "fscanf") {
855             // fscanf reads and writes the FILE argument, and applies the type
856             // to it.
857             DSNodeHandle H = getValueDest(**AI);
858             if (DSNode *N = H.getNode()) {
859               N->setReadMarker();
860               const Type *ArgTy = (*AI)->getType();
861               if (const PointerType *PTy = dyn_cast<PointerType>(ArgTy))
862                 N->mergeTypeInfo(PTy->getElementType(), H.getOffset());
863             }
864           } else if (F->getName() == "sscanf") {
865             // sscanf reads the first string argument.
866             DSNodeHandle H = getValueDest(**AI++);
867             if (DSNode *N = H.getNode()) {
868               N->setReadMarker();
869               const Type *ArgTy = (*AI)->getType();
870               if (const PointerType *PTy = dyn_cast<PointerType>(ArgTy))
871                 N->mergeTypeInfo(PTy->getElementType(), H.getOffset());
872             }
873           }
874
875           for (; AI != E; ++AI) {
876             // scanf writes all pointer arguments.
877             if (isPointerType((*AI)->getType()))
878               if (DSNode *N = getValueDest(**AI).getNode())
879                 N->setModifiedMarker();   
880           }
881           return;
882         } else if (F->getName() == "strtok") {
883           // strtok reads and writes the first argument, returning it.  It reads
884           // its second arg.  FIXME: strtok also modifies some hidden static
885           // data.  Someday this might matter.
886           CallSite::arg_iterator AI = CS.arg_begin();
887           DSNodeHandle H = getValueDest(**AI++);
888           if (DSNode *N = H.getNode()) {
889             N->setReadMarker()->setModifiedMarker();      // Reads/Writes buffer
890             const Type *ArgTy = F->getFunctionType()->getParamType(0);
891             if (const PointerType *PTy = dyn_cast<PointerType>(ArgTy))
892               N->mergeTypeInfo(PTy->getElementType(), H.getOffset());
893           }
894           H.mergeWith(getValueDest(*CS.getInstruction())); // Returns buffer
895
896           H = getValueDest(**AI);       // Reads delimiter
897           if (DSNode *N = H.getNode()) {
898             N->setReadMarker();
899             const Type *ArgTy = F->getFunctionType()->getParamType(1);
900             if (const PointerType *PTy = dyn_cast<PointerType>(ArgTy))
901               N->mergeTypeInfo(PTy->getElementType(), H.getOffset());
902           }
903           return;
904         } else if (F->getName() == "strchr" || F->getName() == "strrchr" ||
905                    F->getName() == "strstr") {
906           // These read their arguments, and return the first one
907           DSNodeHandle H = getValueDest(**CS.arg_begin());
908           H.mergeWith(getValueDest(*CS.getInstruction())); // Returns buffer
909
910           for (CallSite::arg_iterator AI = CS.arg_begin(), E = CS.arg_end();
911                AI != E; ++AI)
912             if (isPointerType((*AI)->getType()))
913               if (DSNode *N = getValueDest(**AI).getNode())
914                 N->setReadMarker();
915     
916           if (DSNode *N = H.getNode())
917             N->setReadMarker();
918           return;
919         } else if (F->getName() == "__assert_fail") {
920           for (CallSite::arg_iterator AI = CS.arg_begin(), E = CS.arg_end();
921                AI != E; ++AI)
922             if (isPointerType((*AI)->getType()))
923               if (DSNode *N = getValueDest(**AI).getNode())
924                 N->setReadMarker();
925           return;
926         } else if (F->getName() == "modf" && CS.arg_end()-CS.arg_begin() == 2) {
927           // This writes its second argument, and forces it to double.
928           CallSite::arg_iterator compit = CS.arg_end();
929           DSNodeHandle H = getValueDest(**--compit);
930           if (DSNode *N = H.getNode()) {
931             N->setModifiedMarker();
932             N->mergeTypeInfo(Type::DoubleTy, H.getOffset());
933           }
934           return;
935         } else {
936           // Unknown function, warn if it returns a pointer type or takes a
937           // pointer argument.
938           bool Warn = isPointerType(CS.getInstruction()->getType());
939           if (!Warn)
940             for (CallSite::arg_iterator I = CS.arg_begin(), E = CS.arg_end();
941                  I != E; ++I)
942               if (isPointerType((*I)->getType())) {
943                 Warn = true;
944                 break;
945               }
946           if (Warn)
947             std::cerr << "WARNING: Call to unknown external function '"
948                       << F->getName() << "' will cause pessimistic results!\n";
949         }
950       }
951
952
953   // Set up the return value...
954   DSNodeHandle RetVal;
955   Instruction *I = CS.getInstruction();
956   if (isPointerType(I->getType()))
957     RetVal = getValueDest(*I);
958
959   DSNode *CalleeNode = 0;
960   if (DisableDirectCallOpt || !isa<Function>(Callee)) {
961     CalleeNode = getValueDest(*Callee).getNode();
962     if (CalleeNode == 0) {
963       std::cerr << "WARNING: Program is calling through a null pointer?\n"<< *I;
964       return;  // Calling a null pointer?
965     }
966   }
967
968   std::vector<DSNodeHandle> Args;
969   Args.reserve(CS.arg_end()-CS.arg_begin());
970
971   // Calculate the arguments vector...
972   for (CallSite::arg_iterator I = CS.arg_begin(), E = CS.arg_end(); I != E; ++I)
973     if (isPointerType((*I)->getType()))
974       Args.push_back(getValueDest(**I));
975
976   // Add a new function call entry...
977   if (CalleeNode)
978     FunctionCalls->push_back(DSCallSite(CS, RetVal, CalleeNode, Args));
979   else
980     FunctionCalls->push_back(DSCallSite(CS, RetVal, cast<Function>(Callee),
981                                         Args));
982 }
983
984 void GraphBuilder::visitFreeInst(FreeInst &FI) {
985   // Mark that the node is written to...
986   if (DSNode *N = getValueDest(*FI.getOperand(0)).getNode())
987     N->setModifiedMarker()->setHeapNodeMarker();
988 }
989
990 /// Handle casts...
991 void GraphBuilder::visitCastInst(CastInst &CI) {
992   if (isPointerType(CI.getType()))
993     if (isPointerType(CI.getOperand(0)->getType())) {
994       DSNodeHandle Ptr = getValueDest(*CI.getOperand(0));
995       if (Ptr.getNode() == 0) return;
996
997       // Cast one pointer to the other, just act like a copy instruction
998       setDestTo(CI, Ptr);
999     } else {
1000       // Cast something (floating point, small integer) to a pointer.  We need
1001       // to track the fact that the node points to SOMETHING, just something we
1002       // don't know about.  Make an "Unknown" node.
1003       //
1004       setDestTo(CI, createNode()->setUnknownNodeMarker());
1005     }
1006 }
1007
1008
1009 // visitInstruction - For all other instruction types, if we have any arguments
1010 // that are of pointer type, make them have unknown composition bits, and merge
1011 // the nodes together.
1012 void GraphBuilder::visitInstruction(Instruction &Inst) {
1013   DSNodeHandle CurNode;
1014   if (isPointerType(Inst.getType()))
1015     CurNode = getValueDest(Inst);
1016   for (User::op_iterator I = Inst.op_begin(), E = Inst.op_end(); I != E; ++I)
1017     if (isPointerType((*I)->getType()))
1018       CurNode.mergeWith(getValueDest(**I));
1019
1020   if (DSNode *N = CurNode.getNode())
1021     N->setUnknownNodeMarker();
1022 }
1023
1024
1025
1026 //===----------------------------------------------------------------------===//
1027 // LocalDataStructures Implementation
1028 //===----------------------------------------------------------------------===//
1029
1030 // MergeConstantInitIntoNode - Merge the specified constant into the node
1031 // pointed to by NH.
1032 void GraphBuilder::MergeConstantInitIntoNode(DSNodeHandle &NH, Constant *C) {
1033   // Ensure a type-record exists...
1034   DSNode *NHN = NH.getNode();
1035   NHN->mergeTypeInfo(C->getType(), NH.getOffset());
1036
1037   if (C->getType()->isFirstClassType()) {
1038     if (isPointerType(C->getType()))
1039       // Avoid adding edges from null, or processing non-"pointer" stores
1040       NH.addEdgeTo(getValueDest(*C));
1041     return;
1042   }
1043
1044   const TargetData &TD = NH.getNode()->getTargetData();
1045
1046   if (ConstantArray *CA = dyn_cast<ConstantArray>(C)) {
1047     for (unsigned i = 0, e = CA->getNumOperands(); i != e; ++i)
1048       // We don't currently do any indexing for arrays...
1049       MergeConstantInitIntoNode(NH, cast<Constant>(CA->getOperand(i)));
1050   } else if (ConstantStruct *CS = dyn_cast<ConstantStruct>(C)) {
1051     const StructLayout *SL = TD.getStructLayout(CS->getType());
1052     for (unsigned i = 0, e = CS->getNumOperands(); i != e; ++i) {
1053       DSNode *NHN = NH.getNode();
1054       DSNodeHandle NewNH(NHN, NH.getOffset()+(unsigned)SL->MemberOffsets[i]);
1055       MergeConstantInitIntoNode(NewNH, cast<Constant>(CS->getOperand(i)));
1056     }
1057   } else if (isa<ConstantAggregateZero>(C) || isa<UndefValue>(C)) {
1058     // Noop
1059   } else {
1060     assert(0 && "Unknown constant type!");
1061   }
1062 }
1063
1064 void GraphBuilder::mergeInGlobalInitializer(GlobalVariable *GV) {
1065   assert(!GV->isExternal() && "Cannot merge in external global!");
1066   // Get a node handle to the global node and merge the initializer into it.
1067   DSNodeHandle NH = getValueDest(*GV);
1068   MergeConstantInitIntoNode(NH, GV->getInitializer());
1069 }
1070
1071
1072 /// BuildGlobalECs - Look at all of the nodes in the globals graph.  If any node
1073 /// contains multiple globals, DSA will never, ever, be able to tell the globals
1074 /// apart.  Instead of maintaining this information in all of the graphs
1075 /// throughout the entire program, store only a single global (the "leader") in
1076 /// the graphs, and build equivalence classes for the rest of the globals.
1077 static void BuildGlobalECs(DSGraph &GG, std::set<GlobalValue*> &ECGlobals) {
1078   DSScalarMap &SM = GG.getScalarMap();
1079   EquivalenceClasses<GlobalValue*> &GlobalECs = SM.getGlobalECs();
1080   for (DSGraph::node_iterator I = GG.node_begin(), E = GG.node_end();
1081        I != E; ++I) {
1082     if (I->getGlobalsList().size() <= 1) continue;
1083
1084     // First, build up the equivalence set for this block of globals.
1085     const std::vector<GlobalValue*> &GVs = I->getGlobalsList();
1086     GlobalValue *First = GVs[0];
1087     for (unsigned i = 1, e = GVs.size(); i != e; ++i)
1088       GlobalECs.unionSets(First, GVs[i]);
1089     
1090     // Next, get the leader element.
1091     assert(First == GlobalECs.getLeaderValue(First) &&
1092            "First did not end up being the leader?");
1093     
1094     // Next, remove all globals from the scalar map that are not the leader.
1095     assert(GVs[0] == First && "First had to be at the front!");
1096     for (unsigned i = 1, e = GVs.size(); i != e; ++i) {
1097       ECGlobals.insert(GVs[i]);
1098       SM.erase(SM.find(GVs[i]));
1099     }
1100     
1101     // Finally, change the global node to only contain the leader.
1102     I->clearGlobals();
1103     I->addGlobal(First);
1104   }
1105   
1106   DEBUG(GG.AssertGraphOK());
1107 }
1108
1109 /// EliminateUsesOfECGlobals - Once we have determined that some globals are in
1110 /// really just equivalent to some other globals, remove the globals from the
1111 /// specified DSGraph (if present), and merge any nodes with their leader nodes.
1112 static void EliminateUsesOfECGlobals(DSGraph &G,
1113                                      const std::set<GlobalValue*> &ECGlobals) {
1114   DSScalarMap &SM = G.getScalarMap();
1115   EquivalenceClasses<GlobalValue*> &GlobalECs = SM.getGlobalECs();
1116
1117   bool MadeChange = false;
1118   for (DSScalarMap::global_iterator GI = SM.global_begin(), E = SM.global_end();
1119        GI != E; ) {
1120     GlobalValue *GV = *GI++;
1121     if (!ECGlobals.count(GV)) continue;
1122
1123     const DSNodeHandle &GVNH = SM[GV];
1124     assert(!GVNH.isNull() && "Global has null NH!?");
1125
1126     // Okay, this global is in some equivalence class.  Start by finding the
1127     // leader of the class.
1128     GlobalValue *Leader = GlobalECs.getLeaderValue(GV);
1129
1130     // If the leader isn't already in the graph, insert it into the node
1131     // corresponding to GV.
1132     if (!SM.global_count(Leader)) {
1133       GVNH.getNode()->addGlobal(Leader);
1134       SM[Leader] = GVNH;
1135     } else {
1136       // Otherwise, the leader is in the graph, make sure the nodes are the
1137       // merged in the specified graph.
1138       const DSNodeHandle &LNH = SM[Leader];
1139       if (LNH.getNode() != GVNH.getNode())
1140         LNH.mergeWith(GVNH);
1141     }
1142
1143     // Next step, remove the global from the DSNode.
1144     GVNH.getNode()->removeGlobal(GV);
1145
1146     // Finally, remove the global from the ScalarMap.
1147     SM.erase(GV);
1148     MadeChange = true;
1149   }
1150
1151   DEBUG(if(MadeChange) G.AssertGraphOK());
1152 }
1153
1154 bool LocalDataStructures::runOnModule(Module &M) {
1155   const TargetData &TD = getAnalysis<TargetData>();
1156
1157   // First step, build the globals graph.
1158   GlobalsGraph = new DSGraph(GlobalECs, TD);
1159   {
1160     GraphBuilder GGB(*GlobalsGraph);
1161     
1162     // Add initializers for all of the globals to the globals graph.
1163     for (Module::global_iterator I = M.global_begin(), E = M.global_end();
1164          I != E; ++I)
1165       if (!I->isExternal())
1166         GGB.mergeInGlobalInitializer(I);
1167   }
1168
1169   // Next step, iterate through the nodes in the globals graph, unioning
1170   // together the globals into equivalence classes.
1171   std::set<GlobalValue*> ECGlobals;
1172   BuildGlobalECs(*GlobalsGraph, ECGlobals);
1173   DEBUG(std::cerr << "Eliminating " << ECGlobals.size() << " EC Globals!\n");
1174   ECGlobals.clear();
1175
1176   // Calculate all of the graphs...
1177   for (Module::iterator I = M.begin(), E = M.end(); I != E; ++I)
1178     if (!I->isExternal())
1179       DSInfo.insert(std::make_pair(I, new DSGraph(GlobalECs, TD, *I,
1180                                                   GlobalsGraph)));
1181
1182   GlobalsGraph->removeTriviallyDeadNodes();
1183   GlobalsGraph->markIncompleteNodes(DSGraph::MarkFormalArgs);
1184
1185   // Now that we've computed all of the graphs, and merged all of the info into
1186   // the globals graph, see if we have further constrained the globals in the
1187   // program if so, update GlobalECs and remove the extraneous globals from the
1188   // program.
1189   BuildGlobalECs(*GlobalsGraph, ECGlobals);
1190   if (!ECGlobals.empty()) {
1191     DEBUG(std::cerr << "Eliminating " << ECGlobals.size() << " EC Globals!\n");
1192     for (hash_map<Function*, DSGraph*>::iterator I = DSInfo.begin(),
1193            E = DSInfo.end(); I != E; ++I)
1194       EliminateUsesOfECGlobals(*I->second, ECGlobals);
1195   }
1196
1197   return false;
1198 }
1199
1200 // releaseMemory - If the pass pipeline is done with this pass, we can release
1201 // our memory... here...
1202 //
1203 void LocalDataStructures::releaseMemory() {
1204   for (hash_map<Function*, DSGraph*>::iterator I = DSInfo.begin(),
1205          E = DSInfo.end(); I != E; ++I) {
1206     I->second->getReturnNodes().erase(I->first);
1207     if (I->second->getReturnNodes().empty())
1208       delete I->second;
1209   }
1210
1211   // Empty map so next time memory is released, data structures are not
1212   // re-deleted.
1213   DSInfo.clear();
1214   delete GlobalsGraph;
1215   GlobalsGraph = 0;
1216 }
1217