Add a simple interpreter to this code, allowing us to statically evaluate
[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/CallingConv.h"
19 #include "llvm/Constants.h"
20 #include "llvm/DerivedTypes.h"
21 #include "llvm/Instructions.h"
22 #include "llvm/IntrinsicInst.h"
23 #include "llvm/Module.h"
24 #include "llvm/Pass.h"
25 #include "llvm/Support/Debug.h"
26 #include "llvm/Target/TargetData.h"
27 #include "llvm/Transforms/Utils/Local.h"
28 #include "llvm/ADT/Statistic.h"
29 #include "llvm/ADT/StringExtras.h"
30 #include <set>
31 #include <algorithm>
32 using namespace llvm;
33
34 namespace {
35   Statistic<> NumMarked   ("globalopt", "Number of globals marked constant");
36   Statistic<> NumSRA      ("globalopt", "Number of aggregate globals broken "
37                            "into scalars");
38   Statistic<> NumSubstitute("globalopt",
39                         "Number of globals with initializers stored into them");
40   Statistic<> NumDeleted  ("globalopt", "Number of globals deleted");
41   Statistic<> NumFnDeleted("globalopt", "Number of functions deleted");
42   Statistic<> NumGlobUses ("globalopt", "Number of global uses devirtualized");
43   Statistic<> NumLocalized("globalopt", "Number of globals localized");
44   Statistic<> NumShrunkToBool("globalopt",
45                               "Number of global vars shrunk to booleans");
46   Statistic<> NumFastCallFns("globalopt",
47                              "Number of functions converted to fastcc");
48   Statistic<> NumEmptyCtor  ("globalopt", "Number of empty ctors removed");
49   Statistic<> NumCtorsEvaluated("globalopt","Number of static ctors evaluated");
50
51   struct GlobalOpt : public ModulePass {
52     virtual void getAnalysisUsage(AnalysisUsage &AU) const {
53       AU.addRequired<TargetData>();
54     }
55
56     bool runOnModule(Module &M);
57
58   private:
59     GlobalVariable *FindGlobalCtors(Module &M);
60     bool OptimizeFunctions(Module &M);
61     bool OptimizeGlobalVars(Module &M);
62     bool OptimizeGlobalCtorsList(GlobalVariable *&GCL);
63     bool ProcessInternalGlobal(GlobalVariable *GV, Module::global_iterator &GVI);
64   };
65
66   RegisterOpt<GlobalOpt> X("globalopt", "Global Variable Optimizer");
67 }
68
69 ModulePass *llvm::createGlobalOptimizerPass() { return new GlobalOpt(); }
70
71 /// GlobalStatus - As we analyze each global, keep track of some information
72 /// about it.  If we find out that the address of the global is taken, none of
73 /// this info will be accurate.
74 struct GlobalStatus {
75   /// isLoaded - True if the global is ever loaded.  If the global isn't ever
76   /// loaded it can be deleted.
77   bool isLoaded;
78
79   /// StoredType - Keep track of what stores to the global look like.
80   ///
81   enum StoredType {
82     /// NotStored - There is no store to this global.  It can thus be marked
83     /// constant.
84     NotStored,
85
86     /// isInitializerStored - This global is stored to, but the only thing
87     /// stored is the constant it was initialized with.  This is only tracked
88     /// for scalar globals.
89     isInitializerStored,
90
91     /// isStoredOnce - This global is stored to, but only its initializer and
92     /// one other value is ever stored to it.  If this global isStoredOnce, we
93     /// track the value stored to it in StoredOnceValue below.  This is only
94     /// tracked for scalar globals.
95     isStoredOnce,
96
97     /// isStored - This global is stored to by multiple values or something else
98     /// that we cannot track.
99     isStored
100   } StoredType;
101
102   /// StoredOnceValue - If only one value (besides the initializer constant) is
103   /// ever stored to this global, keep track of what value it is.
104   Value *StoredOnceValue;
105
106   // AccessingFunction/HasMultipleAccessingFunctions - These start out
107   // null/false.  When the first accessing function is noticed, it is recorded.
108   // When a second different accessing function is noticed,
109   // HasMultipleAccessingFunctions is set to true.
110   Function *AccessingFunction;
111   bool HasMultipleAccessingFunctions;
112
113   // HasNonInstructionUser - Set to true if this global has a user that is not
114   // an instruction (e.g. a constant expr or GV initializer).
115   bool HasNonInstructionUser;
116
117   /// isNotSuitableForSRA - Keep track of whether any SRA preventing users of
118   /// the global exist.  Such users include GEP instruction with variable
119   /// indexes, and non-gep/load/store users like constant expr casts.
120   bool isNotSuitableForSRA;
121
122   GlobalStatus() : isLoaded(false), StoredType(NotStored), StoredOnceValue(0),
123                    AccessingFunction(0), HasMultipleAccessingFunctions(false),
124                    HasNonInstructionUser(false), isNotSuitableForSRA(false) {}
125 };
126
127
128
129 /// ConstantIsDead - Return true if the specified constant is (transitively)
130 /// dead.  The constant may be used by other constants (e.g. constant arrays and
131 /// constant exprs) as long as they are dead, but it cannot be used by anything
132 /// else.
133 static bool ConstantIsDead(Constant *C) {
134   if (isa<GlobalValue>(C)) return false;
135
136   for (Value::use_iterator UI = C->use_begin(), E = C->use_end(); UI != E; ++UI)
137     if (Constant *CU = dyn_cast<Constant>(*UI)) {
138       if (!ConstantIsDead(CU)) return false;
139     } else
140       return false;
141   return true;
142 }
143
144
145 /// AnalyzeGlobal - Look at all uses of the global and fill in the GlobalStatus
146 /// structure.  If the global has its address taken, return true to indicate we
147 /// can't do anything with it.
148 ///
149 static bool AnalyzeGlobal(Value *V, GlobalStatus &GS,
150                           std::set<PHINode*> &PHIUsers) {
151   for (Value::use_iterator UI = V->use_begin(), E = V->use_end(); UI != E; ++UI)
152     if (ConstantExpr *CE = dyn_cast<ConstantExpr>(*UI)) {
153       GS.HasNonInstructionUser = true;
154
155       if (AnalyzeGlobal(CE, GS, PHIUsers)) return true;
156       if (CE->getOpcode() != Instruction::GetElementPtr)
157         GS.isNotSuitableForSRA = true;
158       else if (!GS.isNotSuitableForSRA) {
159         // Check to see if this ConstantExpr GEP is SRA'able.  In particular, we
160         // don't like < 3 operand CE's, and we don't like non-constant integer
161         // indices.
162         if (CE->getNumOperands() < 3 || !CE->getOperand(1)->isNullValue())
163           GS.isNotSuitableForSRA = true;
164         else {
165           for (unsigned i = 1, e = CE->getNumOperands(); i != e; ++i)
166             if (!isa<ConstantInt>(CE->getOperand(i))) {
167               GS.isNotSuitableForSRA = true;
168               break;
169             }
170         }
171       }
172
173     } else if (Instruction *I = dyn_cast<Instruction>(*UI)) {
174       if (!GS.HasMultipleAccessingFunctions) {
175         Function *F = I->getParent()->getParent();
176         if (GS.AccessingFunction == 0)
177           GS.AccessingFunction = F;
178         else if (GS.AccessingFunction != F)
179           GS.HasMultipleAccessingFunctions = true;
180       }
181       if (isa<LoadInst>(I)) {
182         GS.isLoaded = true;
183       } else if (StoreInst *SI = dyn_cast<StoreInst>(I)) {
184         // Don't allow a store OF the address, only stores TO the address.
185         if (SI->getOperand(0) == V) return true;
186
187         // If this is a direct store to the global (i.e., the global is a scalar
188         // value, not an aggregate), keep more specific information about
189         // stores.
190         if (GS.StoredType != GlobalStatus::isStored)
191           if (GlobalVariable *GV = dyn_cast<GlobalVariable>(SI->getOperand(1))){
192             Value *StoredVal = SI->getOperand(0);
193             if (StoredVal == GV->getInitializer()) {
194               if (GS.StoredType < GlobalStatus::isInitializerStored)
195                 GS.StoredType = GlobalStatus::isInitializerStored;
196             } else if (isa<LoadInst>(StoredVal) &&
197                        cast<LoadInst>(StoredVal)->getOperand(0) == GV) {
198               // G = G
199               if (GS.StoredType < GlobalStatus::isInitializerStored)
200                 GS.StoredType = GlobalStatus::isInitializerStored;
201             } else if (GS.StoredType < GlobalStatus::isStoredOnce) {
202               GS.StoredType = GlobalStatus::isStoredOnce;
203               GS.StoredOnceValue = StoredVal;
204             } else if (GS.StoredType == GlobalStatus::isStoredOnce &&
205                        GS.StoredOnceValue == StoredVal) {
206               // noop.
207             } else {
208               GS.StoredType = GlobalStatus::isStored;
209             }
210           } else {
211             GS.StoredType = GlobalStatus::isStored;
212           }
213       } else if (isa<GetElementPtrInst>(I)) {
214         if (AnalyzeGlobal(I, GS, PHIUsers)) return true;
215
216         // If the first two indices are constants, this can be SRA'd.
217         if (isa<GlobalVariable>(I->getOperand(0))) {
218           if (I->getNumOperands() < 3 || !isa<Constant>(I->getOperand(1)) ||
219               !cast<Constant>(I->getOperand(1))->isNullValue() ||
220               !isa<ConstantInt>(I->getOperand(2)))
221             GS.isNotSuitableForSRA = true;
222         } else if (ConstantExpr *CE = dyn_cast<ConstantExpr>(I->getOperand(0))){
223           if (CE->getOpcode() != Instruction::GetElementPtr ||
224               CE->getNumOperands() < 3 || I->getNumOperands() < 2 ||
225               !isa<Constant>(I->getOperand(0)) ||
226               !cast<Constant>(I->getOperand(0))->isNullValue())
227             GS.isNotSuitableForSRA = true;
228         } else {
229           GS.isNotSuitableForSRA = true;
230         }
231       } else if (isa<SelectInst>(I)) {
232         if (AnalyzeGlobal(I, GS, PHIUsers)) return true;
233         GS.isNotSuitableForSRA = true;
234       } else if (PHINode *PN = dyn_cast<PHINode>(I)) {
235         // PHI nodes we can check just like select or GEP instructions, but we
236         // have to be careful about infinite recursion.
237         if (PHIUsers.insert(PN).second)  // Not already visited.
238           if (AnalyzeGlobal(I, GS, PHIUsers)) return true;
239         GS.isNotSuitableForSRA = true;
240       } else if (isa<SetCondInst>(I)) {
241         GS.isNotSuitableForSRA = true;
242       } else if (isa<MemCpyInst>(I) || isa<MemMoveInst>(I)) {
243         if (I->getOperand(1) == V)
244           GS.StoredType = GlobalStatus::isStored;
245         if (I->getOperand(2) == V)
246           GS.isLoaded = true;
247         GS.isNotSuitableForSRA = true;
248       } else if (isa<MemSetInst>(I)) {
249         assert(I->getOperand(1) == V && "Memset only takes one pointer!");
250         GS.StoredType = GlobalStatus::isStored;
251         GS.isNotSuitableForSRA = true;
252       } else {
253         return true;  // Any other non-load instruction might take address!
254       }
255     } else if (Constant *C = dyn_cast<Constant>(*UI)) {
256       GS.HasNonInstructionUser = true;
257       // We might have a dead and dangling constant hanging off of here.
258       if (!ConstantIsDead(C))
259         return true;
260     } else {
261       GS.HasNonInstructionUser = true;
262       // Otherwise must be some other user.
263       return true;
264     }
265
266   return false;
267 }
268
269 static Constant *getAggregateConstantElement(Constant *Agg, Constant *Idx) {
270   ConstantInt *CI = dyn_cast<ConstantInt>(Idx);
271   if (!CI) return 0;
272   unsigned IdxV = (unsigned)CI->getRawValue();
273
274   if (ConstantStruct *CS = dyn_cast<ConstantStruct>(Agg)) {
275     if (IdxV < CS->getNumOperands()) return CS->getOperand(IdxV);
276   } else if (ConstantArray *CA = dyn_cast<ConstantArray>(Agg)) {
277     if (IdxV < CA->getNumOperands()) return CA->getOperand(IdxV);
278   } else if (ConstantPacked *CP = dyn_cast<ConstantPacked>(Agg)) {
279     if (IdxV < CP->getNumOperands()) return CP->getOperand(IdxV);
280   } else if (isa<ConstantAggregateZero>(Agg)) {
281     if (const StructType *STy = dyn_cast<StructType>(Agg->getType())) {
282       if (IdxV < STy->getNumElements())
283         return Constant::getNullValue(STy->getElementType(IdxV));
284     } else if (const SequentialType *STy =
285                dyn_cast<SequentialType>(Agg->getType())) {
286       return Constant::getNullValue(STy->getElementType());
287     }
288   } else if (isa<UndefValue>(Agg)) {
289     if (const StructType *STy = dyn_cast<StructType>(Agg->getType())) {
290       if (IdxV < STy->getNumElements())
291         return UndefValue::get(STy->getElementType(IdxV));
292     } else if (const SequentialType *STy =
293                dyn_cast<SequentialType>(Agg->getType())) {
294       return UndefValue::get(STy->getElementType());
295     }
296   }
297   return 0;
298 }
299
300 static Constant *TraverseGEPInitializer(User *GEP, Constant *Init) {
301   if (Init == 0) return 0;
302   if (GEP->getNumOperands() == 1 ||
303       !isa<Constant>(GEP->getOperand(1)) ||
304       !cast<Constant>(GEP->getOperand(1))->isNullValue())
305     return 0;
306
307   for (unsigned i = 2, e = GEP->getNumOperands(); i != e; ++i) {
308     ConstantInt *Idx = dyn_cast<ConstantInt>(GEP->getOperand(i));
309     if (!Idx) return 0;
310     Init = getAggregateConstantElement(Init, Idx);
311     if (Init == 0) return 0;
312   }
313   return Init;
314 }
315
316 /// CleanupConstantGlobalUsers - We just marked GV constant.  Loop over all
317 /// users of the global, cleaning up the obvious ones.  This is largely just a
318 /// quick scan over the use list to clean up the easy and obvious cruft.  This
319 /// returns true if it made a change.
320 static bool CleanupConstantGlobalUsers(Value *V, Constant *Init) {
321   bool Changed = false;
322   for (Value::use_iterator UI = V->use_begin(), E = V->use_end(); UI != E;) {
323     User *U = *UI++;
324
325     if (LoadInst *LI = dyn_cast<LoadInst>(U)) {
326       if (Init) {
327         // Replace the load with the initializer.
328         LI->replaceAllUsesWith(Init);
329         LI->eraseFromParent();
330         Changed = true;
331       }
332     } else if (StoreInst *SI = dyn_cast<StoreInst>(U)) {
333       // Store must be unreachable or storing Init into the global.
334       SI->eraseFromParent();
335       Changed = true;
336     } else if (ConstantExpr *CE = dyn_cast<ConstantExpr>(U)) {
337       if (CE->getOpcode() == Instruction::GetElementPtr) {
338         Constant *SubInit = TraverseGEPInitializer(CE, Init);
339         Changed |= CleanupConstantGlobalUsers(CE, SubInit);
340       } else if (CE->getOpcode() == Instruction::Cast &&
341                  isa<PointerType>(CE->getType())) {
342         // Pointer cast, delete any stores and memsets to the global.
343         Changed |= CleanupConstantGlobalUsers(CE, 0);
344       }
345
346       if (CE->use_empty()) {
347         CE->destroyConstant();
348         Changed = true;
349       }
350     } else if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(U)) {
351       Constant *SubInit = TraverseGEPInitializer(GEP, Init);
352       Changed |= CleanupConstantGlobalUsers(GEP, SubInit);
353
354       if (GEP->use_empty()) {
355         GEP->eraseFromParent();
356         Changed = true;
357       }
358     } else if (MemIntrinsic *MI = dyn_cast<MemIntrinsic>(U)) { // memset/cpy/mv
359       if (MI->getRawDest() == V) {
360         MI->eraseFromParent();
361         Changed = true;
362       }
363
364     } else if (Constant *C = dyn_cast<Constant>(U)) {
365       // If we have a chain of dead constantexprs or other things dangling from
366       // us, and if they are all dead, nuke them without remorse.
367       if (ConstantIsDead(C)) {
368         C->destroyConstant();
369         // This could have invalidated UI, start over from scratch.
370         CleanupConstantGlobalUsers(V, Init);
371         return true;
372       }
373     }
374   }
375   return Changed;
376 }
377
378 /// SRAGlobal - Perform scalar replacement of aggregates on the specified global
379 /// variable.  This opens the door for other optimizations by exposing the
380 /// behavior of the program in a more fine-grained way.  We have determined that
381 /// this transformation is safe already.  We return the first global variable we
382 /// insert so that the caller can reprocess it.
383 static GlobalVariable *SRAGlobal(GlobalVariable *GV) {
384   assert(GV->hasInternalLinkage() && !GV->isConstant());
385   Constant *Init = GV->getInitializer();
386   const Type *Ty = Init->getType();
387
388   std::vector<GlobalVariable*> NewGlobals;
389   Module::GlobalListType &Globals = GV->getParent()->getGlobalList();
390
391   if (const StructType *STy = dyn_cast<StructType>(Ty)) {
392     NewGlobals.reserve(STy->getNumElements());
393     for (unsigned i = 0, e = STy->getNumElements(); i != e; ++i) {
394       Constant *In = getAggregateConstantElement(Init,
395                                             ConstantUInt::get(Type::UIntTy, i));
396       assert(In && "Couldn't get element of initializer?");
397       GlobalVariable *NGV = new GlobalVariable(STy->getElementType(i), false,
398                                                GlobalVariable::InternalLinkage,
399                                                In, GV->getName()+"."+utostr(i));
400       Globals.insert(GV, NGV);
401       NewGlobals.push_back(NGV);
402     }
403   } else if (const SequentialType *STy = dyn_cast<SequentialType>(Ty)) {
404     unsigned NumElements = 0;
405     if (const ArrayType *ATy = dyn_cast<ArrayType>(STy))
406       NumElements = ATy->getNumElements();
407     else if (const PackedType *PTy = dyn_cast<PackedType>(STy))
408       NumElements = PTy->getNumElements();
409     else
410       assert(0 && "Unknown aggregate sequential type!");
411
412     if (NumElements > 16 && GV->hasNUsesOrMore(16))
413       return 0; // It's not worth it.
414     NewGlobals.reserve(NumElements);
415     for (unsigned i = 0, e = NumElements; i != e; ++i) {
416       Constant *In = getAggregateConstantElement(Init,
417                                             ConstantUInt::get(Type::UIntTy, i));
418       assert(In && "Couldn't get element of initializer?");
419
420       GlobalVariable *NGV = new GlobalVariable(STy->getElementType(), false,
421                                                GlobalVariable::InternalLinkage,
422                                                In, GV->getName()+"."+utostr(i));
423       Globals.insert(GV, NGV);
424       NewGlobals.push_back(NGV);
425     }
426   }
427
428   if (NewGlobals.empty())
429     return 0;
430
431   DEBUG(std::cerr << "PERFORMING GLOBAL SRA ON: " << *GV);
432
433   Constant *NullInt = Constant::getNullValue(Type::IntTy);
434
435   // Loop over all of the uses of the global, replacing the constantexpr geps,
436   // with smaller constantexpr geps or direct references.
437   while (!GV->use_empty()) {
438     User *GEP = GV->use_back();
439     assert(((isa<ConstantExpr>(GEP) &&
440              cast<ConstantExpr>(GEP)->getOpcode()==Instruction::GetElementPtr)||
441             isa<GetElementPtrInst>(GEP)) && "NonGEP CE's are not SRAable!");
442
443     // Ignore the 1th operand, which has to be zero or else the program is quite
444     // broken (undefined).  Get the 2nd operand, which is the structure or array
445     // index.
446     unsigned Val =
447        (unsigned)cast<ConstantInt>(GEP->getOperand(2))->getRawValue();
448     if (Val >= NewGlobals.size()) Val = 0; // Out of bound array access.
449
450     Value *NewPtr = NewGlobals[Val];
451
452     // Form a shorter GEP if needed.
453     if (GEP->getNumOperands() > 3)
454       if (ConstantExpr *CE = dyn_cast<ConstantExpr>(GEP)) {
455         std::vector<Constant*> Idxs;
456         Idxs.push_back(NullInt);
457         for (unsigned i = 3, e = CE->getNumOperands(); i != e; ++i)
458           Idxs.push_back(CE->getOperand(i));
459         NewPtr = ConstantExpr::getGetElementPtr(cast<Constant>(NewPtr), Idxs);
460       } else {
461         GetElementPtrInst *GEPI = cast<GetElementPtrInst>(GEP);
462         std::vector<Value*> Idxs;
463         Idxs.push_back(NullInt);
464         for (unsigned i = 3, e = GEPI->getNumOperands(); i != e; ++i)
465           Idxs.push_back(GEPI->getOperand(i));
466         NewPtr = new GetElementPtrInst(NewPtr, Idxs,
467                                        GEPI->getName()+"."+utostr(Val), GEPI);
468       }
469     GEP->replaceAllUsesWith(NewPtr);
470
471     if (GetElementPtrInst *GEPI = dyn_cast<GetElementPtrInst>(GEP))
472       GEPI->eraseFromParent();
473     else
474       cast<ConstantExpr>(GEP)->destroyConstant();
475   }
476
477   // Delete the old global, now that it is dead.
478   Globals.erase(GV);
479   ++NumSRA;
480
481   // Loop over the new globals array deleting any globals that are obviously
482   // dead.  This can arise due to scalarization of a structure or an array that
483   // has elements that are dead.
484   unsigned FirstGlobal = 0;
485   for (unsigned i = 0, e = NewGlobals.size(); i != e; ++i)
486     if (NewGlobals[i]->use_empty()) {
487       Globals.erase(NewGlobals[i]);
488       if (FirstGlobal == i) ++FirstGlobal;
489     }
490
491   return FirstGlobal != NewGlobals.size() ? NewGlobals[FirstGlobal] : 0;
492 }
493
494 /// AllUsesOfValueWillTrapIfNull - Return true if all users of the specified
495 /// value will trap if the value is dynamically null.
496 static bool AllUsesOfValueWillTrapIfNull(Value *V) {
497   for (Value::use_iterator UI = V->use_begin(), E = V->use_end(); UI != E; ++UI)
498     if (isa<LoadInst>(*UI)) {
499       // Will trap.
500     } else if (StoreInst *SI = dyn_cast<StoreInst>(*UI)) {
501       if (SI->getOperand(0) == V) {
502         //std::cerr << "NONTRAPPING USE: " << **UI;
503         return false;  // Storing the value.
504       }
505     } else if (CallInst *CI = dyn_cast<CallInst>(*UI)) {
506       if (CI->getOperand(0) != V) {
507         //std::cerr << "NONTRAPPING USE: " << **UI;
508         return false;  // Not calling the ptr
509       }
510     } else if (InvokeInst *II = dyn_cast<InvokeInst>(*UI)) {
511       if (II->getOperand(0) != V) {
512         //std::cerr << "NONTRAPPING USE: " << **UI;
513         return false;  // Not calling the ptr
514       }
515     } else if (CastInst *CI = dyn_cast<CastInst>(*UI)) {
516       if (!AllUsesOfValueWillTrapIfNull(CI)) return false;
517     } else if (GetElementPtrInst *GEPI = dyn_cast<GetElementPtrInst>(*UI)) {
518       if (!AllUsesOfValueWillTrapIfNull(GEPI)) return false;
519     } else if (isa<SetCondInst>(*UI) &&
520                isa<ConstantPointerNull>(UI->getOperand(1))) {
521       // Ignore setcc X, null
522     } else {
523       //std::cerr << "NONTRAPPING USE: " << **UI;
524       return false;
525     }
526   return true;
527 }
528
529 /// AllUsesOfLoadedValueWillTrapIfNull - Return true if all uses of any loads
530 /// from GV will trap if the loaded value is null.  Note that this also permits
531 /// comparisons of the loaded value against null, as a special case.
532 static bool AllUsesOfLoadedValueWillTrapIfNull(GlobalVariable *GV) {
533   for (Value::use_iterator UI = GV->use_begin(), E = GV->use_end(); UI!=E; ++UI)
534     if (LoadInst *LI = dyn_cast<LoadInst>(*UI)) {
535       if (!AllUsesOfValueWillTrapIfNull(LI))
536         return false;
537     } else if (isa<StoreInst>(*UI)) {
538       // Ignore stores to the global.
539     } else {
540       // We don't know or understand this user, bail out.
541       //std::cerr << "UNKNOWN USER OF GLOBAL!: " << **UI;
542       return false;
543     }
544
545   return true;
546 }
547
548 static bool OptimizeAwayTrappingUsesOfValue(Value *V, Constant *NewV) {
549   bool Changed = false;
550   for (Value::use_iterator UI = V->use_begin(), E = V->use_end(); UI != E; ) {
551     Instruction *I = cast<Instruction>(*UI++);
552     if (LoadInst *LI = dyn_cast<LoadInst>(I)) {
553       LI->setOperand(0, NewV);
554       Changed = true;
555     } else if (StoreInst *SI = dyn_cast<StoreInst>(I)) {
556       if (SI->getOperand(1) == V) {
557         SI->setOperand(1, NewV);
558         Changed = true;
559       }
560     } else if (isa<CallInst>(I) || isa<InvokeInst>(I)) {
561       if (I->getOperand(0) == V) {
562         // Calling through the pointer!  Turn into a direct call, but be careful
563         // that the pointer is not also being passed as an argument.
564         I->setOperand(0, NewV);
565         Changed = true;
566         bool PassedAsArg = false;
567         for (unsigned i = 1, e = I->getNumOperands(); i != e; ++i)
568           if (I->getOperand(i) == V) {
569             PassedAsArg = true;
570             I->setOperand(i, NewV);
571           }
572
573         if (PassedAsArg) {
574           // Being passed as an argument also.  Be careful to not invalidate UI!
575           UI = V->use_begin();
576         }
577       }
578     } else if (CastInst *CI = dyn_cast<CastInst>(I)) {
579       Changed |= OptimizeAwayTrappingUsesOfValue(CI,
580                                     ConstantExpr::getCast(NewV, CI->getType()));
581       if (CI->use_empty()) {
582         Changed = true;
583         CI->eraseFromParent();
584       }
585     } else if (GetElementPtrInst *GEPI = dyn_cast<GetElementPtrInst>(I)) {
586       // Should handle GEP here.
587       std::vector<Constant*> Indices;
588       Indices.reserve(GEPI->getNumOperands()-1);
589       for (unsigned i = 1, e = GEPI->getNumOperands(); i != e; ++i)
590         if (Constant *C = dyn_cast<Constant>(GEPI->getOperand(i)))
591           Indices.push_back(C);
592         else
593           break;
594       if (Indices.size() == GEPI->getNumOperands()-1)
595         Changed |= OptimizeAwayTrappingUsesOfValue(GEPI,
596                                 ConstantExpr::getGetElementPtr(NewV, Indices));
597       if (GEPI->use_empty()) {
598         Changed = true;
599         GEPI->eraseFromParent();
600       }
601     }
602   }
603
604   return Changed;
605 }
606
607
608 /// OptimizeAwayTrappingUsesOfLoads - The specified global has only one non-null
609 /// value stored into it.  If there are uses of the loaded value that would trap
610 /// if the loaded value is dynamically null, then we know that they cannot be
611 /// reachable with a null optimize away the load.
612 static bool OptimizeAwayTrappingUsesOfLoads(GlobalVariable *GV, Constant *LV) {
613   std::vector<LoadInst*> Loads;
614   bool Changed = false;
615
616   // Replace all uses of loads with uses of uses of the stored value.
617   for (Value::use_iterator GUI = GV->use_begin(), E = GV->use_end();
618        GUI != E; ++GUI)
619     if (LoadInst *LI = dyn_cast<LoadInst>(*GUI)) {
620       Loads.push_back(LI);
621       Changed |= OptimizeAwayTrappingUsesOfValue(LI, LV);
622     } else {
623       assert(isa<StoreInst>(*GUI) && "Only expect load and stores!");
624     }
625
626   if (Changed) {
627     DEBUG(std::cerr << "OPTIMIZED LOADS FROM STORED ONCE POINTER: " << *GV);
628     ++NumGlobUses;
629   }
630
631   // Delete all of the loads we can, keeping track of whether we nuked them all!
632   bool AllLoadsGone = true;
633   while (!Loads.empty()) {
634     LoadInst *L = Loads.back();
635     if (L->use_empty()) {
636       L->eraseFromParent();
637       Changed = true;
638     } else {
639       AllLoadsGone = false;
640     }
641     Loads.pop_back();
642   }
643
644   // If we nuked all of the loads, then none of the stores are needed either,
645   // nor is the global.
646   if (AllLoadsGone) {
647     DEBUG(std::cerr << "  *** GLOBAL NOW DEAD!\n");
648     CleanupConstantGlobalUsers(GV, 0);
649     if (GV->use_empty()) {
650       GV->eraseFromParent();
651       ++NumDeleted;
652     }
653     Changed = true;
654   }
655   return Changed;
656 }
657
658 /// ConstantPropUsersOf - Walk the use list of V, constant folding all of the
659 /// instructions that are foldable.
660 static void ConstantPropUsersOf(Value *V) {
661   for (Value::use_iterator UI = V->use_begin(), E = V->use_end(); UI != E; )
662     if (Instruction *I = dyn_cast<Instruction>(*UI++))
663       if (Constant *NewC = ConstantFoldInstruction(I)) {
664         I->replaceAllUsesWith(NewC);
665
666         // Advance UI to the next non-I use to avoid invalidating it!
667         // Instructions could multiply use V.
668         while (UI != E && *UI == I)
669           ++UI;
670         I->eraseFromParent();
671       }
672 }
673
674 /// OptimizeGlobalAddressOfMalloc - This function takes the specified global
675 /// variable, and transforms the program as if it always contained the result of
676 /// the specified malloc.  Because it is always the result of the specified
677 /// malloc, there is no reason to actually DO the malloc.  Instead, turn the
678 /// malloc into a global, and any laods of GV as uses of the new global.
679 static GlobalVariable *OptimizeGlobalAddressOfMalloc(GlobalVariable *GV,
680                                                      MallocInst *MI) {
681   DEBUG(std::cerr << "PROMOTING MALLOC GLOBAL: " << *GV << "  MALLOC = " <<*MI);
682   ConstantInt *NElements = cast<ConstantInt>(MI->getArraySize());
683
684   if (NElements->getRawValue() != 1) {
685     // If we have an array allocation, transform it to a single element
686     // allocation to make the code below simpler.
687     Type *NewTy = ArrayType::get(MI->getAllocatedType(),
688                                  (unsigned)NElements->getRawValue());
689     MallocInst *NewMI =
690       new MallocInst(NewTy, Constant::getNullValue(Type::UIntTy),
691                      MI->getName(), MI);
692     std::vector<Value*> Indices;
693     Indices.push_back(Constant::getNullValue(Type::IntTy));
694     Indices.push_back(Indices[0]);
695     Value *NewGEP = new GetElementPtrInst(NewMI, Indices,
696                                           NewMI->getName()+".el0", MI);
697     MI->replaceAllUsesWith(NewGEP);
698     MI->eraseFromParent();
699     MI = NewMI;
700   }
701
702   // Create the new global variable.  The contents of the malloc'd memory is
703   // undefined, so initialize with an undef value.
704   Constant *Init = UndefValue::get(MI->getAllocatedType());
705   GlobalVariable *NewGV = new GlobalVariable(MI->getAllocatedType(), false,
706                                              GlobalValue::InternalLinkage, Init,
707                                              GV->getName()+".body");
708   GV->getParent()->getGlobalList().insert(GV, NewGV);
709
710   // Anything that used the malloc now uses the global directly.
711   MI->replaceAllUsesWith(NewGV);
712
713   Constant *RepValue = NewGV;
714   if (NewGV->getType() != GV->getType()->getElementType())
715     RepValue = ConstantExpr::getCast(RepValue, GV->getType()->getElementType());
716
717   // If there is a comparison against null, we will insert a global bool to
718   // keep track of whether the global was initialized yet or not.
719   GlobalVariable *InitBool =
720     new GlobalVariable(Type::BoolTy, false, GlobalValue::InternalLinkage,
721                        ConstantBool::False, GV->getName()+".init");
722   bool InitBoolUsed = false;
723
724   // Loop over all uses of GV, processing them in turn.
725   std::vector<StoreInst*> Stores;
726   while (!GV->use_empty())
727     if (LoadInst *LI = dyn_cast<LoadInst>(GV->use_back())) {
728       while (!LI->use_empty()) {
729         Use &LoadUse = LI->use_begin().getUse();
730         if (!isa<SetCondInst>(LoadUse.getUser()))
731           LoadUse = RepValue;
732         else {
733           // Replace the setcc X, 0 with a use of the bool value.
734           SetCondInst *SCI = cast<SetCondInst>(LoadUse.getUser());
735           Value *LV = new LoadInst(InitBool, InitBool->getName()+".val", SCI);
736           InitBoolUsed = true;
737           switch (SCI->getOpcode()) {
738           default: assert(0 && "Unknown opcode!");
739           case Instruction::SetLT:
740             LV = ConstantBool::False;   // X < null -> always false
741             break;
742           case Instruction::SetEQ:
743           case Instruction::SetLE:
744             LV = BinaryOperator::createNot(LV, "notinit", SCI);
745             break;
746           case Instruction::SetNE:
747           case Instruction::SetGE:
748           case Instruction::SetGT:
749             break;  // no change.
750           }
751           SCI->replaceAllUsesWith(LV);
752           SCI->eraseFromParent();
753         }
754       }
755       LI->eraseFromParent();
756     } else {
757       StoreInst *SI = cast<StoreInst>(GV->use_back());
758       // The global is initialized when the store to it occurs.
759       new StoreInst(ConstantBool::True, InitBool, SI);
760       SI->eraseFromParent();
761     }
762
763   // If the initialization boolean was used, insert it, otherwise delete it.
764   if (!InitBoolUsed) {
765     while (!InitBool->use_empty())  // Delete initializations
766       cast<Instruction>(InitBool->use_back())->eraseFromParent();
767     delete InitBool;
768   } else
769     GV->getParent()->getGlobalList().insert(GV, InitBool);
770
771
772   // Now the GV is dead, nuke it and the malloc.
773   GV->eraseFromParent();
774   MI->eraseFromParent();
775
776   // To further other optimizations, loop over all users of NewGV and try to
777   // constant prop them.  This will promote GEP instructions with constant
778   // indices into GEP constant-exprs, which will allow global-opt to hack on it.
779   ConstantPropUsersOf(NewGV);
780   if (RepValue != NewGV)
781     ConstantPropUsersOf(RepValue);
782
783   return NewGV;
784 }
785
786 /// ValueIsOnlyUsedLocallyOrStoredToOneGlobal - Scan the use-list of V checking
787 /// to make sure that there are no complex uses of V.  We permit simple things
788 /// like dereferencing the pointer, but not storing through the address, unless
789 /// it is to the specified global.
790 static bool ValueIsOnlyUsedLocallyOrStoredToOneGlobal(Instruction *V,
791                                                       GlobalVariable *GV) {
792   for (Value::use_iterator UI = V->use_begin(), E = V->use_end(); UI != E;++UI)
793     if (isa<LoadInst>(*UI) || isa<SetCondInst>(*UI)) {
794       // Fine, ignore.
795     } else if (StoreInst *SI = dyn_cast<StoreInst>(*UI)) {
796       if (SI->getOperand(0) == V && SI->getOperand(1) != GV)
797         return false;  // Storing the pointer itself... bad.
798       // Otherwise, storing through it, or storing into GV... fine.
799     } else if (isa<GetElementPtrInst>(*UI) || isa<SelectInst>(*UI)) {
800       if (!ValueIsOnlyUsedLocallyOrStoredToOneGlobal(cast<Instruction>(*UI),GV))
801         return false;
802     } else {
803       return false;
804     }
805   return true;
806
807 }
808
809 // OptimizeOnceStoredGlobal - Try to optimize globals based on the knowledge
810 // that only one value (besides its initializer) is ever stored to the global.
811 static bool OptimizeOnceStoredGlobal(GlobalVariable *GV, Value *StoredOnceVal,
812                                      Module::global_iterator &GVI, TargetData &TD) {
813   if (CastInst *CI = dyn_cast<CastInst>(StoredOnceVal))
814     StoredOnceVal = CI->getOperand(0);
815   else if (GetElementPtrInst *GEPI =dyn_cast<GetElementPtrInst>(StoredOnceVal)){
816     // "getelementptr Ptr, 0, 0, 0" is really just a cast.
817     bool IsJustACast = true;
818     for (unsigned i = 1, e = GEPI->getNumOperands(); i != e; ++i)
819       if (!isa<Constant>(GEPI->getOperand(i)) ||
820           !cast<Constant>(GEPI->getOperand(i))->isNullValue()) {
821         IsJustACast = false;
822         break;
823       }
824     if (IsJustACast)
825       StoredOnceVal = GEPI->getOperand(0);
826   }
827
828   // If we are dealing with a pointer global that is initialized to null and
829   // only has one (non-null) value stored into it, then we can optimize any
830   // users of the loaded value (often calls and loads) that would trap if the
831   // value was null.
832   if (isa<PointerType>(GV->getInitializer()->getType()) &&
833       GV->getInitializer()->isNullValue()) {
834     if (Constant *SOVC = dyn_cast<Constant>(StoredOnceVal)) {
835       if (GV->getInitializer()->getType() != SOVC->getType())
836         SOVC = ConstantExpr::getCast(SOVC, GV->getInitializer()->getType());
837
838       // Optimize away any trapping uses of the loaded value.
839       if (OptimizeAwayTrappingUsesOfLoads(GV, SOVC))
840         return true;
841     } else if (MallocInst *MI = dyn_cast<MallocInst>(StoredOnceVal)) {
842       // If we have a global that is only initialized with a fixed size malloc,
843       // and if all users of the malloc trap, and if the malloc'd address is not
844       // put anywhere else, transform the program to use global memory instead
845       // of malloc'd memory.  This eliminates dynamic allocation (good) and
846       // exposes the resultant global to further GlobalOpt (even better).  Note
847       // that we restrict this transformation to only working on small
848       // allocations (2048 bytes currently), as we don't want to introduce a 16M
849       // global or something.
850       if (ConstantInt *NElements = dyn_cast<ConstantInt>(MI->getArraySize()))
851         if (MI->getAllocatedType()->isSized() &&
852             NElements->getRawValue()*
853                      TD.getTypeSize(MI->getAllocatedType()) < 2048 &&
854             AllUsesOfLoadedValueWillTrapIfNull(GV) &&
855             ValueIsOnlyUsedLocallyOrStoredToOneGlobal(MI, GV)) {
856           GVI = OptimizeGlobalAddressOfMalloc(GV, MI);
857           return true;
858         }
859     }
860   }
861
862   return false;
863 }
864
865 /// ShrinkGlobalToBoolean - At this point, we have learned that the only two
866 /// values ever stored into GV are its initializer and OtherVal.
867 static void ShrinkGlobalToBoolean(GlobalVariable *GV, Constant *OtherVal) {
868   // Create the new global, initializing it to false.
869   GlobalVariable *NewGV = new GlobalVariable(Type::BoolTy, false,
870          GlobalValue::InternalLinkage, ConstantBool::False, GV->getName()+".b");
871   GV->getParent()->getGlobalList().insert(GV, NewGV);
872
873   Constant *InitVal = GV->getInitializer();
874   assert(InitVal->getType() != Type::BoolTy && "No reason to shrink to bool!");
875
876   // If initialized to zero and storing one into the global, we can use a cast
877   // instead of a select to synthesize the desired value.
878   bool IsOneZero = false;
879   if (ConstantInt *CI = dyn_cast<ConstantInt>(OtherVal))
880     IsOneZero = InitVal->isNullValue() && CI->equalsInt(1);
881
882   while (!GV->use_empty()) {
883     Instruction *UI = cast<Instruction>(GV->use_back());
884     if (StoreInst *SI = dyn_cast<StoreInst>(UI)) {
885       // Change the store into a boolean store.
886       bool StoringOther = SI->getOperand(0) == OtherVal;
887       // Only do this if we weren't storing a loaded value.
888       Value *StoreVal;
889       if (StoringOther || SI->getOperand(0) == InitVal)
890         StoreVal = ConstantBool::get(StoringOther);
891       else {
892         // Otherwise, we are storing a previously loaded copy.  To do this,
893         // change the copy from copying the original value to just copying the
894         // bool.
895         Instruction *StoredVal = cast<Instruction>(SI->getOperand(0));
896
897         // If we're already replaced the input, StoredVal will be a cast or
898         // select instruction.  If not, it will be a load of the original
899         // global.
900         if (LoadInst *LI = dyn_cast<LoadInst>(StoredVal)) {
901           assert(LI->getOperand(0) == GV && "Not a copy!");
902           // Insert a new load, to preserve the saved value.
903           StoreVal = new LoadInst(NewGV, LI->getName()+".b", LI);
904         } else {
905           assert((isa<CastInst>(StoredVal) || isa<SelectInst>(StoredVal)) &&
906                  "This is not a form that we understand!");
907           StoreVal = StoredVal->getOperand(0);
908           assert(isa<LoadInst>(StoreVal) && "Not a load of NewGV!");
909         }
910       }
911       new StoreInst(StoreVal, NewGV, SI);
912     } else if (!UI->use_empty()) {
913       // Change the load into a load of bool then a select.
914       LoadInst *LI = cast<LoadInst>(UI);
915
916       std::string Name = LI->getName(); LI->setName("");
917       LoadInst *NLI = new LoadInst(NewGV, Name+".b", LI);
918       Value *NSI;
919       if (IsOneZero)
920         NSI = new CastInst(NLI, LI->getType(), Name, LI);
921       else
922         NSI = new SelectInst(NLI, OtherVal, InitVal, Name, LI);
923       LI->replaceAllUsesWith(NSI);
924     }
925     UI->eraseFromParent();
926   }
927
928   GV->eraseFromParent();
929 }
930
931
932 /// ProcessInternalGlobal - Analyze the specified global variable and optimize
933 /// it if possible.  If we make a change, return true.
934 bool GlobalOpt::ProcessInternalGlobal(GlobalVariable *GV,
935                                       Module::global_iterator &GVI) {
936   std::set<PHINode*> PHIUsers;
937   GlobalStatus GS;
938   PHIUsers.clear();
939   GV->removeDeadConstantUsers();
940
941   if (GV->use_empty()) {
942     DEBUG(std::cerr << "GLOBAL DEAD: " << *GV);
943     GV->eraseFromParent();
944     ++NumDeleted;
945     return true;
946   }
947
948   if (!AnalyzeGlobal(GV, GS, PHIUsers)) {
949     // If this is a first class global and has only one accessing function
950     // and this function is main (which we know is not recursive we can make
951     // this global a local variable) we replace the global with a local alloca
952     // in this function.
953     //
954     // NOTE: It doesn't make sense to promote non first class types since we
955     // are just replacing static memory to stack memory.
956     if (!GS.HasMultipleAccessingFunctions &&
957         GS.AccessingFunction && !GS.HasNonInstructionUser &&
958         GV->getType()->getElementType()->isFirstClassType() &&
959         GS.AccessingFunction->getName() == "main" &&
960         GS.AccessingFunction->hasExternalLinkage()) {
961       DEBUG(std::cerr << "LOCALIZING GLOBAL: " << *GV);
962       Instruction* FirstI = GS.AccessingFunction->getEntryBlock().begin();
963       const Type* ElemTy = GV->getType()->getElementType();
964       AllocaInst* Alloca = new AllocaInst(ElemTy, NULL, GV->getName(), FirstI);
965       if (!isa<UndefValue>(GV->getInitializer()))
966         new StoreInst(GV->getInitializer(), Alloca, FirstI);
967
968       GV->replaceAllUsesWith(Alloca);
969       GV->eraseFromParent();
970       ++NumLocalized;
971       return true;
972     }
973     // If the global is never loaded (but may be stored to), it is dead.
974     // Delete it now.
975     if (!GS.isLoaded) {
976       DEBUG(std::cerr << "GLOBAL NEVER LOADED: " << *GV);
977
978       // Delete any stores we can find to the global.  We may not be able to
979       // make it completely dead though.
980       bool Changed = CleanupConstantGlobalUsers(GV, GV->getInitializer());
981
982       // If the global is dead now, delete it.
983       if (GV->use_empty()) {
984         GV->eraseFromParent();
985         ++NumDeleted;
986         Changed = true;
987       }
988       return Changed;
989
990     } else if (GS.StoredType <= GlobalStatus::isInitializerStored) {
991       DEBUG(std::cerr << "MARKING CONSTANT: " << *GV);
992       GV->setConstant(true);
993
994       // Clean up any obviously simplifiable users now.
995       CleanupConstantGlobalUsers(GV, GV->getInitializer());
996
997       // If the global is dead now, just nuke it.
998       if (GV->use_empty()) {
999         DEBUG(std::cerr << "   *** Marking constant allowed us to simplify "
1000               "all users and delete global!\n");
1001         GV->eraseFromParent();
1002         ++NumDeleted;
1003       }
1004
1005       ++NumMarked;
1006       return true;
1007     } else if (!GS.isNotSuitableForSRA &&
1008                !GV->getInitializer()->getType()->isFirstClassType()) {
1009       if (GlobalVariable *FirstNewGV = SRAGlobal(GV)) {
1010         GVI = FirstNewGV;  // Don't skip the newly produced globals!
1011         return true;
1012       }
1013     } else if (GS.StoredType == GlobalStatus::isStoredOnce) {
1014       // If the initial value for the global was an undef value, and if only
1015       // one other value was stored into it, we can just change the
1016       // initializer to be an undef value, then delete all stores to the
1017       // global.  This allows us to mark it constant.
1018       if (Constant *SOVConstant = dyn_cast<Constant>(GS.StoredOnceValue))
1019         if (isa<UndefValue>(GV->getInitializer())) {
1020           // Change the initial value here.
1021           GV->setInitializer(SOVConstant);
1022
1023           // Clean up any obviously simplifiable users now.
1024           CleanupConstantGlobalUsers(GV, GV->getInitializer());
1025
1026           if (GV->use_empty()) {
1027             DEBUG(std::cerr << "   *** Substituting initializer allowed us to "
1028                   "simplify all users and delete global!\n");
1029             GV->eraseFromParent();
1030             ++NumDeleted;
1031           } else {
1032             GVI = GV;
1033           }
1034           ++NumSubstitute;
1035           return true;
1036         }
1037
1038       // Try to optimize globals based on the knowledge that only one value
1039       // (besides its initializer) is ever stored to the global.
1040       if (OptimizeOnceStoredGlobal(GV, GS.StoredOnceValue, GVI,
1041                                    getAnalysis<TargetData>()))
1042         return true;
1043
1044       // Otherwise, if the global was not a boolean, we can shrink it to be a
1045       // boolean.
1046       if (Constant *SOVConstant = dyn_cast<Constant>(GS.StoredOnceValue))
1047         if (GV->getType()->getElementType() != Type::BoolTy &&
1048             !GV->getType()->getElementType()->isFloatingPoint()) {
1049           DEBUG(std::cerr << "   *** SHRINKING TO BOOL: " << *GV);
1050           ShrinkGlobalToBoolean(GV, SOVConstant);
1051           ++NumShrunkToBool;
1052           return true;
1053         }
1054     }
1055   }
1056   return false;
1057 }
1058
1059 /// OnlyCalledDirectly - Return true if the specified function is only called
1060 /// directly.  In other words, its address is never taken.
1061 static bool OnlyCalledDirectly(Function *F) {
1062   for (Value::use_iterator UI = F->use_begin(), E = F->use_end(); UI != E;++UI){
1063     Instruction *User = dyn_cast<Instruction>(*UI);
1064     if (!User) return false;
1065     if (!isa<CallInst>(User) && !isa<InvokeInst>(User)) return false;
1066
1067     // See if the function address is passed as an argument.
1068     for (unsigned i = 1, e = User->getNumOperands(); i != e; ++i)
1069       if (User->getOperand(i) == F) return false;
1070   }
1071   return true;
1072 }
1073
1074 /// ChangeCalleesToFastCall - Walk all of the direct calls of the specified
1075 /// function, changing them to FastCC.
1076 static void ChangeCalleesToFastCall(Function *F) {
1077   for (Value::use_iterator UI = F->use_begin(), E = F->use_end(); UI != E;++UI){
1078     Instruction *User = cast<Instruction>(*UI);
1079     if (CallInst *CI = dyn_cast<CallInst>(User))
1080       CI->setCallingConv(CallingConv::Fast);
1081     else
1082       cast<InvokeInst>(User)->setCallingConv(CallingConv::Fast);
1083   }
1084 }
1085
1086 bool GlobalOpt::OptimizeFunctions(Module &M) {
1087   bool Changed = false;
1088   // Optimize functions.
1089   for (Module::iterator FI = M.begin(), E = M.end(); FI != E; ) {
1090     Function *F = FI++;
1091     F->removeDeadConstantUsers();
1092     if (F->use_empty() && (F->hasInternalLinkage() ||
1093                            F->hasLinkOnceLinkage())) {
1094       M.getFunctionList().erase(F);
1095       Changed = true;
1096       ++NumFnDeleted;
1097     } else if (F->hasInternalLinkage() &&
1098                F->getCallingConv() == CallingConv::C &&  !F->isVarArg() &&
1099                OnlyCalledDirectly(F)) {
1100       // If this function has C calling conventions, is not a varargs
1101       // function, and is only called directly, promote it to use the Fast
1102       // calling convention.
1103       F->setCallingConv(CallingConv::Fast);
1104       ChangeCalleesToFastCall(F);
1105       ++NumFastCallFns;
1106       Changed = true;
1107     }
1108   }
1109   return Changed;
1110 }
1111
1112 bool GlobalOpt::OptimizeGlobalVars(Module &M) {
1113   bool Changed = false;
1114   for (Module::global_iterator GVI = M.global_begin(), E = M.global_end();
1115        GVI != E; ) {
1116     GlobalVariable *GV = GVI++;
1117     if (!GV->isConstant() && GV->hasInternalLinkage() &&
1118         GV->hasInitializer())
1119       Changed |= ProcessInternalGlobal(GV, GVI);
1120   }
1121   return Changed;
1122 }
1123
1124 /// FindGlobalCtors - Find the llvm.globalctors list, verifying that all
1125 /// initializers have an init priority of 65535.
1126 GlobalVariable *GlobalOpt::FindGlobalCtors(Module &M) {
1127   for (Module::giterator I = M.global_begin(), E = M.global_end(); I != E; ++I)
1128     if (I->getName() == "llvm.global_ctors") {
1129       // Found it, verify it's an array of { int, void()* }.
1130       const ArrayType *ATy =dyn_cast<ArrayType>(I->getType()->getElementType());
1131       if (!ATy) return 0;
1132       const StructType *STy = dyn_cast<StructType>(ATy->getElementType());
1133       if (!STy || STy->getNumElements() != 2 ||
1134           STy->getElementType(0) != Type::IntTy) return 0;
1135       const PointerType *PFTy = dyn_cast<PointerType>(STy->getElementType(1));
1136       if (!PFTy) return 0;
1137       const FunctionType *FTy = dyn_cast<FunctionType>(PFTy->getElementType());
1138       if (!FTy || FTy->getReturnType() != Type::VoidTy || FTy->isVarArg() ||
1139           FTy->getNumParams() != 0)
1140         return 0;
1141       
1142       // Verify that the initializer is simple enough for us to handle.
1143       if (!I->hasInitializer()) return 0;
1144       ConstantArray *CA = dyn_cast<ConstantArray>(I->getInitializer());
1145       if (!CA) return 0;
1146       for (unsigned i = 0, e = CA->getNumOperands(); i != e; ++i)
1147         if (ConstantStruct *CS = dyn_cast<ConstantStruct>(CA->getOperand(i))) {
1148           if (isa<ConstantPointerNull>(CS->getOperand(1)))
1149             continue;
1150
1151           // Must have a function or null ptr.
1152           if (!isa<Function>(CS->getOperand(1)))
1153             return 0;
1154           
1155           // Init priority must be standard.
1156           ConstantInt *CI = dyn_cast<ConstantInt>(CS->getOperand(0));
1157           if (!CI || CI->getRawValue() != 65535)
1158             return 0;
1159         } else {
1160           return 0;
1161         }
1162       
1163       return I;
1164     }
1165   return 0;
1166 }
1167
1168 /// ParseGlobalCtors - Given a llvm.global_ctors list that we can understand,
1169 /// return a list of the functions and null terminator as a vector.
1170 static std::vector<Function*> ParseGlobalCtors(GlobalVariable *GV) {
1171   ConstantArray *CA = cast<ConstantArray>(GV->getInitializer());
1172   std::vector<Function*> Result;
1173   Result.reserve(CA->getNumOperands());
1174   for (unsigned i = 0, e = CA->getNumOperands(); i != e; ++i) {
1175     ConstantStruct *CS = cast<ConstantStruct>(CA->getOperand(i));
1176     Result.push_back(dyn_cast<Function>(CS->getOperand(1)));
1177   }
1178   return Result;
1179 }
1180
1181 /// InstallGlobalCtors - Given a specified llvm.global_ctors list, install the
1182 /// specified array, returning the new global to use.
1183 static GlobalVariable *InstallGlobalCtors(GlobalVariable *GCL, 
1184                                           const std::vector<Function*> &Ctors) {
1185   // If we made a change, reassemble the initializer list.
1186   std::vector<Constant*> CSVals;
1187   CSVals.push_back(ConstantSInt::get(Type::IntTy, 65535));
1188   CSVals.push_back(0);
1189   
1190   // Create the new init list.
1191   std::vector<Constant*> CAList;
1192   for (unsigned i = 0, e = Ctors.size(); i != e; ++i) {
1193     if (Ctors[i]) {
1194       CSVals[1] = Ctors[i];
1195     } else {
1196       const Type *FTy = FunctionType::get(Type::VoidTy,
1197                                           std::vector<const Type*>(), false);
1198       const PointerType *PFTy = PointerType::get(FTy);
1199       CSVals[1] = Constant::getNullValue(PFTy);
1200       CSVals[0] = ConstantSInt::get(Type::IntTy, 2147483647);
1201     }
1202     CAList.push_back(ConstantStruct::get(CSVals));
1203   }
1204   
1205   // Create the array initializer.
1206   const Type *StructTy =
1207     cast<ArrayType>(GCL->getType()->getElementType())->getElementType();
1208   Constant *CA = ConstantArray::get(ArrayType::get(StructTy, CAList.size()),
1209                                     CAList);
1210   
1211   // If we didn't change the number of elements, don't create a new GV.
1212   if (CA->getType() == GCL->getInitializer()->getType()) {
1213     GCL->setInitializer(CA);
1214     return GCL;
1215   }
1216   
1217   // Create the new global and insert it next to the existing list.
1218   GlobalVariable *NGV = new GlobalVariable(CA->getType(), GCL->isConstant(),
1219                                            GCL->getLinkage(), CA,
1220                                            GCL->getName());
1221   GCL->setName("");
1222   GCL->getParent()->getGlobalList().insert(GCL, NGV);
1223   
1224   // Nuke the old list, replacing any uses with the new one.
1225   if (!GCL->use_empty()) {
1226     Constant *V = NGV;
1227     if (V->getType() != GCL->getType())
1228       V = ConstantExpr::getCast(V, GCL->getType());
1229     GCL->replaceAllUsesWith(V);
1230   }
1231   GCL->eraseFromParent();
1232   
1233   if (Ctors.size())
1234     return NGV;
1235   else
1236     return 0;
1237 }
1238
1239
1240 static Constant *getVal(std::map<Value*, Constant*> &ComputedValues,
1241                         Value *V) {
1242   if (Constant *CV = dyn_cast<Constant>(V)) return CV;
1243   Constant *R = ComputedValues[V];
1244   assert(R && "Reference to an uncomputed value!");
1245   return R;
1246 }
1247
1248 /// isSimpleEnoughPointerToCommit - Return true if this constant is simple
1249 /// enough for us to understand.  In particular, if it is a cast of something,
1250 /// we punt.  We basically just support direct accesses to globals and GEP's of
1251 /// globals.  This should be kept up to date with CommitValueTo.
1252 static bool isSimpleEnoughPointerToCommit(Constant *C) {
1253   if (GlobalVariable *GV = dyn_cast<GlobalVariable>(C))
1254     return !GV->isExternal();  // reject external globals.
1255   return false;
1256 }
1257
1258 /// CommitValueTo - We have decided that Addr (which satisfies the predicate
1259 /// isSimpleEnoughPointerToCommit) should get Val as its value.  Make it happen.
1260 static void CommitValueTo(Constant *Val, Constant *Addr) {
1261   GlobalVariable *GV = cast<GlobalVariable>(Addr);
1262   assert(GV->hasInitializer());
1263   GV->setInitializer(Val);
1264 }
1265
1266 /// EvaluateStaticConstructor - Evaluate static constructors in the function, if
1267 /// we can.  Return true if we can, false otherwise.
1268 static bool EvaluateStaticConstructor(Function *F) {
1269   /// Values - As we compute SSA register values, we store their contents here.
1270   std::map<Value*, Constant*> Values;
1271   
1272   /// MutatedMemory - For each store we execute, we update this map.  Loads
1273   /// check this to get the most up-to-date value.  If evaluation is successful,
1274   /// this state is committed to the process.
1275   std::map<Constant*, Constant*> MutatedMemory;
1276   
1277   // CurInst - The current instruction we're evaluating.
1278   BasicBlock::iterator CurInst = F->begin()->begin();
1279   
1280   // This is the main evaluation loop.
1281   while (1) {
1282     Constant *InstResult = 0;
1283     
1284     if (StoreInst *SI = dyn_cast<StoreInst>(CurInst)) {
1285       Constant *Ptr = getVal(Values, SI->getOperand(1));
1286       if (!isSimpleEnoughPointerToCommit(Ptr))
1287         // If this is too complex for us to commit, reject it.
1288         return false;
1289       Constant *Val = getVal(Values, SI->getOperand(0));
1290       MutatedMemory[Ptr] = Val;
1291     } else if (BinaryOperator *BO = dyn_cast<BinaryOperator>(CurInst)) {
1292       InstResult = ConstantExpr::get(BO->getOpcode(),
1293                                      getVal(Values, BO->getOperand(0)),
1294                                      getVal(Values, BO->getOperand(1)));
1295     } else if (ShiftInst *SI = dyn_cast<ShiftInst>(CurInst)) {
1296       InstResult = ConstantExpr::get(SI->getOpcode(),
1297                                      getVal(Values, SI->getOperand(0)),
1298                                      getVal(Values, SI->getOperand(1)));
1299     } else if (CastInst *CI = dyn_cast<CastInst>(CurInst)) {
1300       InstResult = ConstantExpr::getCast(getVal(Values, CI->getOperand(0)),
1301                                          CI->getType());
1302     } else if (SelectInst *SI = dyn_cast<SelectInst>(CurInst)) {
1303       InstResult = ConstantExpr::getSelect(getVal(Values, SI->getOperand(0)),
1304                                            getVal(Values, SI->getOperand(1)),
1305                                            getVal(Values, SI->getOperand(2)));
1306     } else if (ReturnInst *RI = dyn_cast<ReturnInst>(CurInst)) {
1307       assert(RI->getNumOperands() == 0);
1308       break;  // We succeeded at evaluating this ctor!
1309     } else {
1310       // TODO: use ConstantFoldCall for function calls.
1311       
1312       // Did not know how to evaluate this!
1313       return false;
1314     }
1315     
1316     if (!CurInst->use_empty())
1317       Values[CurInst] = InstResult;
1318     
1319     // Advance program counter.
1320     ++CurInst;
1321   }
1322   
1323   // If we get here, we know that we succeeded at evaluation: commit the result.
1324   //
1325   for (std::map<Constant*, Constant*>::iterator I = MutatedMemory.begin(),
1326        E = MutatedMemory.end(); I != E; ++I)
1327     CommitValueTo(I->second, I->first);
1328   return true;
1329 }
1330
1331
1332 /// OptimizeGlobalCtorsList - Simplify and evaluation global ctors if possible.
1333 /// Return true if anything changed.
1334 bool GlobalOpt::OptimizeGlobalCtorsList(GlobalVariable *&GCL) {
1335   std::vector<Function*> Ctors = ParseGlobalCtors(GCL);
1336   bool MadeChange = false;
1337   if (Ctors.empty()) return false;
1338   
1339   // Loop over global ctors, optimizing them when we can.
1340   for (unsigned i = 0; i != Ctors.size(); ++i) {
1341     Function *F = Ctors[i];
1342     // Found a null terminator in the middle of the list, prune off the rest of
1343     // the list.
1344     if (F == 0) {
1345       if (i != Ctors.size()-1) {
1346         Ctors.resize(i+1);
1347         MadeChange = true;
1348       }
1349       break;
1350     }
1351     
1352     // We cannot simplify external ctor functions.
1353     if (F->empty()) continue;
1354     
1355     // If we can evaluate the ctor at compile time, do.
1356     if (EvaluateStaticConstructor(F)) {
1357       Ctors.erase(Ctors.begin()+i);
1358       MadeChange = true;
1359       --i;
1360       ++NumCtorsEvaluated;
1361       continue;
1362     }
1363     
1364     // If the function is empty, just remove it from the ctor list.
1365     if (isa<ReturnInst>(F->begin()->getTerminator()) &&
1366         &F->begin()->front() == F->begin()->getTerminator()) {
1367       Ctors.erase(Ctors.begin()+i);
1368       MadeChange = true;
1369       --i;
1370       ++NumEmptyCtor;
1371       continue;
1372     }
1373   }
1374   
1375   if (!MadeChange) return false;
1376   
1377   GCL = InstallGlobalCtors(GCL, Ctors);
1378   return true;
1379 }
1380
1381
1382 bool GlobalOpt::runOnModule(Module &M) {
1383   bool Changed = false;
1384   
1385   // Try to find the llvm.globalctors list.
1386   GlobalVariable *GlobalCtors = FindGlobalCtors(M);
1387
1388   bool LocalChange = true;
1389   while (LocalChange) {
1390     LocalChange = false;
1391     
1392     // Delete functions that are trivially dead, ccc -> fastcc
1393     LocalChange |= OptimizeFunctions(M);
1394     
1395     // Optimize global_ctors list.
1396     if (GlobalCtors)
1397       LocalChange |= OptimizeGlobalCtorsList(GlobalCtors);
1398     
1399     // Optimize non-address-taken globals.
1400     LocalChange |= OptimizeGlobalVars(M);
1401     Changed |= LocalChange;
1402   }
1403   
1404   // TODO: Move all global ctors functions to the end of the module for code
1405   // layout.
1406   
1407   return Changed;
1408 }