Fix VS warnings.
[oota-llvm.git] / lib / Transforms / IPO / GlobalOpt.cpp
1 //===- GlobalOpt.cpp - Optimize Global Variables --------------------------===//
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 // This pass transforms simple global variables that never have their address
11 // taken.  If obviously true, it marks read/write globals as constant, deletes
12 // variables only stored to, etc.
13 //
14 //===----------------------------------------------------------------------===//
15
16 #define DEBUG_TYPE "globalopt"
17 #include "llvm/Transforms/IPO.h"
18 #include "llvm/Constants.h"
19 #include "llvm/DerivedTypes.h"
20 #include "llvm/Instructions.h"
21 #include "llvm/Module.h"
22 #include "llvm/Pass.h"
23 #include "llvm/Support/Debug.h"
24 #include "llvm/Target/TargetData.h"
25 #include "llvm/Transforms/Utils/Local.h"
26 #include "llvm/ADT/Statistic.h"
27 #include "llvm/ADT/StringExtras.h"
28 #include <set>
29 #include <algorithm>
30 using namespace llvm;
31
32 namespace {
33   Statistic<> NumMarked   ("globalopt", "Number of globals marked constant");
34   Statistic<> NumSRA      ("globalopt", "Number of aggregate globals broken "
35                            "into scalars");
36   Statistic<> NumSubstitute("globalopt",
37                         "Number of globals with initializers stored into them");
38   Statistic<> NumDeleted  ("globalopt", "Number of globals deleted");
39   Statistic<> NumFnDeleted("globalopt", "Number of functions deleted");
40   Statistic<> NumGlobUses ("globalopt", "Number of global uses devirtualized");
41   Statistic<> NumShrunkToBool("globalopt",
42                               "Number of global vars shrunk to booleans");
43
44   struct GlobalOpt : public ModulePass {
45     virtual void getAnalysisUsage(AnalysisUsage &AU) const {
46       AU.addRequired<TargetData>();
47     }
48     
49     bool runOnModule(Module &M);
50
51   private:
52     bool ProcessInternalGlobal(GlobalVariable *GV, Module::giterator &GVI);
53   };
54
55   RegisterOpt<GlobalOpt> X("globalopt", "Global Variable Optimizer");
56 }
57
58 ModulePass *llvm::createGlobalOptimizerPass() { return new GlobalOpt(); }
59
60 /// GlobalStatus - As we analyze each global, keep track of some information
61 /// about it.  If we find out that the address of the global is taken, none of
62 /// this info will be accurate.
63 struct GlobalStatus {
64   /// isLoaded - True if the global is ever loaded.  If the global isn't ever
65   /// loaded it can be deleted.
66   bool isLoaded;
67
68   /// StoredType - Keep track of what stores to the global look like.
69   ///
70   enum StoredType {
71     /// NotStored - There is no store to this global.  It can thus be marked
72     /// constant.
73     NotStored,
74
75     /// isInitializerStored - This global is stored to, but the only thing
76     /// stored is the constant it was initialized with.  This is only tracked
77     /// for scalar globals.
78     isInitializerStored,
79
80     /// isStoredOnce - This global is stored to, but only its initializer and
81     /// one other value is ever stored to it.  If this global isStoredOnce, we
82     /// track the value stored to it in StoredOnceValue below.  This is only
83     /// tracked for scalar globals.
84     isStoredOnce,
85
86     /// isStored - This global is stored to by multiple values or something else
87     /// that we cannot track.
88     isStored
89   } StoredType;
90
91   /// StoredOnceValue - If only one value (besides the initializer constant) is
92   /// ever stored to this global, keep track of what value it is.
93   Value *StoredOnceValue;
94
95   /// isNotSuitableForSRA - Keep track of whether any SRA preventing users of
96   /// the global exist.  Such users include GEP instruction with variable
97   /// indexes, and non-gep/load/store users like constant expr casts.
98   bool isNotSuitableForSRA;
99
100   GlobalStatus() : isLoaded(false), StoredType(NotStored), StoredOnceValue(0),
101                    isNotSuitableForSRA(false) {}
102 };
103
104
105
106 /// ConstantIsDead - Return true if the specified constant is (transitively)
107 /// dead.  The constant may be used by other constants (e.g. constant arrays and
108 /// constant exprs) as long as they are dead, but it cannot be used by anything
109 /// else.
110 static bool ConstantIsDead(Constant *C) {
111   if (isa<GlobalValue>(C)) return false;
112
113   for (Value::use_iterator UI = C->use_begin(), E = C->use_end(); UI != E; ++UI)
114     if (Constant *CU = dyn_cast<Constant>(*UI)) {
115       if (!ConstantIsDead(CU)) return false;
116     } else
117       return false;
118   return true;
119 }
120
121
122 /// AnalyzeGlobal - Look at all uses of the global and fill in the GlobalStatus
123 /// structure.  If the global has its address taken, return true to indicate we
124 /// can't do anything with it.
125 ///
126 static bool AnalyzeGlobal(Value *V, GlobalStatus &GS,
127                           std::set<PHINode*> &PHIUsers) {
128   for (Value::use_iterator UI = V->use_begin(), E = V->use_end(); UI != E; ++UI)
129     if (ConstantExpr *CE = dyn_cast<ConstantExpr>(*UI)) {
130       if (AnalyzeGlobal(CE, GS, PHIUsers)) return true;
131       if (CE->getOpcode() != Instruction::GetElementPtr)
132         GS.isNotSuitableForSRA = true;
133       else if (!GS.isNotSuitableForSRA) {
134         // Check to see if this ConstantExpr GEP is SRA'able.  In particular, we
135         // don't like < 3 operand CE's, and we don't like non-constant integer
136         // indices.
137         if (CE->getNumOperands() < 3 || !CE->getOperand(1)->isNullValue())
138           GS.isNotSuitableForSRA = true;
139         else {
140           for (unsigned i = 1, e = CE->getNumOperands(); i != e; ++i)
141             if (!isa<ConstantInt>(CE->getOperand(i))) {
142               GS.isNotSuitableForSRA = true;
143               break;
144             }
145         }
146       }
147
148     } else if (Instruction *I = dyn_cast<Instruction>(*UI)) {
149       if (isa<LoadInst>(I)) {
150         GS.isLoaded = true;
151       } else if (StoreInst *SI = dyn_cast<StoreInst>(I)) {
152         // Don't allow a store OF the address, only stores TO the address.
153         if (SI->getOperand(0) == V) return true;
154
155         // If this is a direct store to the global (i.e., the global is a scalar
156         // value, not an aggregate), keep more specific information about
157         // stores.
158         if (GS.StoredType != GlobalStatus::isStored)
159           if (GlobalVariable *GV = dyn_cast<GlobalVariable>(SI->getOperand(1))){
160             Value *StoredVal = SI->getOperand(0);
161             if (StoredVal == GV->getInitializer()) {
162               if (GS.StoredType < GlobalStatus::isInitializerStored)
163                 GS.StoredType = GlobalStatus::isInitializerStored;
164             } else if (isa<LoadInst>(StoredVal) &&
165                        cast<LoadInst>(StoredVal)->getOperand(0) == GV) {
166               // G = G
167               if (GS.StoredType < GlobalStatus::isInitializerStored)
168                 GS.StoredType = GlobalStatus::isInitializerStored;
169             } else if (GS.StoredType < GlobalStatus::isStoredOnce) {
170               GS.StoredType = GlobalStatus::isStoredOnce;
171               GS.StoredOnceValue = StoredVal;
172             } else if (GS.StoredType == GlobalStatus::isStoredOnce &&
173                        GS.StoredOnceValue == StoredVal) {
174               // noop.
175             } else {
176               GS.StoredType = GlobalStatus::isStored;
177             }
178           } else {
179             GS.StoredType = GlobalStatus::isStored;
180           }
181       } else if (I->getOpcode() == Instruction::GetElementPtr) {
182         if (AnalyzeGlobal(I, GS, PHIUsers)) return true;
183
184         // If the first two indices are constants, this can be SRA'd.
185         if (isa<GlobalVariable>(I->getOperand(0))) {
186           if (I->getNumOperands() < 3 || !isa<Constant>(I->getOperand(1)) ||
187               !cast<Constant>(I->getOperand(1))->isNullValue() || 
188               !isa<ConstantInt>(I->getOperand(2)))
189             GS.isNotSuitableForSRA = true;
190         } else if (ConstantExpr *CE = dyn_cast<ConstantExpr>(I->getOperand(0))){
191           if (CE->getOpcode() != Instruction::GetElementPtr ||
192               CE->getNumOperands() < 3 || I->getNumOperands() < 2 ||
193               !isa<Constant>(I->getOperand(0)) ||
194               !cast<Constant>(I->getOperand(0))->isNullValue())
195             GS.isNotSuitableForSRA = true;
196         } else {
197           GS.isNotSuitableForSRA = true;
198         }
199       } else if (I->getOpcode() == Instruction::Select) {
200         if (AnalyzeGlobal(I, GS, PHIUsers)) return true;
201         GS.isNotSuitableForSRA = true;
202       } else if (PHINode *PN = dyn_cast<PHINode>(I)) {
203         // PHI nodes we can check just like select or GEP instructions, but we
204         // have to be careful about infinite recursion.
205         if (PHIUsers.insert(PN).second)  // Not already visited.
206           if (AnalyzeGlobal(I, GS, PHIUsers)) return true;
207         GS.isNotSuitableForSRA = true;
208       } else if (isa<SetCondInst>(I)) {
209         GS.isNotSuitableForSRA = true;
210       } else {
211         return true;  // Any other non-load instruction might take address!
212       }
213     } else if (Constant *C = dyn_cast<Constant>(*UI)) {
214       // We might have a dead and dangling constant hanging off of here.
215       if (!ConstantIsDead(C))
216         return true;
217     } else {
218       // Otherwise must be a global or some other user.
219       return true;
220     }
221
222   return false;
223 }
224
225 static Constant *getAggregateConstantElement(Constant *Agg, Constant *Idx) {
226   ConstantInt *CI = dyn_cast<ConstantInt>(Idx);
227   if (!CI) return 0;
228   unsigned IdxV = (unsigned)CI->getRawValue();
229
230   if (ConstantStruct *CS = dyn_cast<ConstantStruct>(Agg)) {
231     if (IdxV < CS->getNumOperands()) return CS->getOperand(IdxV);
232   } else if (ConstantArray *CA = dyn_cast<ConstantArray>(Agg)) {
233     if (IdxV < CA->getNumOperands()) return CA->getOperand(IdxV);
234   } else if (ConstantPacked *CP = dyn_cast<ConstantPacked>(Agg)) {
235     if (IdxV < CP->getNumOperands()) return CP->getOperand(IdxV);
236   } else if (isa<ConstantAggregateZero>(Agg)) {
237     if (const StructType *STy = dyn_cast<StructType>(Agg->getType())) {
238       if (IdxV < STy->getNumElements())
239         return Constant::getNullValue(STy->getElementType(IdxV));
240     } else if (const SequentialType *STy =
241                dyn_cast<SequentialType>(Agg->getType())) {
242       return Constant::getNullValue(STy->getElementType());
243     }
244   } else if (isa<UndefValue>(Agg)) {
245     if (const StructType *STy = dyn_cast<StructType>(Agg->getType())) {
246       if (IdxV < STy->getNumElements())
247         return UndefValue::get(STy->getElementType(IdxV));
248     } else if (const SequentialType *STy =
249                dyn_cast<SequentialType>(Agg->getType())) {
250       return UndefValue::get(STy->getElementType());
251     }
252   }
253   return 0;
254 }
255
256 static Constant *TraverseGEPInitializer(User *GEP, Constant *Init) {
257   if (GEP->getNumOperands() == 1 ||
258       !isa<Constant>(GEP->getOperand(1)) ||
259       !cast<Constant>(GEP->getOperand(1))->isNullValue())
260     return 0;
261
262   for (unsigned i = 2, e = GEP->getNumOperands(); i != e; ++i) {
263     ConstantInt *Idx = dyn_cast<ConstantInt>(GEP->getOperand(i));
264     if (!Idx) return 0;
265     Init = getAggregateConstantElement(Init, Idx);
266     if (Init == 0) return 0;
267   }
268   return Init;
269 }
270
271 /// CleanupConstantGlobalUsers - We just marked GV constant.  Loop over all
272 /// users of the global, cleaning up the obvious ones.  This is largely just a
273 /// quick scan over the use list to clean up the easy and obvious cruft.  This
274 /// returns true if it made a change.
275 static bool CleanupConstantGlobalUsers(Value *V, Constant *Init) {
276   bool Changed = false;
277   for (Value::use_iterator UI = V->use_begin(), E = V->use_end(); UI != E;) {
278     User *U = *UI++;
279     
280     if (LoadInst *LI = dyn_cast<LoadInst>(U)) {
281       // Replace the load with the initializer.
282       LI->replaceAllUsesWith(Init);
283       LI->eraseFromParent();
284       Changed = true;
285     } else if (StoreInst *SI = dyn_cast<StoreInst>(U)) {
286       // Store must be unreachable or storing Init into the global.
287       SI->eraseFromParent();
288       Changed = true;
289     } else if (ConstantExpr *CE = dyn_cast<ConstantExpr>(U)) {
290       if (CE->getOpcode() == Instruction::GetElementPtr) {
291         if (Constant *SubInit = TraverseGEPInitializer(CE, Init))
292           Changed |= CleanupConstantGlobalUsers(CE, SubInit);
293         if (CE->use_empty()) {
294           CE->destroyConstant();
295           Changed = true;
296         }
297       }
298     } else if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(U)) {
299       if (Constant *SubInit = TraverseGEPInitializer(GEP, Init))
300         Changed |= CleanupConstantGlobalUsers(GEP, SubInit);
301       else {
302         // If this GEP has variable indexes, we should still be able to delete
303         // any stores through it.
304         for (Value::use_iterator GUI = GEP->use_begin(), E = GEP->use_end();
305              GUI != E;)
306           if (StoreInst *SI = dyn_cast<StoreInst>(*GUI++)) {
307             SI->eraseFromParent();
308             Changed = true;
309           }
310       }
311
312       if (GEP->use_empty()) {
313         GEP->eraseFromParent();
314         Changed = true;
315       }
316     } else if (Constant *C = dyn_cast<Constant>(U)) {
317       // If we have a chain of dead constantexprs or other things dangling from
318       // us, and if they are all dead, nuke them without remorse.
319       if (ConstantIsDead(C)) {
320         C->destroyConstant();
321         // This could have incalidated UI, start over from scratch.x
322         CleanupConstantGlobalUsers(V, Init);
323         return true;
324       }
325     }
326   }
327   return Changed;
328 }
329
330 /// SRAGlobal - Perform scalar replacement of aggregates on the specified global
331 /// variable.  This opens the door for other optimizations by exposing the
332 /// behavior of the program in a more fine-grained way.  We have determined that
333 /// this transformation is safe already.  We return the first global variable we
334 /// insert so that the caller can reprocess it.
335 static GlobalVariable *SRAGlobal(GlobalVariable *GV) {
336   assert(GV->hasInternalLinkage() && !GV->isConstant());
337   Constant *Init = GV->getInitializer();
338   const Type *Ty = Init->getType();
339   
340   std::vector<GlobalVariable*> NewGlobals;
341   Module::GlobalListType &Globals = GV->getParent()->getGlobalList();
342
343   if (const StructType *STy = dyn_cast<StructType>(Ty)) {
344     NewGlobals.reserve(STy->getNumElements());
345     for (unsigned i = 0, e = STy->getNumElements(); i != e; ++i) {
346       Constant *In = getAggregateConstantElement(Init,
347                                             ConstantUInt::get(Type::UIntTy, i));
348       assert(In && "Couldn't get element of initializer?");
349       GlobalVariable *NGV = new GlobalVariable(STy->getElementType(i), false,
350                                                GlobalVariable::InternalLinkage,
351                                                In, GV->getName()+"."+utostr(i));
352       Globals.insert(GV, NGV);
353       NewGlobals.push_back(NGV);
354     }
355   } else if (const SequentialType *STy = dyn_cast<SequentialType>(Ty)) {
356     unsigned NumElements = 0;
357     if (const ArrayType *ATy = dyn_cast<ArrayType>(STy))
358       NumElements = ATy->getNumElements();
359     else if (const PackedType *PTy = dyn_cast<PackedType>(STy))
360       NumElements = PTy->getNumElements();
361     else
362       assert(0 && "Unknown aggregate sequential type!");
363
364     if (NumElements > 16 && GV->use_size() > 16) return 0; // It's not worth it.
365     NewGlobals.reserve(NumElements);
366     for (unsigned i = 0, e = NumElements; i != e; ++i) {
367       Constant *In = getAggregateConstantElement(Init,
368                                             ConstantUInt::get(Type::UIntTy, i));
369       assert(In && "Couldn't get element of initializer?");
370
371       GlobalVariable *NGV = new GlobalVariable(STy->getElementType(), false,
372                                                GlobalVariable::InternalLinkage,
373                                                In, GV->getName()+"."+utostr(i));
374       Globals.insert(GV, NGV);
375       NewGlobals.push_back(NGV);
376     }
377   }
378
379   if (NewGlobals.empty())
380     return 0;
381
382   DEBUG(std::cerr << "PERFORMING GLOBAL SRA ON: " << *GV);
383
384   Constant *NullInt = Constant::getNullValue(Type::IntTy);
385
386   // Loop over all of the uses of the global, replacing the constantexpr geps,
387   // with smaller constantexpr geps or direct references.
388   while (!GV->use_empty()) {
389     User *GEP = GV->use_back();
390     assert(((isa<ConstantExpr>(GEP) &&
391              cast<ConstantExpr>(GEP)->getOpcode()==Instruction::GetElementPtr)||
392             isa<GetElementPtrInst>(GEP)) && "NonGEP CE's are not SRAable!");
393              
394     // Ignore the 1th operand, which has to be zero or else the program is quite
395     // broken (undefined).  Get the 2nd operand, which is the structure or array
396     // index.
397     unsigned Val =
398        (unsigned)cast<ConstantInt>(GEP->getOperand(2))->getRawValue();
399     if (Val >= NewGlobals.size()) Val = 0; // Out of bound array access.
400
401     Value *NewPtr = NewGlobals[Val];
402
403     // Form a shorter GEP if needed.
404     if (GEP->getNumOperands() > 3)
405       if (ConstantExpr *CE = dyn_cast<ConstantExpr>(GEP)) {
406         std::vector<Constant*> Idxs;
407         Idxs.push_back(NullInt);
408         for (unsigned i = 3, e = CE->getNumOperands(); i != e; ++i)
409           Idxs.push_back(CE->getOperand(i));
410         NewPtr = ConstantExpr::getGetElementPtr(cast<Constant>(NewPtr), Idxs);
411       } else {
412         GetElementPtrInst *GEPI = cast<GetElementPtrInst>(GEP);
413         std::vector<Value*> Idxs;
414         Idxs.push_back(NullInt);
415         for (unsigned i = 3, e = GEPI->getNumOperands(); i != e; ++i)
416           Idxs.push_back(GEPI->getOperand(i));
417         NewPtr = new GetElementPtrInst(NewPtr, Idxs,
418                                        GEPI->getName()+"."+utostr(Val), GEPI);
419       }
420     GEP->replaceAllUsesWith(NewPtr);
421
422     if (GetElementPtrInst *GEPI = dyn_cast<GetElementPtrInst>(GEP))
423       GEPI->eraseFromParent();
424     else
425       cast<ConstantExpr>(GEP)->destroyConstant();
426   }
427
428   // Delete the old global, now that it is dead.
429   Globals.erase(GV);
430   ++NumSRA;
431
432   // Loop over the new globals array deleting any globals that are obviously
433   // dead.  This can arise due to scalarization of a structure or an array that
434   // has elements that are dead.
435   unsigned FirstGlobal = 0;
436   for (unsigned i = 0, e = NewGlobals.size(); i != e; ++i)
437     if (NewGlobals[i]->use_empty()) {
438       Globals.erase(NewGlobals[i]);
439       if (FirstGlobal == i) ++FirstGlobal;
440     }
441
442   return FirstGlobal != NewGlobals.size() ? NewGlobals[FirstGlobal] : 0;
443 }
444
445 /// AllUsesOfValueWillTrapIfNull - Return true if all users of the specified
446 /// value will trap if the value is dynamically null.
447 static bool AllUsesOfValueWillTrapIfNull(Value *V) {
448   for (Value::use_iterator UI = V->use_begin(), E = V->use_end(); UI != E; ++UI)
449     if (isa<LoadInst>(*UI)) {
450       // Will trap.
451     } else if (StoreInst *SI = dyn_cast<StoreInst>(*UI)) {
452       if (SI->getOperand(0) == V) {
453         //std::cerr << "NONTRAPPING USE: " << **UI;
454         return false;  // Storing the value.
455       }
456     } else if (CallInst *CI = dyn_cast<CallInst>(*UI)) {
457       if (CI->getOperand(0) != V) {
458         //std::cerr << "NONTRAPPING USE: " << **UI;
459         return false;  // Not calling the ptr
460       }
461     } else if (InvokeInst *II = dyn_cast<InvokeInst>(*UI)) {
462       if (II->getOperand(0) != V) {
463         //std::cerr << "NONTRAPPING USE: " << **UI;
464         return false;  // Not calling the ptr
465       }
466     } else if (CastInst *CI = dyn_cast<CastInst>(*UI)) {
467       if (!AllUsesOfValueWillTrapIfNull(CI)) return false;
468     } else if (GetElementPtrInst *GEPI = dyn_cast<GetElementPtrInst>(*UI)) {
469       if (!AllUsesOfValueWillTrapIfNull(GEPI)) return false;
470     } else if (isa<SetCondInst>(*UI) && 
471                isa<ConstantPointerNull>(UI->getOperand(1))) {
472       // Ignore setcc X, null
473     } else {
474       //std::cerr << "NONTRAPPING USE: " << **UI;
475       return false;
476     }
477   return true;
478 }
479
480 /// AllUsesOfLoadedValueWillTrapIfNull - Return true if all uses of any loads
481 /// from GV will trap if the loaded value is null.  Note that this also permits
482 /// comparisons of the loaded value against null, as a special case.
483 static bool AllUsesOfLoadedValueWillTrapIfNull(GlobalVariable *GV) {
484   for (Value::use_iterator UI = GV->use_begin(), E = GV->use_end(); UI!=E; ++UI)
485     if (LoadInst *LI = dyn_cast<LoadInst>(*UI)) {
486       if (!AllUsesOfValueWillTrapIfNull(LI))
487         return false;
488     } else if (isa<StoreInst>(*UI)) {
489       // Ignore stores to the global.
490     } else {
491       // We don't know or understand this user, bail out.
492       //std::cerr << "UNKNOWN USER OF GLOBAL!: " << **UI;
493       return false;
494     }
495
496   return true;
497 }
498
499 static bool OptimizeAwayTrappingUsesOfValue(Value *V, Constant *NewV) {
500   bool Changed = false;
501   for (Value::use_iterator UI = V->use_begin(), E = V->use_end(); UI != E; ) {
502     Instruction *I = cast<Instruction>(*UI++);
503     if (LoadInst *LI = dyn_cast<LoadInst>(I)) {
504       LI->setOperand(0, NewV);
505       Changed = true;
506     } else if (StoreInst *SI = dyn_cast<StoreInst>(I)) {
507       if (SI->getOperand(1) == V) {
508         SI->setOperand(1, NewV);
509         Changed = true;
510       }
511     } else if (isa<CallInst>(I) || isa<InvokeInst>(I)) {
512       if (I->getOperand(0) == V) {
513         // Calling through the pointer!  Turn into a direct call, but be careful
514         // that the pointer is not also being passed as an argument.
515         I->setOperand(0, NewV);
516         Changed = true;
517         bool PassedAsArg = false;
518         for (unsigned i = 1, e = I->getNumOperands(); i != e; ++i)
519           if (I->getOperand(i) == V) {
520             PassedAsArg = true;
521             I->setOperand(i, NewV);
522           }
523
524         if (PassedAsArg) {
525           // Being passed as an argument also.  Be careful to not invalidate UI!
526           UI = V->use_begin();
527         }
528       }
529     } else if (CastInst *CI = dyn_cast<CastInst>(I)) {
530       Changed |= OptimizeAwayTrappingUsesOfValue(CI,
531                                     ConstantExpr::getCast(NewV, CI->getType()));
532       if (CI->use_empty()) {
533         Changed = true;
534         CI->eraseFromParent();
535       }
536     } else if (GetElementPtrInst *GEPI = dyn_cast<GetElementPtrInst>(I)) {
537       // Should handle GEP here.
538       std::vector<Constant*> Indices;
539       Indices.reserve(GEPI->getNumOperands()-1);
540       for (unsigned i = 1, e = GEPI->getNumOperands(); i != e; ++i)
541         if (Constant *C = dyn_cast<Constant>(GEPI->getOperand(i)))
542           Indices.push_back(C);
543         else
544           break;
545       if (Indices.size() == GEPI->getNumOperands()-1)
546         Changed |= OptimizeAwayTrappingUsesOfValue(GEPI,
547                                 ConstantExpr::getGetElementPtr(NewV, Indices));
548       if (GEPI->use_empty()) {
549         Changed = true;
550         GEPI->eraseFromParent();
551       }
552     }
553   }
554
555   return Changed;
556 }
557
558
559 /// OptimizeAwayTrappingUsesOfLoads - The specified global has only one non-null
560 /// value stored into it.  If there are uses of the loaded value that would trap
561 /// if the loaded value is dynamically null, then we know that they cannot be
562 /// reachable with a null optimize away the load.
563 static bool OptimizeAwayTrappingUsesOfLoads(GlobalVariable *GV, Constant *LV) {
564   std::vector<LoadInst*> Loads;
565   bool Changed = false;
566
567   // Replace all uses of loads with uses of uses of the stored value.
568   for (Value::use_iterator GUI = GV->use_begin(), E = GV->use_end();
569        GUI != E; ++GUI)
570     if (LoadInst *LI = dyn_cast<LoadInst>(*GUI)) {
571       Loads.push_back(LI);
572       Changed |= OptimizeAwayTrappingUsesOfValue(LI, LV);
573     } else {
574       assert(isa<StoreInst>(*GUI) && "Only expect load and stores!");
575     }
576
577   if (Changed) {
578     DEBUG(std::cerr << "OPTIMIZED LOADS FROM STORED ONCE POINTER: " << *GV);
579     ++NumGlobUses;
580   }
581
582   // Delete all of the loads we can, keeping track of whether we nuked them all!
583   bool AllLoadsGone = true;
584   while (!Loads.empty()) {
585     LoadInst *L = Loads.back();
586     if (L->use_empty()) {
587       L->eraseFromParent();
588       Changed = true;
589     } else {
590       AllLoadsGone = false;
591     }
592     Loads.pop_back();
593   }
594
595   // If we nuked all of the loads, then none of the stores are needed either,
596   // nor is the global.
597   if (AllLoadsGone) {
598     DEBUG(std::cerr << "  *** GLOBAL NOW DEAD!\n");
599     CleanupConstantGlobalUsers(GV, 0);
600     if (GV->use_empty()) {
601       GV->eraseFromParent();
602       ++NumDeleted;
603     }
604     Changed = true;
605   }
606   return Changed;
607 }
608
609 /// ConstantPropUsersOf - Walk the use list of V, constant folding all of the
610 /// instructions that are foldable.
611 static void ConstantPropUsersOf(Value *V) {
612   for (Value::use_iterator UI = V->use_begin(), E = V->use_end(); UI != E; )
613     if (Instruction *I = dyn_cast<Instruction>(*UI++))
614       if (Constant *NewC = ConstantFoldInstruction(I)) {
615         I->replaceAllUsesWith(NewC);
616
617         // Back up UI to avoid invalidating it!
618         bool AtBegin = false;
619         if (UI == V->use_begin())
620           AtBegin = true;
621         else
622           --UI;
623         I->eraseFromParent();
624         if (AtBegin)
625           UI = V->use_begin();
626         else
627           ++UI;
628       }
629 }
630
631 /// OptimizeGlobalAddressOfMalloc - This function takes the specified global
632 /// variable, and transforms the program as if it always contained the result of
633 /// the specified malloc.  Because it is always the result of the specified
634 /// malloc, there is no reason to actually DO the malloc.  Instead, turn the
635 /// malloc into a global, and any laods of GV as uses of the new global.
636 static GlobalVariable *OptimizeGlobalAddressOfMalloc(GlobalVariable *GV,
637                                                      MallocInst *MI) {
638   DEBUG(std::cerr << "PROMOTING MALLOC GLOBAL: " << *GV << "  MALLOC = " <<*MI);
639   ConstantInt *NElements = cast<ConstantInt>(MI->getArraySize());
640
641   if (NElements->getRawValue() != 1) {
642     // If we have an array allocation, transform it to a single element
643     // allocation to make the code below simpler.
644     Type *NewTy = ArrayType::get(MI->getAllocatedType(),
645                                  (unsigned)NElements->getRawValue());
646     MallocInst *NewMI =
647       new MallocInst(NewTy, Constant::getNullValue(Type::UIntTy),
648                      MI->getName(), MI);
649     std::vector<Value*> Indices;
650     Indices.push_back(Constant::getNullValue(Type::IntTy));
651     Indices.push_back(Indices[0]);
652     Value *NewGEP = new GetElementPtrInst(NewMI, Indices,
653                                           NewMI->getName()+".el0", MI);
654     MI->replaceAllUsesWith(NewGEP);
655     MI->eraseFromParent();
656     MI = NewMI;
657   }
658   
659   // Create the new global variable.  The contents of the malloc'd memory is
660   // undefined, so initialize with an undef value.
661   Constant *Init = UndefValue::get(MI->getAllocatedType());
662   GlobalVariable *NewGV = new GlobalVariable(MI->getAllocatedType(), false,
663                                              GlobalValue::InternalLinkage, Init,
664                                              GV->getName()+".body");
665   GV->getParent()->getGlobalList().insert(GV, NewGV);
666   
667   // Anything that used the malloc now uses the global directly.
668   MI->replaceAllUsesWith(NewGV);
669
670   Constant *RepValue = NewGV;
671   if (NewGV->getType() != GV->getType()->getElementType())
672     RepValue = ConstantExpr::getCast(RepValue, GV->getType()->getElementType());
673
674   // If there is a comparison against null, we will insert a global bool to
675   // keep track of whether the global was initialized yet or not.
676   GlobalVariable *InitBool = 
677     new GlobalVariable(Type::BoolTy, false, GlobalValue::InternalLinkage, 
678                        ConstantBool::False, GV->getName()+".init");
679   bool InitBoolUsed = false;
680
681   // Loop over all uses of GV, processing them in turn.
682   std::vector<StoreInst*> Stores;
683   while (!GV->use_empty())
684     if (LoadInst *LI = dyn_cast<LoadInst>(GV->use_back())) {
685       while (!LI->use_empty()) {
686         // FIXME: the iterator should expose a getUse() method.
687         Use &LoadUse = *(const iplist<Use>::iterator&)LI->use_begin();
688         if (!isa<SetCondInst>(LoadUse.getUser()))
689           LoadUse = RepValue;
690         else {
691           // Replace the setcc X, 0 with a use of the bool value.
692           SetCondInst *SCI = cast<SetCondInst>(LoadUse.getUser());
693           Value *LV = new LoadInst(InitBool, InitBool->getName()+".val", SCI);
694           InitBoolUsed = true;
695           switch (SCI->getOpcode()) {
696           default: assert(0 && "Unknown opcode!");
697           case Instruction::SetLT:
698             LV = ConstantBool::False;   // X < null -> always false
699             break;
700           case Instruction::SetEQ:
701           case Instruction::SetLE:
702             LV = BinaryOperator::createNot(LV, "notinit", SCI);
703             break;
704           case Instruction::SetNE:
705           case Instruction::SetGE:
706           case Instruction::SetGT:
707             break;  // no change.
708           }
709           SCI->replaceAllUsesWith(LV);
710           SCI->eraseFromParent();
711         }
712       }
713       LI->eraseFromParent();
714     } else {
715       StoreInst *SI = cast<StoreInst>(GV->use_back());
716       // The global is initialized when the store to it occurs.
717       new StoreInst(ConstantBool::True, InitBool, SI);
718       SI->eraseFromParent();
719     }
720
721   // If the initialization boolean was used, insert it, otherwise delete it.
722   if (!InitBoolUsed) {
723     while (!InitBool->use_empty())  // Delete initializations
724       cast<Instruction>(InitBool->use_back())->eraseFromParent();
725     delete InitBool;
726   } else
727     GV->getParent()->getGlobalList().insert(GV, InitBool);
728
729
730   // Now the GV is dead, nuke it and the malloc.
731   GV->eraseFromParent();
732   MI->eraseFromParent();
733
734   // To further other optimizations, loop over all users of NewGV and try to
735   // constant prop them.  This will promote GEP instructions with constant
736   // indices into GEP constant-exprs, which will allow global-opt to hack on it.
737   ConstantPropUsersOf(NewGV);
738   if (RepValue != NewGV)
739     ConstantPropUsersOf(RepValue);
740
741   return NewGV;
742 }
743
744 /// ValueIsOnlyUsedLocallyOrStoredToOneGlobal - Scan the use-list of V checking
745 /// to make sure that there are no complex uses of V.  We permit simple things
746 /// like dereferencing the pointer, but not storing through the address, unless
747 /// it is to the specified global.
748 static bool ValueIsOnlyUsedLocallyOrStoredToOneGlobal(Instruction *V,
749                                                       GlobalVariable *GV) {
750   for (Value::use_iterator UI = V->use_begin(), E = V->use_end(); UI != E;++UI)
751     if (isa<LoadInst>(*UI) || isa<SetCondInst>(*UI)) {
752       // Fine, ignore.
753     } else if (StoreInst *SI = dyn_cast<StoreInst>(*UI)) {
754       if (SI->getOperand(0) == V && SI->getOperand(1) != GV)
755         return false;  // Storing the pointer itself... bad.
756       // Otherwise, storing through it, or storing into GV... fine.
757     } else if (isa<GetElementPtrInst>(*UI) || isa<SelectInst>(*UI)) {
758       if (!ValueIsOnlyUsedLocallyOrStoredToOneGlobal(cast<Instruction>(*UI),GV))
759         return false;
760     } else {
761       return false;
762     }
763   return true;
764
765 }
766
767 // OptimizeOnceStoredGlobal - Try to optimize globals based on the knowledge
768 // that only one value (besides its initializer) is ever stored to the global.
769 static bool OptimizeOnceStoredGlobal(GlobalVariable *GV, Value *StoredOnceVal,
770                                      Module::giterator &GVI, TargetData &TD) {
771   if (CastInst *CI = dyn_cast<CastInst>(StoredOnceVal))
772     StoredOnceVal = CI->getOperand(0);
773   else if (GetElementPtrInst *GEPI =dyn_cast<GetElementPtrInst>(StoredOnceVal)){
774     // "getelementptr Ptr, 0, 0, 0" is really just a cast.
775     bool IsJustACast = true;
776     for (unsigned i = 1, e = GEPI->getNumOperands(); i != e; ++i)
777       if (!isa<Constant>(GEPI->getOperand(i)) ||
778           !cast<Constant>(GEPI->getOperand(i))->isNullValue()) {
779         IsJustACast = false;
780         break;
781       }
782     if (IsJustACast)
783       StoredOnceVal = GEPI->getOperand(0);
784   }
785
786   // If we are dealing with a pointer global that is initialized to null and
787   // only has one (non-null) value stored into it, then we can optimize any
788   // users of the loaded value (often calls and loads) that would trap if the
789   // value was null.
790   if (isa<PointerType>(GV->getInitializer()->getType()) &&
791       GV->getInitializer()->isNullValue()) {
792     if (Constant *SOVC = dyn_cast<Constant>(StoredOnceVal)) {
793       if (GV->getInitializer()->getType() != SOVC->getType())
794         SOVC = ConstantExpr::getCast(SOVC, GV->getInitializer()->getType());
795       
796       // Optimize away any trapping uses of the loaded value.
797       if (OptimizeAwayTrappingUsesOfLoads(GV, SOVC))
798         return true;
799     } else if (MallocInst *MI = dyn_cast<MallocInst>(StoredOnceVal)) {
800       // If we have a global that is only initialized with a fixed size malloc,
801       // and if all users of the malloc trap, and if the malloc'd address is not
802       // put anywhere else, transform the program to use global memory instead
803       // of malloc'd memory.  This eliminates dynamic allocation (good) and
804       // exposes the resultant global to further GlobalOpt (even better).  Note
805       // that we restrict this transformation to only working on small
806       // allocations (2048 bytes currently), as we don't want to introduce a 16M
807       // global or something.
808       if (ConstantInt *NElements = dyn_cast<ConstantInt>(MI->getArraySize()))
809         if (MI->getAllocatedType()->isSized() &&
810             NElements->getRawValue()*
811                      TD.getTypeSize(MI->getAllocatedType()) < 2048 &&
812             AllUsesOfLoadedValueWillTrapIfNull(GV) &&
813             ValueIsOnlyUsedLocallyOrStoredToOneGlobal(MI, GV)) {
814           GVI = OptimizeGlobalAddressOfMalloc(GV, MI);
815           return true;
816         }
817     }
818   }
819
820   return false;
821 }
822
823 /// ShrinkGlobalToBoolean - At this point, we have learned that the only two
824 /// values ever stored into GV are its initializer and OtherVal.  
825 static void ShrinkGlobalToBoolean(GlobalVariable *GV, Constant *OtherVal) {
826   // Create the new global, initializing it to false.
827   GlobalVariable *NewGV = new GlobalVariable(Type::BoolTy, false,
828          GlobalValue::InternalLinkage, ConstantBool::False, GV->getName()+".b");
829   GV->getParent()->getGlobalList().insert(GV, NewGV);
830
831   Constant *InitVal = GV->getInitializer();
832   assert(InitVal->getType() != Type::BoolTy && "No reason to shrink to bool!");
833
834   // If initialized to zero and storing one into the global, we can use a cast
835   // instead of a select to synthesize the desired value.
836   bool IsOneZero = false;
837   if (ConstantInt *CI = dyn_cast<ConstantInt>(OtherVal))
838     IsOneZero = InitVal->isNullValue() && CI->equalsInt(1);
839
840   while (!GV->use_empty()) {
841     Instruction *UI = cast<Instruction>(GV->use_back());
842     if (StoreInst *SI = dyn_cast<StoreInst>(UI)) {
843       // Change the store into a boolean store.
844       bool StoringOther = SI->getOperand(0) == OtherVal;
845       // Only do this if we weren't storing a loaded value.
846       Value *StoreVal;
847       if (StoringOther || SI->getOperand(0) == InitVal)
848         StoreVal = ConstantBool::get(StoringOther);
849       else {
850         // Otherwise, we are storing a previously loaded copy.  To do this,
851         // change the copy from copying the original value to just copying the
852         // bool.
853         Instruction *StoredVal = cast<Instruction>(SI->getOperand(0));
854
855         // If we're already replaced the input, StoredVal will be a cast or
856         // select instruction.  If not, it will be a load of the original
857         // global.
858         if (LoadInst *LI = dyn_cast<LoadInst>(StoredVal)) {
859           assert(LI->getOperand(0) == GV && "Not a copy!");
860           // Insert a new load, to preserve the saved value.
861           StoreVal = new LoadInst(NewGV, LI->getName()+".b", LI);
862         } else {
863           assert((isa<CastInst>(StoredVal) || isa<SelectInst>(StoredVal)) &&
864                  "This is not a form that we understand!");
865           StoreVal = StoredVal->getOperand(0);
866           assert(isa<LoadInst>(StoreVal) && "Not a load of NewGV!");
867         }
868       }
869       new StoreInst(StoreVal, NewGV, SI);
870     } else if (!UI->use_empty()) {
871       // Change the load into a load of bool then a select.
872       LoadInst *LI = cast<LoadInst>(UI);
873       
874       std::string Name = LI->getName(); LI->setName("");
875       LoadInst *NLI = new LoadInst(NewGV, Name+".b", LI);
876       Value *NSI;
877       if (IsOneZero)
878         NSI = new CastInst(NLI, LI->getType(), Name, LI);
879       else 
880         NSI = new SelectInst(NLI, OtherVal, InitVal, Name, LI);
881       LI->replaceAllUsesWith(NSI);
882     }
883     UI->eraseFromParent();
884   }
885
886   GV->eraseFromParent();
887 }
888
889
890 /// ProcessInternalGlobal - Analyze the specified global variable and optimize
891 /// it if possible.  If we make a change, return true.
892 bool GlobalOpt::ProcessInternalGlobal(GlobalVariable *GV,
893                                       Module::giterator &GVI) {
894   std::set<PHINode*> PHIUsers;
895   GlobalStatus GS;
896   PHIUsers.clear();
897   GV->removeDeadConstantUsers();
898
899   if (GV->use_empty()) {
900     DEBUG(std::cerr << "GLOBAL DEAD: " << *GV);
901     GV->eraseFromParent();
902     ++NumDeleted;
903     return true;
904   }
905
906   if (!AnalyzeGlobal(GV, GS, PHIUsers)) {
907     // If the global is never loaded (but may be stored to), it is dead.
908     // Delete it now.
909     if (!GS.isLoaded) {
910       DEBUG(std::cerr << "GLOBAL NEVER LOADED: " << *GV);
911
912       // Delete any stores we can find to the global.  We may not be able to
913       // make it completely dead though.
914       bool Changed = CleanupConstantGlobalUsers(GV, GV->getInitializer());
915
916       // If the global is dead now, delete it.
917       if (GV->use_empty()) {
918         GV->eraseFromParent();
919         ++NumDeleted;
920         Changed = true;
921       }
922       return Changed;
923           
924     } else if (GS.StoredType <= GlobalStatus::isInitializerStored) {
925       DEBUG(std::cerr << "MARKING CONSTANT: " << *GV);
926       GV->setConstant(true);
927           
928       // Clean up any obviously simplifiable users now.
929       CleanupConstantGlobalUsers(GV, GV->getInitializer());
930           
931       // If the global is dead now, just nuke it.
932       if (GV->use_empty()) {
933         DEBUG(std::cerr << "   *** Marking constant allowed us to simplify "
934               "all users and delete global!\n");
935         GV->eraseFromParent();
936         ++NumDeleted;
937       }
938           
939       ++NumMarked;
940       return true;
941     } else if (!GS.isNotSuitableForSRA &&
942                !GV->getInitializer()->getType()->isFirstClassType()) {
943       if (GlobalVariable *FirstNewGV = SRAGlobal(GV)) {
944         GVI = FirstNewGV;  // Don't skip the newly produced globals!
945         return true;
946       }
947     } else if (GS.StoredType == GlobalStatus::isStoredOnce) {
948       // If the initial value for the global was an undef value, and if only
949       // one other value was stored into it, we can just change the
950       // initializer to be an undef value, then delete all stores to the
951       // global.  This allows us to mark it constant.
952       if (Constant *SOVConstant = dyn_cast<Constant>(GS.StoredOnceValue))
953         if (isa<UndefValue>(GV->getInitializer())) {
954           // Change the initial value here.
955           GV->setInitializer(SOVConstant);
956           
957           // Clean up any obviously simplifiable users now.
958           CleanupConstantGlobalUsers(GV, GV->getInitializer());
959           
960           if (GV->use_empty()) {
961             DEBUG(std::cerr << "   *** Substituting initializer allowed us to "
962                   "simplify all users and delete global!\n");
963             GV->eraseFromParent();
964             ++NumDeleted;
965           } else {
966             GVI = GV;
967           }
968           ++NumSubstitute;
969           return true;
970         }
971
972       // Try to optimize globals based on the knowledge that only one value
973       // (besides its initializer) is ever stored to the global.
974       if (OptimizeOnceStoredGlobal(GV, GS.StoredOnceValue, GVI,
975                                    getAnalysis<TargetData>()))
976         return true;
977
978       // Otherwise, if the global was not a boolean, we can shrink it to be a
979       // boolean.
980       if (Constant *SOVConstant = dyn_cast<Constant>(GS.StoredOnceValue))
981         if (GV->getType()->getElementType() != Type::BoolTy &&
982             !GV->getType()->getElementType()->isFloatingPoint()) {
983           DEBUG(std::cerr << "   *** SHRINKING TO BOOL: " << *GV);
984           ShrinkGlobalToBoolean(GV, SOVConstant);
985           ++NumShrunkToBool;
986           return true;
987         }
988     }
989   }
990   return false;
991 }
992
993
994 bool GlobalOpt::runOnModule(Module &M) {
995   bool Changed = false;
996
997   // As a prepass, delete functions that are trivially dead.
998   bool LocalChange = true;
999   while (LocalChange) {
1000     LocalChange = false;
1001     for (Module::iterator FI = M.begin(), E = M.end(); FI != E; ) {
1002       Function *F = FI++;
1003       F->removeDeadConstantUsers();
1004       if (F->use_empty() && (F->hasInternalLinkage() ||
1005                              F->hasLinkOnceLinkage())) {
1006         M.getFunctionList().erase(F);
1007         LocalChange = true;
1008         ++NumFnDeleted;
1009       }
1010     }
1011     Changed |= LocalChange;
1012   }
1013
1014   LocalChange = true;
1015   while (LocalChange) {
1016     LocalChange = false;
1017     for (Module::giterator GVI = M.gbegin(), E = M.gend(); GVI != E;) {
1018       GlobalVariable *GV = GVI++;
1019       if (!GV->isConstant() && GV->hasInternalLinkage() &&
1020           GV->hasInitializer())
1021         LocalChange |= ProcessInternalGlobal(GV, GVI);
1022     }
1023     Changed |= LocalChange;
1024   }
1025   return Changed;
1026 }