Fix typo in comment.
[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/Analysis/ConstantFolding.h"
26 #include "llvm/Target/TargetData.h"
27 #include "llvm/Support/Compiler.h"
28 #include "llvm/Support/Debug.h"
29 #include "llvm/ADT/SmallVector.h"
30 #include "llvm/ADT/Statistic.h"
31 #include "llvm/ADT/StringExtras.h"
32 #include <algorithm>
33 #include <set>
34 using namespace llvm;
35
36 STATISTIC(NumMarked    , "Number of globals marked constant");
37 STATISTIC(NumSRA       , "Number of aggregate globals broken into scalars");
38 STATISTIC(NumHeapSRA   , "Number of heap objects SRA'd");
39 STATISTIC(NumSubstitute,"Number of globals with initializers stored into them");
40 STATISTIC(NumDeleted   , "Number of globals deleted");
41 STATISTIC(NumFnDeleted , "Number of functions deleted");
42 STATISTIC(NumGlobUses  , "Number of global uses devirtualized");
43 STATISTIC(NumLocalized , "Number of globals localized");
44 STATISTIC(NumShrunkToBool  , "Number of global vars shrunk to booleans");
45 STATISTIC(NumFastCallFns   , "Number of functions converted to fastcc");
46 STATISTIC(NumCtorsEvaluated, "Number of static ctors evaluated");
47
48 namespace {
49   struct VISIBILITY_HIDDEN GlobalOpt : public ModulePass {
50     virtual void getAnalysisUsage(AnalysisUsage &AU) const {
51       AU.addRequired<TargetData>();
52     }
53     static char ID; // Pass identification, replacement for typeid
54     GlobalOpt() : ModulePass((intptr_t)&ID) {}
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   char GlobalOpt::ID = 0;
67   RegisterPass<GlobalOpt> X("globalopt", "Global Variable Optimizer");
68 }
69
70 ModulePass *llvm::createGlobalOptimizerPass() { return new GlobalOpt(); }
71
72 /// GlobalStatus - As we analyze each global, keep track of some information
73 /// about it.  If we find out that the address of the global is taken, none of
74 /// this info will be accurate.
75 struct VISIBILITY_HIDDEN GlobalStatus {
76   /// isLoaded - True if the global is ever loaded.  If the global isn't ever
77   /// loaded it can be deleted.
78   bool isLoaded;
79
80   /// StoredType - Keep track of what stores to the global look like.
81   ///
82   enum StoredType {
83     /// NotStored - There is no store to this global.  It can thus be marked
84     /// constant.
85     NotStored,
86
87     /// isInitializerStored - This global is stored to, but the only thing
88     /// stored is the constant it was initialized with.  This is only tracked
89     /// for scalar globals.
90     isInitializerStored,
91
92     /// isStoredOnce - This global is stored to, but only its initializer and
93     /// one other value is ever stored to it.  If this global isStoredOnce, we
94     /// track the value stored to it in StoredOnceValue below.  This is only
95     /// tracked for scalar globals.
96     isStoredOnce,
97
98     /// isStored - This global is stored to by multiple values or something else
99     /// that we cannot track.
100     isStored
101   } StoredType;
102
103   /// StoredOnceValue - If only one value (besides the initializer constant) is
104   /// ever stored to this global, keep track of what value it is.
105   Value *StoredOnceValue;
106
107   /// AccessingFunction/HasMultipleAccessingFunctions - These start out
108   /// null/false.  When the first accessing function is noticed, it is recorded.
109   /// When a second different accessing function is noticed,
110   /// HasMultipleAccessingFunctions is set to true.
111   Function *AccessingFunction;
112   bool HasMultipleAccessingFunctions;
113
114   /// HasNonInstructionUser - Set to true if this global has a user that is not
115   /// an instruction (e.g. a constant expr or GV initializer).
116   bool HasNonInstructionUser;
117
118   /// HasPHIUser - Set to true if this global has a user that is a PHI node.
119   bool HasPHIUser;
120   
121   /// isNotSuitableForSRA - Keep track of whether any SRA preventing users of
122   /// the global exist.  Such users include GEP instruction with variable
123   /// indexes, and non-gep/load/store users like constant expr casts.
124   bool isNotSuitableForSRA;
125
126   GlobalStatus() : isLoaded(false), StoredType(NotStored), StoredOnceValue(0),
127                    AccessingFunction(0), HasMultipleAccessingFunctions(false),
128                    HasNonInstructionUser(false), HasPHIUser(false),
129                    isNotSuitableForSRA(false) {}
130 };
131
132
133
134 /// ConstantIsDead - Return true if the specified constant is (transitively)
135 /// dead.  The constant may be used by other constants (e.g. constant arrays and
136 /// constant exprs) as long as they are dead, but it cannot be used by anything
137 /// else.
138 static bool ConstantIsDead(Constant *C) {
139   if (isa<GlobalValue>(C)) return false;
140
141   for (Value::use_iterator UI = C->use_begin(), E = C->use_end(); UI != E; ++UI)
142     if (Constant *CU = dyn_cast<Constant>(*UI)) {
143       if (!ConstantIsDead(CU)) return false;
144     } else
145       return false;
146   return true;
147 }
148
149
150 /// AnalyzeGlobal - Look at all uses of the global and fill in the GlobalStatus
151 /// structure.  If the global has its address taken, return true to indicate we
152 /// can't do anything with it.
153 ///
154 static bool AnalyzeGlobal(Value *V, GlobalStatus &GS,
155                           std::set<PHINode*> &PHIUsers) {
156   for (Value::use_iterator UI = V->use_begin(), E = V->use_end(); UI != E; ++UI)
157     if (ConstantExpr *CE = dyn_cast<ConstantExpr>(*UI)) {
158       GS.HasNonInstructionUser = true;
159
160       if (AnalyzeGlobal(CE, GS, PHIUsers)) return true;
161       if (CE->getOpcode() != Instruction::GetElementPtr)
162         GS.isNotSuitableForSRA = true;
163       else if (!GS.isNotSuitableForSRA) {
164         // Check to see if this ConstantExpr GEP is SRA'able.  In particular, we
165         // don't like < 3 operand CE's, and we don't like non-constant integer
166         // indices.
167         if (CE->getNumOperands() < 3 || !CE->getOperand(1)->isNullValue())
168           GS.isNotSuitableForSRA = true;
169         else {
170           for (unsigned i = 1, e = CE->getNumOperands(); i != e; ++i)
171             if (!isa<ConstantInt>(CE->getOperand(i))) {
172               GS.isNotSuitableForSRA = true;
173               break;
174             }
175         }
176       }
177
178     } else if (Instruction *I = dyn_cast<Instruction>(*UI)) {
179       if (!GS.HasMultipleAccessingFunctions) {
180         Function *F = I->getParent()->getParent();
181         if (GS.AccessingFunction == 0)
182           GS.AccessingFunction = F;
183         else if (GS.AccessingFunction != F)
184           GS.HasMultipleAccessingFunctions = true;
185       }
186       if (isa<LoadInst>(I)) {
187         GS.isLoaded = true;
188       } else if (StoreInst *SI = dyn_cast<StoreInst>(I)) {
189         // Don't allow a store OF the address, only stores TO the address.
190         if (SI->getOperand(0) == V) return true;
191
192         // If this is a direct store to the global (i.e., the global is a scalar
193         // value, not an aggregate), keep more specific information about
194         // stores.
195         if (GS.StoredType != GlobalStatus::isStored)
196           if (GlobalVariable *GV = dyn_cast<GlobalVariable>(SI->getOperand(1))){
197             Value *StoredVal = SI->getOperand(0);
198             if (StoredVal == GV->getInitializer()) {
199               if (GS.StoredType < GlobalStatus::isInitializerStored)
200                 GS.StoredType = GlobalStatus::isInitializerStored;
201             } else if (isa<LoadInst>(StoredVal) &&
202                        cast<LoadInst>(StoredVal)->getOperand(0) == GV) {
203               // G = G
204               if (GS.StoredType < GlobalStatus::isInitializerStored)
205                 GS.StoredType = GlobalStatus::isInitializerStored;
206             } else if (GS.StoredType < GlobalStatus::isStoredOnce) {
207               GS.StoredType = GlobalStatus::isStoredOnce;
208               GS.StoredOnceValue = StoredVal;
209             } else if (GS.StoredType == GlobalStatus::isStoredOnce &&
210                        GS.StoredOnceValue == StoredVal) {
211               // noop.
212             } else {
213               GS.StoredType = GlobalStatus::isStored;
214             }
215           } else {
216             GS.StoredType = GlobalStatus::isStored;
217           }
218       } else if (isa<GetElementPtrInst>(I)) {
219         if (AnalyzeGlobal(I, GS, PHIUsers)) return true;
220
221         // If the first two indices are constants, this can be SRA'd.
222         if (isa<GlobalVariable>(I->getOperand(0))) {
223           if (I->getNumOperands() < 3 || !isa<Constant>(I->getOperand(1)) ||
224               !cast<Constant>(I->getOperand(1))->isNullValue() ||
225               !isa<ConstantInt>(I->getOperand(2)))
226             GS.isNotSuitableForSRA = true;
227         } else if (ConstantExpr *CE = dyn_cast<ConstantExpr>(I->getOperand(0))){
228           if (CE->getOpcode() != Instruction::GetElementPtr ||
229               CE->getNumOperands() < 3 || I->getNumOperands() < 2 ||
230               !isa<Constant>(I->getOperand(0)) ||
231               !cast<Constant>(I->getOperand(0))->isNullValue())
232             GS.isNotSuitableForSRA = true;
233         } else {
234           GS.isNotSuitableForSRA = true;
235         }
236       } else if (isa<SelectInst>(I)) {
237         if (AnalyzeGlobal(I, GS, PHIUsers)) return true;
238         GS.isNotSuitableForSRA = true;
239       } else if (PHINode *PN = dyn_cast<PHINode>(I)) {
240         // PHI nodes we can check just like select or GEP instructions, but we
241         // have to be careful about infinite recursion.
242         if (PHIUsers.insert(PN).second)  // Not already visited.
243           if (AnalyzeGlobal(I, GS, PHIUsers)) return true;
244         GS.isNotSuitableForSRA = true;
245         GS.HasPHIUser = true;
246       } else if (isa<CmpInst>(I)) {
247         GS.isNotSuitableForSRA = true;
248       } else if (isa<MemCpyInst>(I) || isa<MemMoveInst>(I)) {
249         if (I->getOperand(1) == V)
250           GS.StoredType = GlobalStatus::isStored;
251         if (I->getOperand(2) == V)
252           GS.isLoaded = true;
253         GS.isNotSuitableForSRA = true;
254       } else if (isa<MemSetInst>(I)) {
255         assert(I->getOperand(1) == V && "Memset only takes one pointer!");
256         GS.StoredType = GlobalStatus::isStored;
257         GS.isNotSuitableForSRA = true;
258       } else {
259         return true;  // Any other non-load instruction might take address!
260       }
261     } else if (Constant *C = dyn_cast<Constant>(*UI)) {
262       GS.HasNonInstructionUser = true;
263       // We might have a dead and dangling constant hanging off of here.
264       if (!ConstantIsDead(C))
265         return true;
266     } else {
267       GS.HasNonInstructionUser = true;
268       // Otherwise must be some other user.
269       return true;
270     }
271
272   return false;
273 }
274
275 static Constant *getAggregateConstantElement(Constant *Agg, Constant *Idx) {
276   ConstantInt *CI = dyn_cast<ConstantInt>(Idx);
277   if (!CI) return 0;
278   unsigned IdxV = CI->getZExtValue();
279
280   if (ConstantStruct *CS = dyn_cast<ConstantStruct>(Agg)) {
281     if (IdxV < CS->getNumOperands()) return CS->getOperand(IdxV);
282   } else if (ConstantArray *CA = dyn_cast<ConstantArray>(Agg)) {
283     if (IdxV < CA->getNumOperands()) return CA->getOperand(IdxV);
284   } else if (ConstantVector *CP = dyn_cast<ConstantVector>(Agg)) {
285     if (IdxV < CP->getNumOperands()) return CP->getOperand(IdxV);
286   } else if (isa<ConstantAggregateZero>(Agg)) {
287     if (const StructType *STy = dyn_cast<StructType>(Agg->getType())) {
288       if (IdxV < STy->getNumElements())
289         return Constant::getNullValue(STy->getElementType(IdxV));
290     } else if (const SequentialType *STy =
291                dyn_cast<SequentialType>(Agg->getType())) {
292       return Constant::getNullValue(STy->getElementType());
293     }
294   } else if (isa<UndefValue>(Agg)) {
295     if (const StructType *STy = dyn_cast<StructType>(Agg->getType())) {
296       if (IdxV < STy->getNumElements())
297         return UndefValue::get(STy->getElementType(IdxV));
298     } else if (const SequentialType *STy =
299                dyn_cast<SequentialType>(Agg->getType())) {
300       return UndefValue::get(STy->getElementType());
301     }
302   }
303   return 0;
304 }
305
306
307 /// CleanupConstantGlobalUsers - We just marked GV constant.  Loop over all
308 /// users of the global, cleaning up the obvious ones.  This is largely just a
309 /// quick scan over the use list to clean up the easy and obvious cruft.  This
310 /// returns true if it made a change.
311 static bool CleanupConstantGlobalUsers(Value *V, Constant *Init) {
312   bool Changed = false;
313   for (Value::use_iterator UI = V->use_begin(), E = V->use_end(); UI != E;) {
314     User *U = *UI++;
315
316     if (LoadInst *LI = dyn_cast<LoadInst>(U)) {
317       if (Init) {
318         // Replace the load with the initializer.
319         LI->replaceAllUsesWith(Init);
320         LI->eraseFromParent();
321         Changed = true;
322       }
323     } else if (StoreInst *SI = dyn_cast<StoreInst>(U)) {
324       // Store must be unreachable or storing Init into the global.
325       SI->eraseFromParent();
326       Changed = true;
327     } else if (ConstantExpr *CE = dyn_cast<ConstantExpr>(U)) {
328       if (CE->getOpcode() == Instruction::GetElementPtr) {
329         Constant *SubInit = 0;
330         if (Init)
331           SubInit = ConstantFoldLoadThroughGEPConstantExpr(Init, CE);
332         Changed |= CleanupConstantGlobalUsers(CE, SubInit);
333       } else if (CE->getOpcode() == Instruction::BitCast && 
334                  isa<PointerType>(CE->getType())) {
335         // Pointer cast, delete any stores and memsets to the global.
336         Changed |= CleanupConstantGlobalUsers(CE, 0);
337       }
338
339       if (CE->use_empty()) {
340         CE->destroyConstant();
341         Changed = true;
342       }
343     } else if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(U)) {
344       Constant *SubInit = 0;
345       ConstantExpr *CE = 
346         dyn_cast_or_null<ConstantExpr>(ConstantFoldInstruction(GEP));
347       if (Init && CE && CE->getOpcode() == Instruction::GetElementPtr)
348         SubInit = ConstantFoldLoadThroughGEPConstantExpr(Init, CE);
349       Changed |= CleanupConstantGlobalUsers(GEP, SubInit);
350
351       if (GEP->use_empty()) {
352         GEP->eraseFromParent();
353         Changed = true;
354       }
355     } else if (MemIntrinsic *MI = dyn_cast<MemIntrinsic>(U)) { // memset/cpy/mv
356       if (MI->getRawDest() == V) {
357         MI->eraseFromParent();
358         Changed = true;
359       }
360
361     } else if (Constant *C = dyn_cast<Constant>(U)) {
362       // If we have a chain of dead constantexprs or other things dangling from
363       // us, and if they are all dead, nuke them without remorse.
364       if (ConstantIsDead(C)) {
365         C->destroyConstant();
366         // This could have invalidated UI, start over from scratch.
367         CleanupConstantGlobalUsers(V, Init);
368         return true;
369       }
370     }
371   }
372   return Changed;
373 }
374
375 /// SRAGlobal - Perform scalar replacement of aggregates on the specified global
376 /// variable.  This opens the door for other optimizations by exposing the
377 /// behavior of the program in a more fine-grained way.  We have determined that
378 /// this transformation is safe already.  We return the first global variable we
379 /// insert so that the caller can reprocess it.
380 static GlobalVariable *SRAGlobal(GlobalVariable *GV) {
381   assert(GV->hasInternalLinkage() && !GV->isConstant());
382   Constant *Init = GV->getInitializer();
383   const Type *Ty = Init->getType();
384
385   std::vector<GlobalVariable*> NewGlobals;
386   Module::GlobalListType &Globals = GV->getParent()->getGlobalList();
387
388   if (const StructType *STy = dyn_cast<StructType>(Ty)) {
389     NewGlobals.reserve(STy->getNumElements());
390     for (unsigned i = 0, e = STy->getNumElements(); i != e; ++i) {
391       Constant *In = getAggregateConstantElement(Init,
392                                             ConstantInt::get(Type::Int32Ty, i));
393       assert(In && "Couldn't get element of initializer?");
394       GlobalVariable *NGV = new GlobalVariable(STy->getElementType(i), false,
395                                                GlobalVariable::InternalLinkage,
396                                                In, GV->getName()+"."+utostr(i),
397                                                (Module *)NULL,
398                                                GV->isThreadLocal());
399       Globals.insert(GV, NGV);
400       NewGlobals.push_back(NGV);
401     }
402   } else if (const SequentialType *STy = dyn_cast<SequentialType>(Ty)) {
403     unsigned NumElements = 0;
404     if (const ArrayType *ATy = dyn_cast<ArrayType>(STy))
405       NumElements = ATy->getNumElements();
406     else if (const VectorType *PTy = dyn_cast<VectorType>(STy))
407       NumElements = PTy->getNumElements();
408     else
409       assert(0 && "Unknown aggregate sequential type!");
410
411     if (NumElements > 16 && GV->hasNUsesOrMore(16))
412       return 0; // It's not worth it.
413     NewGlobals.reserve(NumElements);
414     for (unsigned i = 0, e = NumElements; i != e; ++i) {
415       Constant *In = getAggregateConstantElement(Init,
416                                             ConstantInt::get(Type::Int32Ty, i));
417       assert(In && "Couldn't get element of initializer?");
418
419       GlobalVariable *NGV = new GlobalVariable(STy->getElementType(), false,
420                                                GlobalVariable::InternalLinkage,
421                                                In, GV->getName()+"."+utostr(i),
422                                                (Module *)NULL,
423                                                GV->isThreadLocal());
424       Globals.insert(GV, NGV);
425       NewGlobals.push_back(NGV);
426     }
427   }
428
429   if (NewGlobals.empty())
430     return 0;
431
432   DOUT << "PERFORMING GLOBAL SRA ON: " << *GV;
433
434   Constant *NullInt = Constant::getNullValue(Type::Int32Ty);
435
436   // Loop over all of the uses of the global, replacing the constantexpr geps,
437   // with smaller constantexpr geps or direct references.
438   while (!GV->use_empty()) {
439     User *GEP = GV->use_back();
440     assert(((isa<ConstantExpr>(GEP) &&
441              cast<ConstantExpr>(GEP)->getOpcode()==Instruction::GetElementPtr)||
442             isa<GetElementPtrInst>(GEP)) && "NonGEP CE's are not SRAable!");
443
444     // Ignore the 1th operand, which has to be zero or else the program is quite
445     // broken (undefined).  Get the 2nd operand, which is the structure or array
446     // index.
447     unsigned Val = cast<ConstantInt>(GEP->getOperand(2))->getZExtValue();
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         SmallVector<Constant*, 8> 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),
460                                                 &Idxs[0], Idxs.size());
461       } else {
462         GetElementPtrInst *GEPI = cast<GetElementPtrInst>(GEP);
463         SmallVector<Value*, 8> Idxs;
464         Idxs.push_back(NullInt);
465         for (unsigned i = 3, e = GEPI->getNumOperands(); i != e; ++i)
466           Idxs.push_back(GEPI->getOperand(i));
467         NewPtr = new GetElementPtrInst(NewPtr, &Idxs[0], Idxs.size(),
468                                        GEPI->getName()+"."+utostr(Val), GEPI);
469       }
470     GEP->replaceAllUsesWith(NewPtr);
471
472     if (GetElementPtrInst *GEPI = dyn_cast<GetElementPtrInst>(GEP))
473       GEPI->eraseFromParent();
474     else
475       cast<ConstantExpr>(GEP)->destroyConstant();
476   }
477
478   // Delete the old global, now that it is dead.
479   Globals.erase(GV);
480   ++NumSRA;
481
482   // Loop over the new globals array deleting any globals that are obviously
483   // dead.  This can arise due to scalarization of a structure or an array that
484   // has elements that are dead.
485   unsigned FirstGlobal = 0;
486   for (unsigned i = 0, e = NewGlobals.size(); i != e; ++i)
487     if (NewGlobals[i]->use_empty()) {
488       Globals.erase(NewGlobals[i]);
489       if (FirstGlobal == i) ++FirstGlobal;
490     }
491
492   return FirstGlobal != NewGlobals.size() ? NewGlobals[FirstGlobal] : 0;
493 }
494
495 /// AllUsesOfValueWillTrapIfNull - Return true if all users of the specified
496 /// value will trap if the value is dynamically null.
497 static bool AllUsesOfValueWillTrapIfNull(Value *V) {
498   for (Value::use_iterator UI = V->use_begin(), E = V->use_end(); UI != E; ++UI)
499     if (isa<LoadInst>(*UI)) {
500       // Will trap.
501     } else if (StoreInst *SI = dyn_cast<StoreInst>(*UI)) {
502       if (SI->getOperand(0) == V) {
503         //cerr << "NONTRAPPING USE: " << **UI;
504         return false;  // Storing the value.
505       }
506     } else if (CallInst *CI = dyn_cast<CallInst>(*UI)) {
507       if (CI->getOperand(0) != V) {
508         //cerr << "NONTRAPPING USE: " << **UI;
509         return false;  // Not calling the ptr
510       }
511     } else if (InvokeInst *II = dyn_cast<InvokeInst>(*UI)) {
512       if (II->getOperand(0) != V) {
513         //cerr << "NONTRAPPING USE: " << **UI;
514         return false;  // Not calling the ptr
515       }
516     } else if (CastInst *CI = dyn_cast<CastInst>(*UI)) {
517       if (!AllUsesOfValueWillTrapIfNull(CI)) return false;
518     } else if (GetElementPtrInst *GEPI = dyn_cast<GetElementPtrInst>(*UI)) {
519       if (!AllUsesOfValueWillTrapIfNull(GEPI)) return false;
520     } else if (isa<ICmpInst>(*UI) &&
521                isa<ConstantPointerNull>(UI->getOperand(1))) {
522       // Ignore setcc X, null
523     } else {
524       //cerr << "NONTRAPPING USE: " << **UI;
525       return false;
526     }
527   return true;
528 }
529
530 /// AllUsesOfLoadedValueWillTrapIfNull - Return true if all uses of any loads
531 /// from GV will trap if the loaded value is null.  Note that this also permits
532 /// comparisons of the loaded value against null, as a special case.
533 static bool AllUsesOfLoadedValueWillTrapIfNull(GlobalVariable *GV) {
534   for (Value::use_iterator UI = GV->use_begin(), E = GV->use_end(); UI!=E; ++UI)
535     if (LoadInst *LI = dyn_cast<LoadInst>(*UI)) {
536       if (!AllUsesOfValueWillTrapIfNull(LI))
537         return false;
538     } else if (isa<StoreInst>(*UI)) {
539       // Ignore stores to the global.
540     } else {
541       // We don't know or understand this user, bail out.
542       //cerr << "UNKNOWN USER OF GLOBAL!: " << **UI;
543       return false;
544     }
545
546   return true;
547 }
548
549 static bool OptimizeAwayTrappingUsesOfValue(Value *V, Constant *NewV) {
550   bool Changed = false;
551   for (Value::use_iterator UI = V->use_begin(), E = V->use_end(); UI != E; ) {
552     Instruction *I = cast<Instruction>(*UI++);
553     if (LoadInst *LI = dyn_cast<LoadInst>(I)) {
554       LI->setOperand(0, NewV);
555       Changed = true;
556     } else if (StoreInst *SI = dyn_cast<StoreInst>(I)) {
557       if (SI->getOperand(1) == V) {
558         SI->setOperand(1, NewV);
559         Changed = true;
560       }
561     } else if (isa<CallInst>(I) || isa<InvokeInst>(I)) {
562       if (I->getOperand(0) == V) {
563         // Calling through the pointer!  Turn into a direct call, but be careful
564         // that the pointer is not also being passed as an argument.
565         I->setOperand(0, NewV);
566         Changed = true;
567         bool PassedAsArg = false;
568         for (unsigned i = 1, e = I->getNumOperands(); i != e; ++i)
569           if (I->getOperand(i) == V) {
570             PassedAsArg = true;
571             I->setOperand(i, NewV);
572           }
573
574         if (PassedAsArg) {
575           // Being passed as an argument also.  Be careful to not invalidate UI!
576           UI = V->use_begin();
577         }
578       }
579     } else if (CastInst *CI = dyn_cast<CastInst>(I)) {
580       Changed |= OptimizeAwayTrappingUsesOfValue(CI,
581                                 ConstantExpr::getCast(CI->getOpcode(),
582                                                       NewV, CI->getType()));
583       if (CI->use_empty()) {
584         Changed = true;
585         CI->eraseFromParent();
586       }
587     } else if (GetElementPtrInst *GEPI = dyn_cast<GetElementPtrInst>(I)) {
588       // Should handle GEP here.
589       SmallVector<Constant*, 8> Idxs;
590       Idxs.reserve(GEPI->getNumOperands()-1);
591       for (unsigned i = 1, e = GEPI->getNumOperands(); i != e; ++i)
592         if (Constant *C = dyn_cast<Constant>(GEPI->getOperand(i)))
593           Idxs.push_back(C);
594         else
595           break;
596       if (Idxs.size() == GEPI->getNumOperands()-1)
597         Changed |= OptimizeAwayTrappingUsesOfValue(GEPI,
598                                 ConstantExpr::getGetElementPtr(NewV, &Idxs[0],
599                                                                Idxs.size()));
600       if (GEPI->use_empty()) {
601         Changed = true;
602         GEPI->eraseFromParent();
603       }
604     }
605   }
606
607   return Changed;
608 }
609
610
611 /// OptimizeAwayTrappingUsesOfLoads - The specified global has only one non-null
612 /// value stored into it.  If there are uses of the loaded value that would trap
613 /// if the loaded value is dynamically null, then we know that they cannot be
614 /// reachable with a null optimize away the load.
615 static bool OptimizeAwayTrappingUsesOfLoads(GlobalVariable *GV, Constant *LV) {
616   std::vector<LoadInst*> Loads;
617   bool Changed = false;
618
619   // Replace all uses of loads with uses of uses of the stored value.
620   for (Value::use_iterator GUI = GV->use_begin(), E = GV->use_end();
621        GUI != E; ++GUI)
622     if (LoadInst *LI = dyn_cast<LoadInst>(*GUI)) {
623       Loads.push_back(LI);
624       Changed |= OptimizeAwayTrappingUsesOfValue(LI, LV);
625     } else {
626       assert(isa<StoreInst>(*GUI) && "Only expect load and stores!");
627     }
628
629   if (Changed) {
630     DOUT << "OPTIMIZED LOADS FROM STORED ONCE POINTER: " << *GV;
631     ++NumGlobUses;
632   }
633
634   // Delete all of the loads we can, keeping track of whether we nuked them all!
635   bool AllLoadsGone = true;
636   while (!Loads.empty()) {
637     LoadInst *L = Loads.back();
638     if (L->use_empty()) {
639       L->eraseFromParent();
640       Changed = true;
641     } else {
642       AllLoadsGone = false;
643     }
644     Loads.pop_back();
645   }
646
647   // If we nuked all of the loads, then none of the stores are needed either,
648   // nor is the global.
649   if (AllLoadsGone) {
650     DOUT << "  *** GLOBAL NOW DEAD!\n";
651     CleanupConstantGlobalUsers(GV, 0);
652     if (GV->use_empty()) {
653       GV->eraseFromParent();
654       ++NumDeleted;
655     }
656     Changed = true;
657   }
658   return Changed;
659 }
660
661 /// ConstantPropUsersOf - Walk the use list of V, constant folding all of the
662 /// instructions that are foldable.
663 static void ConstantPropUsersOf(Value *V) {
664   for (Value::use_iterator UI = V->use_begin(), E = V->use_end(); UI != E; )
665     if (Instruction *I = dyn_cast<Instruction>(*UI++))
666       if (Constant *NewC = ConstantFoldInstruction(I)) {
667         I->replaceAllUsesWith(NewC);
668
669         // Advance UI to the next non-I use to avoid invalidating it!
670         // Instructions could multiply use V.
671         while (UI != E && *UI == I)
672           ++UI;
673         I->eraseFromParent();
674       }
675 }
676
677 /// OptimizeGlobalAddressOfMalloc - This function takes the specified global
678 /// variable, and transforms the program as if it always contained the result of
679 /// the specified malloc.  Because it is always the result of the specified
680 /// malloc, there is no reason to actually DO the malloc.  Instead, turn the
681 /// malloc into a global, and any loads of GV as uses of the new global.
682 static GlobalVariable *OptimizeGlobalAddressOfMalloc(GlobalVariable *GV,
683                                                      MallocInst *MI) {
684   DOUT << "PROMOTING MALLOC GLOBAL: " << *GV << "  MALLOC = " << *MI;
685   ConstantInt *NElements = cast<ConstantInt>(MI->getArraySize());
686
687   if (NElements->getZExtValue() != 1) {
688     // If we have an array allocation, transform it to a single element
689     // allocation to make the code below simpler.
690     Type *NewTy = ArrayType::get(MI->getAllocatedType(),
691                                  NElements->getZExtValue());
692     MallocInst *NewMI =
693       new MallocInst(NewTy, Constant::getNullValue(Type::Int32Ty),
694                      MI->getAlignment(), MI->getName(), MI);
695     Value* Indices[2];
696     Indices[0] = Indices[1] = Constant::getNullValue(Type::Int32Ty);
697     Value *NewGEP = new GetElementPtrInst(NewMI, Indices, 2,
698                                           NewMI->getName()+".el0", MI);
699     MI->replaceAllUsesWith(NewGEP);
700     MI->eraseFromParent();
701     MI = NewMI;
702   }
703
704   // Create the new global variable.  The contents of the malloc'd memory is
705   // undefined, so initialize with an undef value.
706   Constant *Init = UndefValue::get(MI->getAllocatedType());
707   GlobalVariable *NewGV = new GlobalVariable(MI->getAllocatedType(), false,
708                                              GlobalValue::InternalLinkage, Init,
709                                              GV->getName()+".body",
710                                              (Module *)NULL,
711                                              GV->isThreadLocal());
712   GV->getParent()->getGlobalList().insert(GV, NewGV);
713
714   // Anything that used the malloc now uses the global directly.
715   MI->replaceAllUsesWith(NewGV);
716
717   Constant *RepValue = NewGV;
718   if (NewGV->getType() != GV->getType()->getElementType())
719     RepValue = ConstantExpr::getBitCast(RepValue, 
720                                         GV->getType()->getElementType());
721
722   // If there is a comparison against null, we will insert a global bool to
723   // keep track of whether the global was initialized yet or not.
724   GlobalVariable *InitBool =
725     new GlobalVariable(Type::Int1Ty, false, GlobalValue::InternalLinkage,
726                        ConstantInt::getFalse(), GV->getName()+".init",
727                        (Module *)NULL, GV->isThreadLocal());
728   bool InitBoolUsed = false;
729
730   // Loop over all uses of GV, processing them in turn.
731   std::vector<StoreInst*> Stores;
732   while (!GV->use_empty())
733     if (LoadInst *LI = dyn_cast<LoadInst>(GV->use_back())) {
734       while (!LI->use_empty()) {
735         Use &LoadUse = LI->use_begin().getUse();
736         if (!isa<ICmpInst>(LoadUse.getUser()))
737           LoadUse = RepValue;
738         else {
739           ICmpInst *CI = cast<ICmpInst>(LoadUse.getUser());
740           // Replace the cmp X, 0 with a use of the bool value.
741           Value *LV = new LoadInst(InitBool, InitBool->getName()+".val", CI);
742           InitBoolUsed = true;
743           switch (CI->getPredicate()) {
744           default: assert(0 && "Unknown ICmp Predicate!");
745           case ICmpInst::ICMP_ULT:
746           case ICmpInst::ICMP_SLT:
747             LV = ConstantInt::getFalse();   // X < null -> always false
748             break;
749           case ICmpInst::ICMP_ULE:
750           case ICmpInst::ICMP_SLE:
751           case ICmpInst::ICMP_EQ:
752             LV = BinaryOperator::createNot(LV, "notinit", CI);
753             break;
754           case ICmpInst::ICMP_NE:
755           case ICmpInst::ICMP_UGE:
756           case ICmpInst::ICMP_SGE:
757           case ICmpInst::ICMP_UGT:
758           case ICmpInst::ICMP_SGT:
759             break;  // no change.
760           }
761           CI->replaceAllUsesWith(LV);
762           CI->eraseFromParent();
763         }
764       }
765       LI->eraseFromParent();
766     } else {
767       StoreInst *SI = cast<StoreInst>(GV->use_back());
768       // The global is initialized when the store to it occurs.
769       new StoreInst(ConstantInt::getTrue(), InitBool, SI);
770       SI->eraseFromParent();
771     }
772
773   // If the initialization boolean was used, insert it, otherwise delete it.
774   if (!InitBoolUsed) {
775     while (!InitBool->use_empty())  // Delete initializations
776       cast<Instruction>(InitBool->use_back())->eraseFromParent();
777     delete InitBool;
778   } else
779     GV->getParent()->getGlobalList().insert(GV, InitBool);
780
781
782   // Now the GV is dead, nuke it and the malloc.
783   GV->eraseFromParent();
784   MI->eraseFromParent();
785
786   // To further other optimizations, loop over all users of NewGV and try to
787   // constant prop them.  This will promote GEP instructions with constant
788   // indices into GEP constant-exprs, which will allow global-opt to hack on it.
789   ConstantPropUsersOf(NewGV);
790   if (RepValue != NewGV)
791     ConstantPropUsersOf(RepValue);
792
793   return NewGV;
794 }
795
796 /// ValueIsOnlyUsedLocallyOrStoredToOneGlobal - Scan the use-list of V checking
797 /// to make sure that there are no complex uses of V.  We permit simple things
798 /// like dereferencing the pointer, but not storing through the address, unless
799 /// it is to the specified global.
800 static bool ValueIsOnlyUsedLocallyOrStoredToOneGlobal(Instruction *V,
801                                                       GlobalVariable *GV) {
802   for (Value::use_iterator UI = V->use_begin(), E = V->use_end(); UI != E;++UI)
803     if (isa<LoadInst>(*UI) || isa<CmpInst>(*UI)) {
804       // Fine, ignore.
805     } else if (StoreInst *SI = dyn_cast<StoreInst>(*UI)) {
806       if (SI->getOperand(0) == V && SI->getOperand(1) != GV)
807         return false;  // Storing the pointer itself... bad.
808       // Otherwise, storing through it, or storing into GV... fine.
809     } else if (isa<GetElementPtrInst>(*UI) || isa<SelectInst>(*UI)) {
810       if (!ValueIsOnlyUsedLocallyOrStoredToOneGlobal(cast<Instruction>(*UI),GV))
811         return false;
812     } else {
813       return false;
814     }
815   return true;
816 }
817
818 /// ReplaceUsesOfMallocWithGlobal - The Alloc pointer is stored into GV
819 /// somewhere.  Transform all uses of the allocation into loads from the
820 /// global and uses of the resultant pointer.  Further, delete the store into
821 /// GV.  This assumes that these value pass the 
822 /// 'ValueIsOnlyUsedLocallyOrStoredToOneGlobal' predicate.
823 static void ReplaceUsesOfMallocWithGlobal(Instruction *Alloc, 
824                                           GlobalVariable *GV) {
825   while (!Alloc->use_empty()) {
826     Instruction *U = Alloc->use_back();
827     if (StoreInst *SI = dyn_cast<StoreInst>(U)) {
828       // If this is the store of the allocation into the global, remove it.
829       if (SI->getOperand(1) == GV) {
830         SI->eraseFromParent();
831         continue;
832       }
833     }
834     
835     // Insert a load from the global, and use it instead of the malloc.
836     Value *NL = new LoadInst(GV, GV->getName()+".val", U);
837     U->replaceUsesOfWith(Alloc, NL);
838   }
839 }
840
841 /// GlobalLoadUsesSimpleEnoughForHeapSRA - If all users of values loaded from
842 /// GV are simple enough to perform HeapSRA, return true.
843 static bool GlobalLoadUsesSimpleEnoughForHeapSRA(GlobalVariable *GV) {
844   for (Value::use_iterator UI = GV->use_begin(), E = GV->use_end(); UI != E; 
845        ++UI)
846     if (LoadInst *LI = dyn_cast<LoadInst>(*UI)) {
847       // We permit two users of the load: setcc comparing against the null
848       // pointer, and a getelementptr of a specific form.
849       for (Value::use_iterator UI = LI->use_begin(), E = LI->use_end(); UI != E; 
850            ++UI) {
851         // Comparison against null is ok.
852         if (ICmpInst *ICI = dyn_cast<ICmpInst>(*UI)) {
853           if (!isa<ConstantPointerNull>(ICI->getOperand(1)))
854             return false;
855           continue;
856         }
857         
858         // getelementptr is also ok, but only a simple form.
859         GetElementPtrInst *GEPI = dyn_cast<GetElementPtrInst>(*UI);
860         if (!GEPI) return false;
861         
862         // Must index into the array and into the struct.
863         if (GEPI->getNumOperands() < 3)
864           return false;
865         
866         // Otherwise the GEP is ok.
867         continue;
868       }
869     }
870   return true;
871 }
872
873 /// RewriteUsesOfLoadForHeapSRoA - We are performing Heap SRoA on a global.  Ptr
874 /// is a value loaded from the global.  Eliminate all uses of Ptr, making them
875 /// use FieldGlobals instead.  All uses of loaded values satisfy
876 /// GlobalLoadUsesSimpleEnoughForHeapSRA.
877 static void RewriteUsesOfLoadForHeapSRoA(LoadInst *Ptr, 
878                              const std::vector<GlobalVariable*> &FieldGlobals) {
879   std::vector<Value *> InsertedLoadsForPtr;
880   //InsertedLoadsForPtr.resize(FieldGlobals.size());
881   while (!Ptr->use_empty()) {
882     Instruction *User = Ptr->use_back();
883     
884     // If this is a comparison against null, handle it.
885     if (ICmpInst *SCI = dyn_cast<ICmpInst>(User)) {
886       assert(isa<ConstantPointerNull>(SCI->getOperand(1)));
887       // If we have a setcc of the loaded pointer, we can use a setcc of any
888       // field.
889       Value *NPtr;
890       if (InsertedLoadsForPtr.empty()) {
891         NPtr = new LoadInst(FieldGlobals[0], Ptr->getName()+".f0", Ptr);
892         InsertedLoadsForPtr.push_back(Ptr);
893       } else {
894         NPtr = InsertedLoadsForPtr.back();
895       }
896       
897       Value *New = new ICmpInst(SCI->getPredicate(), NPtr,
898                                 Constant::getNullValue(NPtr->getType()),
899                                 SCI->getName(), SCI);
900       SCI->replaceAllUsesWith(New);
901       SCI->eraseFromParent();
902       continue;
903     }
904     
905     // Otherwise, this should be: 'getelementptr Ptr, Idx, uint FieldNo ...'
906     GetElementPtrInst *GEPI = cast<GetElementPtrInst>(User);
907     assert(GEPI->getNumOperands() >= 3 && isa<ConstantInt>(GEPI->getOperand(2))
908            && "Unexpected GEPI!");
909     
910     // Load the pointer for this field.
911     unsigned FieldNo = cast<ConstantInt>(GEPI->getOperand(2))->getZExtValue();
912     if (InsertedLoadsForPtr.size() <= FieldNo)
913       InsertedLoadsForPtr.resize(FieldNo+1);
914     if (InsertedLoadsForPtr[FieldNo] == 0)
915       InsertedLoadsForPtr[FieldNo] = new LoadInst(FieldGlobals[FieldNo],
916                                                   Ptr->getName()+".f" + 
917                                                   utostr(FieldNo), Ptr);
918     Value *NewPtr = InsertedLoadsForPtr[FieldNo];
919
920     // Create the new GEP idx vector.
921     SmallVector<Value*, 8> GEPIdx;
922     GEPIdx.push_back(GEPI->getOperand(1));
923     GEPIdx.append(GEPI->op_begin()+3, GEPI->op_end());
924
925     Value *NGEPI = new GetElementPtrInst(NewPtr, &GEPIdx[0], GEPIdx.size(),
926                                          GEPI->getName(), GEPI);
927     GEPI->replaceAllUsesWith(NGEPI);
928     GEPI->eraseFromParent();
929   }
930 }
931
932 /// PerformHeapAllocSRoA - MI is an allocation of an array of structures.  Break
933 /// it up into multiple allocations of arrays of the fields.
934 static GlobalVariable *PerformHeapAllocSRoA(GlobalVariable *GV, MallocInst *MI){
935   DOUT << "SROA HEAP ALLOC: " << *GV << "  MALLOC = " << *MI;
936   const StructType *STy = cast<StructType>(MI->getAllocatedType());
937
938   // There is guaranteed to be at least one use of the malloc (storing
939   // it into GV).  If there are other uses, change them to be uses of
940   // the global to simplify later code.  This also deletes the store
941   // into GV.
942   ReplaceUsesOfMallocWithGlobal(MI, GV);
943   
944   // Okay, at this point, there are no users of the malloc.  Insert N
945   // new mallocs at the same place as MI, and N globals.
946   std::vector<GlobalVariable*> FieldGlobals;
947   std::vector<MallocInst*> FieldMallocs;
948   
949   for (unsigned FieldNo = 0, e = STy->getNumElements(); FieldNo != e;++FieldNo){
950     const Type *FieldTy = STy->getElementType(FieldNo);
951     const Type *PFieldTy = PointerType::get(FieldTy);
952     
953     GlobalVariable *NGV =
954       new GlobalVariable(PFieldTy, false, GlobalValue::InternalLinkage,
955                          Constant::getNullValue(PFieldTy),
956                          GV->getName() + ".f" + utostr(FieldNo), GV,
957                          GV->isThreadLocal());
958     FieldGlobals.push_back(NGV);
959     
960     MallocInst *NMI = new MallocInst(FieldTy, MI->getArraySize(),
961                                      MI->getName() + ".f" + utostr(FieldNo),MI);
962     FieldMallocs.push_back(NMI);
963     new StoreInst(NMI, NGV, MI);
964   }
965   
966   // The tricky aspect of this transformation is handling the case when malloc
967   // fails.  In the original code, malloc failing would set the result pointer
968   // of malloc to null.  In this case, some mallocs could succeed and others
969   // could fail.  As such, we emit code that looks like this:
970   //    F0 = malloc(field0)
971   //    F1 = malloc(field1)
972   //    F2 = malloc(field2)
973   //    if (F0 == 0 || F1 == 0 || F2 == 0) {
974   //      if (F0) { free(F0); F0 = 0; }
975   //      if (F1) { free(F1); F1 = 0; }
976   //      if (F2) { free(F2); F2 = 0; }
977   //    }
978   Value *RunningOr = 0;
979   for (unsigned i = 0, e = FieldMallocs.size(); i != e; ++i) {
980     Value *Cond = new ICmpInst(ICmpInst::ICMP_EQ, FieldMallocs[i],
981                              Constant::getNullValue(FieldMallocs[i]->getType()),
982                                   "isnull", MI);
983     if (!RunningOr)
984       RunningOr = Cond;   // First seteq
985     else
986       RunningOr = BinaryOperator::createOr(RunningOr, Cond, "tmp", MI);
987   }
988
989   // Split the basic block at the old malloc.
990   BasicBlock *OrigBB = MI->getParent();
991   BasicBlock *ContBB = OrigBB->splitBasicBlock(MI, "malloc_cont");
992   
993   // Create the block to check the first condition.  Put all these blocks at the
994   // end of the function as they are unlikely to be executed.
995   BasicBlock *NullPtrBlock = new BasicBlock("malloc_ret_null",
996                                             OrigBB->getParent());
997   
998   // Remove the uncond branch from OrigBB to ContBB, turning it into a cond
999   // branch on RunningOr.
1000   OrigBB->getTerminator()->eraseFromParent();
1001   new BranchInst(NullPtrBlock, ContBB, RunningOr, OrigBB);
1002   
1003   // Within the NullPtrBlock, we need to emit a comparison and branch for each
1004   // pointer, because some may be null while others are not.
1005   for (unsigned i = 0, e = FieldGlobals.size(); i != e; ++i) {
1006     Value *GVVal = new LoadInst(FieldGlobals[i], "tmp", NullPtrBlock);
1007     Value *Cmp = new ICmpInst(ICmpInst::ICMP_NE, GVVal, 
1008                               Constant::getNullValue(GVVal->getType()),
1009                               "tmp", NullPtrBlock);
1010     BasicBlock *FreeBlock = new BasicBlock("free_it", OrigBB->getParent());
1011     BasicBlock *NextBlock = new BasicBlock("next", OrigBB->getParent());
1012     new BranchInst(FreeBlock, NextBlock, Cmp, NullPtrBlock);
1013
1014     // Fill in FreeBlock.
1015     new FreeInst(GVVal, FreeBlock);
1016     new StoreInst(Constant::getNullValue(GVVal->getType()), FieldGlobals[i],
1017                   FreeBlock);
1018     new BranchInst(NextBlock, FreeBlock);
1019     
1020     NullPtrBlock = NextBlock;
1021   }
1022   
1023   new BranchInst(ContBB, NullPtrBlock);
1024   
1025   
1026   // MI is no longer needed, remove it.
1027   MI->eraseFromParent();
1028
1029   
1030   // Okay, the malloc site is completely handled.  All of the uses of GV are now
1031   // loads, and all uses of those loads are simple.  Rewrite them to use loads
1032   // of the per-field globals instead.
1033   while (!GV->use_empty()) {
1034     if (LoadInst *LI = dyn_cast<LoadInst>(GV->use_back())) {
1035       RewriteUsesOfLoadForHeapSRoA(LI, FieldGlobals);
1036       LI->eraseFromParent();
1037     } else {
1038       // Must be a store of null.
1039       StoreInst *SI = cast<StoreInst>(GV->use_back());
1040       assert(isa<Constant>(SI->getOperand(0)) &&
1041              cast<Constant>(SI->getOperand(0))->isNullValue() &&
1042              "Unexpected heap-sra user!");
1043       
1044       // Insert a store of null into each global.
1045       for (unsigned i = 0, e = FieldGlobals.size(); i != e; ++i) {
1046         Constant *Null = 
1047           Constant::getNullValue(FieldGlobals[i]->getType()->getElementType());
1048         new StoreInst(Null, FieldGlobals[i], SI);
1049       }
1050       // Erase the original store.
1051       SI->eraseFromParent();
1052     }
1053   }
1054
1055   // The old global is now dead, remove it.
1056   GV->eraseFromParent();
1057
1058   ++NumHeapSRA;
1059   return FieldGlobals[0];
1060 }
1061
1062
1063 // OptimizeOnceStoredGlobal - Try to optimize globals based on the knowledge
1064 // that only one value (besides its initializer) is ever stored to the global.
1065 static bool OptimizeOnceStoredGlobal(GlobalVariable *GV, Value *StoredOnceVal,
1066                                      Module::global_iterator &GVI,
1067                                      TargetData &TD) {
1068   if (CastInst *CI = dyn_cast<CastInst>(StoredOnceVal))
1069     StoredOnceVal = CI->getOperand(0);
1070   else if (GetElementPtrInst *GEPI =dyn_cast<GetElementPtrInst>(StoredOnceVal)){
1071     // "getelementptr Ptr, 0, 0, 0" is really just a cast.
1072     bool IsJustACast = true;
1073     for (unsigned i = 1, e = GEPI->getNumOperands(); i != e; ++i)
1074       if (!isa<Constant>(GEPI->getOperand(i)) ||
1075           !cast<Constant>(GEPI->getOperand(i))->isNullValue()) {
1076         IsJustACast = false;
1077         break;
1078       }
1079     if (IsJustACast)
1080       StoredOnceVal = GEPI->getOperand(0);
1081   }
1082
1083   // If we are dealing with a pointer global that is initialized to null and
1084   // only has one (non-null) value stored into it, then we can optimize any
1085   // users of the loaded value (often calls and loads) that would trap if the
1086   // value was null.
1087   if (isa<PointerType>(GV->getInitializer()->getType()) &&
1088       GV->getInitializer()->isNullValue()) {
1089     if (Constant *SOVC = dyn_cast<Constant>(StoredOnceVal)) {
1090       if (GV->getInitializer()->getType() != SOVC->getType())
1091         SOVC = ConstantExpr::getBitCast(SOVC, GV->getInitializer()->getType());
1092
1093       // Optimize away any trapping uses of the loaded value.
1094       if (OptimizeAwayTrappingUsesOfLoads(GV, SOVC))
1095         return true;
1096     } else if (MallocInst *MI = dyn_cast<MallocInst>(StoredOnceVal)) {
1097       // If this is a malloc of an abstract type, don't touch it.
1098       if (!MI->getAllocatedType()->isSized())
1099         return false;
1100       
1101       // We can't optimize this global unless all uses of it are *known* to be
1102       // of the malloc value, not of the null initializer value (consider a use
1103       // that compares the global's value against zero to see if the malloc has
1104       // been reached).  To do this, we check to see if all uses of the global
1105       // would trap if the global were null: this proves that they must all
1106       // happen after the malloc.
1107       if (!AllUsesOfLoadedValueWillTrapIfNull(GV))
1108         return false;
1109
1110       // We can't optimize this if the malloc itself is used in a complex way,
1111       // for example, being stored into multiple globals.  This allows the
1112       // malloc to be stored into the specified global, loaded setcc'd, and
1113       // GEP'd.  These are all things we could transform to using the global
1114       // for.
1115       if (!ValueIsOnlyUsedLocallyOrStoredToOneGlobal(MI, GV))
1116         return false;
1117
1118       
1119       // If we have a global that is only initialized with a fixed size malloc,
1120       // transform the program to use global memory instead of malloc'd memory.
1121       // This eliminates dynamic allocation, avoids an indirection accessing the
1122       // data, and exposes the resultant global to further GlobalOpt.
1123       if (ConstantInt *NElements = dyn_cast<ConstantInt>(MI->getArraySize())) {
1124         // Restrict this transformation to only working on small allocations
1125         // (2048 bytes currently), as we don't want to introduce a 16M global or
1126         // something.
1127         if (NElements->getZExtValue()*
1128                      TD.getTypeSize(MI->getAllocatedType()) < 2048) {
1129           GVI = OptimizeGlobalAddressOfMalloc(GV, MI);
1130           return true;
1131         }
1132       }
1133
1134       // If the allocation is an array of structures, consider transforming this
1135       // into multiple malloc'd arrays, one for each field.  This is basically
1136       // SRoA for malloc'd memory.
1137       if (const StructType *AllocTy = 
1138                   dyn_cast<StructType>(MI->getAllocatedType())) {
1139         // This the structure has an unreasonable number of fields, leave it
1140         // alone.
1141         if (AllocTy->getNumElements() <= 16 && AllocTy->getNumElements() > 0 &&
1142             GlobalLoadUsesSimpleEnoughForHeapSRA(GV)) {
1143           GVI = PerformHeapAllocSRoA(GV, MI);
1144           return true;
1145         }
1146       }
1147     }
1148   }
1149
1150   return false;
1151 }
1152
1153 /// ShrinkGlobalToBoolean - At this point, we have learned that the only two
1154 /// values ever stored into GV are its initializer and OtherVal.
1155 static void ShrinkGlobalToBoolean(GlobalVariable *GV, Constant *OtherVal) {
1156   // Create the new global, initializing it to false.
1157   GlobalVariable *NewGV = new GlobalVariable(Type::Int1Ty, false,
1158          GlobalValue::InternalLinkage, ConstantInt::getFalse(),
1159                                              GV->getName()+".b",
1160                                              (Module *)NULL,
1161                                              GV->isThreadLocal());
1162   GV->getParent()->getGlobalList().insert(GV, NewGV);
1163
1164   Constant *InitVal = GV->getInitializer();
1165   assert(InitVal->getType() != Type::Int1Ty && "No reason to shrink to bool!");
1166
1167   // If initialized to zero and storing one into the global, we can use a cast
1168   // instead of a select to synthesize the desired value.
1169   bool IsOneZero = false;
1170   if (ConstantInt *CI = dyn_cast<ConstantInt>(OtherVal))
1171     IsOneZero = InitVal->isNullValue() && CI->isOne();
1172
1173   while (!GV->use_empty()) {
1174     Instruction *UI = cast<Instruction>(GV->use_back());
1175     if (StoreInst *SI = dyn_cast<StoreInst>(UI)) {
1176       // Change the store into a boolean store.
1177       bool StoringOther = SI->getOperand(0) == OtherVal;
1178       // Only do this if we weren't storing a loaded value.
1179       Value *StoreVal;
1180       if (StoringOther || SI->getOperand(0) == InitVal)
1181         StoreVal = ConstantInt::get(Type::Int1Ty, StoringOther);
1182       else {
1183         // Otherwise, we are storing a previously loaded copy.  To do this,
1184         // change the copy from copying the original value to just copying the
1185         // bool.
1186         Instruction *StoredVal = cast<Instruction>(SI->getOperand(0));
1187
1188         // If we're already replaced the input, StoredVal will be a cast or
1189         // select instruction.  If not, it will be a load of the original
1190         // global.
1191         if (LoadInst *LI = dyn_cast<LoadInst>(StoredVal)) {
1192           assert(LI->getOperand(0) == GV && "Not a copy!");
1193           // Insert a new load, to preserve the saved value.
1194           StoreVal = new LoadInst(NewGV, LI->getName()+".b", LI);
1195         } else {
1196           assert((isa<CastInst>(StoredVal) || isa<SelectInst>(StoredVal)) &&
1197                  "This is not a form that we understand!");
1198           StoreVal = StoredVal->getOperand(0);
1199           assert(isa<LoadInst>(StoreVal) && "Not a load of NewGV!");
1200         }
1201       }
1202       new StoreInst(StoreVal, NewGV, SI);
1203     } else if (!UI->use_empty()) {
1204       // Change the load into a load of bool then a select.
1205       LoadInst *LI = cast<LoadInst>(UI);
1206       LoadInst *NLI = new LoadInst(NewGV, LI->getName()+".b", LI);
1207       Value *NSI;
1208       if (IsOneZero)
1209         NSI = new ZExtInst(NLI, LI->getType(), "", LI);
1210       else
1211         NSI = new SelectInst(NLI, OtherVal, InitVal, "", LI);
1212       NSI->takeName(LI);
1213       LI->replaceAllUsesWith(NSI);
1214     }
1215     UI->eraseFromParent();
1216   }
1217
1218   GV->eraseFromParent();
1219 }
1220
1221
1222 /// ProcessInternalGlobal - Analyze the specified global variable and optimize
1223 /// it if possible.  If we make a change, return true.
1224 bool GlobalOpt::ProcessInternalGlobal(GlobalVariable *GV,
1225                                       Module::global_iterator &GVI) {
1226   std::set<PHINode*> PHIUsers;
1227   GlobalStatus GS;
1228   GV->removeDeadConstantUsers();
1229
1230   if (GV->use_empty()) {
1231     DOUT << "GLOBAL DEAD: " << *GV;
1232     GV->eraseFromParent();
1233     ++NumDeleted;
1234     return true;
1235   }
1236
1237   if (!AnalyzeGlobal(GV, GS, PHIUsers)) {
1238 #if 0
1239     cerr << "Global: " << *GV;
1240     cerr << "  isLoaded = " << GS.isLoaded << "\n";
1241     cerr << "  StoredType = ";
1242     switch (GS.StoredType) {
1243     case GlobalStatus::NotStored: cerr << "NEVER STORED\n"; break;
1244     case GlobalStatus::isInitializerStored: cerr << "INIT STORED\n"; break;
1245     case GlobalStatus::isStoredOnce: cerr << "STORED ONCE\n"; break;
1246     case GlobalStatus::isStored: cerr << "stored\n"; break;
1247     }
1248     if (GS.StoredType == GlobalStatus::isStoredOnce && GS.StoredOnceValue)
1249       cerr << "  StoredOnceValue = " << *GS.StoredOnceValue << "\n";
1250     if (GS.AccessingFunction && !GS.HasMultipleAccessingFunctions)
1251       cerr << "  AccessingFunction = " << GS.AccessingFunction->getName()
1252                 << "\n";
1253     cerr << "  HasMultipleAccessingFunctions =  "
1254               << GS.HasMultipleAccessingFunctions << "\n";
1255     cerr << "  HasNonInstructionUser = " << GS.HasNonInstructionUser<<"\n";
1256     cerr << "  isNotSuitableForSRA = " << GS.isNotSuitableForSRA << "\n";
1257     cerr << "\n";
1258 #endif
1259     
1260     // If this is a first class global and has only one accessing function
1261     // and this function is main (which we know is not recursive we can make
1262     // this global a local variable) we replace the global with a local alloca
1263     // in this function.
1264     //
1265     // NOTE: It doesn't make sense to promote non first class types since we
1266     // are just replacing static memory to stack memory.
1267     if (!GS.HasMultipleAccessingFunctions &&
1268         GS.AccessingFunction && !GS.HasNonInstructionUser &&
1269         GV->getType()->getElementType()->isFirstClassType() &&
1270         GS.AccessingFunction->getName() == "main" &&
1271         GS.AccessingFunction->hasExternalLinkage()) {
1272       DOUT << "LOCALIZING GLOBAL: " << *GV;
1273       Instruction* FirstI = GS.AccessingFunction->getEntryBlock().begin();
1274       const Type* ElemTy = GV->getType()->getElementType();
1275       // FIXME: Pass Global's alignment when globals have alignment
1276       AllocaInst* Alloca = new AllocaInst(ElemTy, NULL, GV->getName(), FirstI);
1277       if (!isa<UndefValue>(GV->getInitializer()))
1278         new StoreInst(GV->getInitializer(), Alloca, FirstI);
1279
1280       GV->replaceAllUsesWith(Alloca);
1281       GV->eraseFromParent();
1282       ++NumLocalized;
1283       return true;
1284     }
1285     
1286     // If the global is never loaded (but may be stored to), it is dead.
1287     // Delete it now.
1288     if (!GS.isLoaded) {
1289       DOUT << "GLOBAL NEVER LOADED: " << *GV;
1290
1291       // Delete any stores we can find to the global.  We may not be able to
1292       // make it completely dead though.
1293       bool Changed = CleanupConstantGlobalUsers(GV, GV->getInitializer());
1294
1295       // If the global is dead now, delete it.
1296       if (GV->use_empty()) {
1297         GV->eraseFromParent();
1298         ++NumDeleted;
1299         Changed = true;
1300       }
1301       return Changed;
1302
1303     } else if (GS.StoredType <= GlobalStatus::isInitializerStored) {
1304       DOUT << "MARKING CONSTANT: " << *GV;
1305       GV->setConstant(true);
1306
1307       // Clean up any obviously simplifiable users now.
1308       CleanupConstantGlobalUsers(GV, GV->getInitializer());
1309
1310       // If the global is dead now, just nuke it.
1311       if (GV->use_empty()) {
1312         DOUT << "   *** Marking constant allowed us to simplify "
1313              << "all users and delete global!\n";
1314         GV->eraseFromParent();
1315         ++NumDeleted;
1316       }
1317
1318       ++NumMarked;
1319       return true;
1320     } else if (!GS.isNotSuitableForSRA &&
1321                !GV->getInitializer()->getType()->isFirstClassType()) {
1322       if (GlobalVariable *FirstNewGV = SRAGlobal(GV)) {
1323         GVI = FirstNewGV;  // Don't skip the newly produced globals!
1324         return true;
1325       }
1326     } else if (GS.StoredType == GlobalStatus::isStoredOnce) {
1327       // If the initial value for the global was an undef value, and if only
1328       // one other value was stored into it, we can just change the
1329       // initializer to be an undef value, then delete all stores to the
1330       // global.  This allows us to mark it constant.
1331       if (Constant *SOVConstant = dyn_cast<Constant>(GS.StoredOnceValue))
1332         if (isa<UndefValue>(GV->getInitializer())) {
1333           // Change the initial value here.
1334           GV->setInitializer(SOVConstant);
1335
1336           // Clean up any obviously simplifiable users now.
1337           CleanupConstantGlobalUsers(GV, GV->getInitializer());
1338
1339           if (GV->use_empty()) {
1340             DOUT << "   *** Substituting initializer allowed us to "
1341                  << "simplify all users and delete global!\n";
1342             GV->eraseFromParent();
1343             ++NumDeleted;
1344           } else {
1345             GVI = GV;
1346           }
1347           ++NumSubstitute;
1348           return true;
1349         }
1350
1351       // Try to optimize globals based on the knowledge that only one value
1352       // (besides its initializer) is ever stored to the global.
1353       if (OptimizeOnceStoredGlobal(GV, GS.StoredOnceValue, GVI,
1354                                    getAnalysis<TargetData>()))
1355         return true;
1356
1357       // Otherwise, if the global was not a boolean, we can shrink it to be a
1358       // boolean.
1359       if (Constant *SOVConstant = dyn_cast<Constant>(GS.StoredOnceValue))
1360         if (GV->getType()->getElementType() != Type::Int1Ty &&
1361             !GV->getType()->getElementType()->isFloatingPoint() &&
1362             !isa<VectorType>(GV->getType()->getElementType()) &&
1363             !GS.HasPHIUser && !GS.isNotSuitableForSRA) {
1364           DOUT << "   *** SHRINKING TO BOOL: " << *GV;
1365           ShrinkGlobalToBoolean(GV, SOVConstant);
1366           ++NumShrunkToBool;
1367           return true;
1368         }
1369     }
1370   }
1371   return false;
1372 }
1373
1374 /// OnlyCalledDirectly - Return true if the specified function is only called
1375 /// directly.  In other words, its address is never taken.
1376 static bool OnlyCalledDirectly(Function *F) {
1377   for (Value::use_iterator UI = F->use_begin(), E = F->use_end(); UI != E;++UI){
1378     Instruction *User = dyn_cast<Instruction>(*UI);
1379     if (!User) return false;
1380     if (!isa<CallInst>(User) && !isa<InvokeInst>(User)) return false;
1381
1382     // See if the function address is passed as an argument.
1383     for (unsigned i = 1, e = User->getNumOperands(); i != e; ++i)
1384       if (User->getOperand(i) == F) return false;
1385   }
1386   return true;
1387 }
1388
1389 /// ChangeCalleesToFastCall - Walk all of the direct calls of the specified
1390 /// function, changing them to FastCC.
1391 static void ChangeCalleesToFastCall(Function *F) {
1392   for (Value::use_iterator UI = F->use_begin(), E = F->use_end(); UI != E;++UI){
1393     Instruction *User = cast<Instruction>(*UI);
1394     if (CallInst *CI = dyn_cast<CallInst>(User))
1395       CI->setCallingConv(CallingConv::Fast);
1396     else
1397       cast<InvokeInst>(User)->setCallingConv(CallingConv::Fast);
1398   }
1399 }
1400
1401 bool GlobalOpt::OptimizeFunctions(Module &M) {
1402   bool Changed = false;
1403   // Optimize functions.
1404   for (Module::iterator FI = M.begin(), E = M.end(); FI != E; ) {
1405     Function *F = FI++;
1406     F->removeDeadConstantUsers();
1407     if (F->use_empty() && (F->hasInternalLinkage() ||
1408                            F->hasLinkOnceLinkage())) {
1409       M.getFunctionList().erase(F);
1410       Changed = true;
1411       ++NumFnDeleted;
1412     } else if (F->hasInternalLinkage() &&
1413                F->getCallingConv() == CallingConv::C &&  !F->isVarArg() &&
1414                OnlyCalledDirectly(F)) {
1415       // If this function has C calling conventions, is not a varargs
1416       // function, and is only called directly, promote it to use the Fast
1417       // calling convention.
1418       F->setCallingConv(CallingConv::Fast);
1419       ChangeCalleesToFastCall(F);
1420       ++NumFastCallFns;
1421       Changed = true;
1422     }
1423   }
1424   return Changed;
1425 }
1426
1427 bool GlobalOpt::OptimizeGlobalVars(Module &M) {
1428   bool Changed = false;
1429   for (Module::global_iterator GVI = M.global_begin(), E = M.global_end();
1430        GVI != E; ) {
1431     GlobalVariable *GV = GVI++;
1432     if (!GV->isConstant() && GV->hasInternalLinkage() &&
1433         GV->hasInitializer())
1434       Changed |= ProcessInternalGlobal(GV, GVI);
1435   }
1436   return Changed;
1437 }
1438
1439 /// FindGlobalCtors - Find the llvm.globalctors list, verifying that all
1440 /// initializers have an init priority of 65535.
1441 GlobalVariable *GlobalOpt::FindGlobalCtors(Module &M) {
1442   for (Module::global_iterator I = M.global_begin(), E = M.global_end();
1443        I != E; ++I)
1444     if (I->getName() == "llvm.global_ctors") {
1445       // Found it, verify it's an array of { int, void()* }.
1446       const ArrayType *ATy =dyn_cast<ArrayType>(I->getType()->getElementType());
1447       if (!ATy) return 0;
1448       const StructType *STy = dyn_cast<StructType>(ATy->getElementType());
1449       if (!STy || STy->getNumElements() != 2 ||
1450           STy->getElementType(0) != Type::Int32Ty) return 0;
1451       const PointerType *PFTy = dyn_cast<PointerType>(STy->getElementType(1));
1452       if (!PFTy) return 0;
1453       const FunctionType *FTy = dyn_cast<FunctionType>(PFTy->getElementType());
1454       if (!FTy || FTy->getReturnType() != Type::VoidTy || FTy->isVarArg() ||
1455           FTy->getNumParams() != 0)
1456         return 0;
1457       
1458       // Verify that the initializer is simple enough for us to handle.
1459       if (!I->hasInitializer()) return 0;
1460       ConstantArray *CA = dyn_cast<ConstantArray>(I->getInitializer());
1461       if (!CA) return 0;
1462       for (unsigned i = 0, e = CA->getNumOperands(); i != e; ++i)
1463         if (ConstantStruct *CS = dyn_cast<ConstantStruct>(CA->getOperand(i))) {
1464           if (isa<ConstantPointerNull>(CS->getOperand(1)))
1465             continue;
1466
1467           // Must have a function or null ptr.
1468           if (!isa<Function>(CS->getOperand(1)))
1469             return 0;
1470           
1471           // Init priority must be standard.
1472           ConstantInt *CI = dyn_cast<ConstantInt>(CS->getOperand(0));
1473           if (!CI || CI->getZExtValue() != 65535)
1474             return 0;
1475         } else {
1476           return 0;
1477         }
1478       
1479       return I;
1480     }
1481   return 0;
1482 }
1483
1484 /// ParseGlobalCtors - Given a llvm.global_ctors list that we can understand,
1485 /// return a list of the functions and null terminator as a vector.
1486 static std::vector<Function*> ParseGlobalCtors(GlobalVariable *GV) {
1487   ConstantArray *CA = cast<ConstantArray>(GV->getInitializer());
1488   std::vector<Function*> Result;
1489   Result.reserve(CA->getNumOperands());
1490   for (unsigned i = 0, e = CA->getNumOperands(); i != e; ++i) {
1491     ConstantStruct *CS = cast<ConstantStruct>(CA->getOperand(i));
1492     Result.push_back(dyn_cast<Function>(CS->getOperand(1)));
1493   }
1494   return Result;
1495 }
1496
1497 /// InstallGlobalCtors - Given a specified llvm.global_ctors list, install the
1498 /// specified array, returning the new global to use.
1499 static GlobalVariable *InstallGlobalCtors(GlobalVariable *GCL, 
1500                                           const std::vector<Function*> &Ctors) {
1501   // If we made a change, reassemble the initializer list.
1502   std::vector<Constant*> CSVals;
1503   CSVals.push_back(ConstantInt::get(Type::Int32Ty, 65535));
1504   CSVals.push_back(0);
1505   
1506   // Create the new init list.
1507   std::vector<Constant*> CAList;
1508   for (unsigned i = 0, e = Ctors.size(); i != e; ++i) {
1509     if (Ctors[i]) {
1510       CSVals[1] = Ctors[i];
1511     } else {
1512       const Type *FTy = FunctionType::get(Type::VoidTy,
1513                                           std::vector<const Type*>(), false);
1514       const PointerType *PFTy = PointerType::get(FTy);
1515       CSVals[1] = Constant::getNullValue(PFTy);
1516       CSVals[0] = ConstantInt::get(Type::Int32Ty, 2147483647);
1517     }
1518     CAList.push_back(ConstantStruct::get(CSVals));
1519   }
1520   
1521   // Create the array initializer.
1522   const Type *StructTy =
1523     cast<ArrayType>(GCL->getType()->getElementType())->getElementType();
1524   Constant *CA = ConstantArray::get(ArrayType::get(StructTy, CAList.size()),
1525                                     CAList);
1526   
1527   // If we didn't change the number of elements, don't create a new GV.
1528   if (CA->getType() == GCL->getInitializer()->getType()) {
1529     GCL->setInitializer(CA);
1530     return GCL;
1531   }
1532   
1533   // Create the new global and insert it next to the existing list.
1534   GlobalVariable *NGV = new GlobalVariable(CA->getType(), GCL->isConstant(),
1535                                            GCL->getLinkage(), CA, "",
1536                                            (Module *)NULL,
1537                                            GCL->isThreadLocal());
1538   GCL->getParent()->getGlobalList().insert(GCL, NGV);
1539   NGV->takeName(GCL);
1540   
1541   // Nuke the old list, replacing any uses with the new one.
1542   if (!GCL->use_empty()) {
1543     Constant *V = NGV;
1544     if (V->getType() != GCL->getType())
1545       V = ConstantExpr::getBitCast(V, GCL->getType());
1546     GCL->replaceAllUsesWith(V);
1547   }
1548   GCL->eraseFromParent();
1549   
1550   if (Ctors.size())
1551     return NGV;
1552   else
1553     return 0;
1554 }
1555
1556
1557 static Constant *getVal(std::map<Value*, Constant*> &ComputedValues,
1558                         Value *V) {
1559   if (Constant *CV = dyn_cast<Constant>(V)) return CV;
1560   Constant *R = ComputedValues[V];
1561   assert(R && "Reference to an uncomputed value!");
1562   return R;
1563 }
1564
1565 /// isSimpleEnoughPointerToCommit - Return true if this constant is simple
1566 /// enough for us to understand.  In particular, if it is a cast of something,
1567 /// we punt.  We basically just support direct accesses to globals and GEP's of
1568 /// globals.  This should be kept up to date with CommitValueTo.
1569 static bool isSimpleEnoughPointerToCommit(Constant *C) {
1570   if (GlobalVariable *GV = dyn_cast<GlobalVariable>(C)) {
1571     if (!GV->hasExternalLinkage() && !GV->hasInternalLinkage())
1572       return false;  // do not allow weak/linkonce/dllimport/dllexport linkage.
1573     return !GV->isDeclaration();  // reject external globals.
1574   }
1575   if (ConstantExpr *CE = dyn_cast<ConstantExpr>(C))
1576     // Handle a constantexpr gep.
1577     if (CE->getOpcode() == Instruction::GetElementPtr &&
1578         isa<GlobalVariable>(CE->getOperand(0))) {
1579       GlobalVariable *GV = cast<GlobalVariable>(CE->getOperand(0));
1580       if (!GV->hasExternalLinkage() && !GV->hasInternalLinkage())
1581         return false;  // do not allow weak/linkonce/dllimport/dllexport linkage.
1582       return GV->hasInitializer() &&
1583              ConstantFoldLoadThroughGEPConstantExpr(GV->getInitializer(), CE);
1584     }
1585   return false;
1586 }
1587
1588 /// EvaluateStoreInto - Evaluate a piece of a constantexpr store into a global
1589 /// initializer.  This returns 'Init' modified to reflect 'Val' stored into it.
1590 /// At this point, the GEP operands of Addr [0, OpNo) have been stepped into.
1591 static Constant *EvaluateStoreInto(Constant *Init, Constant *Val,
1592                                    ConstantExpr *Addr, unsigned OpNo) {
1593   // Base case of the recursion.
1594   if (OpNo == Addr->getNumOperands()) {
1595     assert(Val->getType() == Init->getType() && "Type mismatch!");
1596     return Val;
1597   }
1598   
1599   if (const StructType *STy = dyn_cast<StructType>(Init->getType())) {
1600     std::vector<Constant*> Elts;
1601
1602     // Break up the constant into its elements.
1603     if (ConstantStruct *CS = dyn_cast<ConstantStruct>(Init)) {
1604       for (unsigned i = 0, e = CS->getNumOperands(); i != e; ++i)
1605         Elts.push_back(CS->getOperand(i));
1606     } else if (isa<ConstantAggregateZero>(Init)) {
1607       for (unsigned i = 0, e = STy->getNumElements(); i != e; ++i)
1608         Elts.push_back(Constant::getNullValue(STy->getElementType(i)));
1609     } else if (isa<UndefValue>(Init)) {
1610       for (unsigned i = 0, e = STy->getNumElements(); i != e; ++i)
1611         Elts.push_back(UndefValue::get(STy->getElementType(i)));
1612     } else {
1613       assert(0 && "This code is out of sync with "
1614              " ConstantFoldLoadThroughGEPConstantExpr");
1615     }
1616     
1617     // Replace the element that we are supposed to.
1618     ConstantInt *CU = cast<ConstantInt>(Addr->getOperand(OpNo));
1619     unsigned Idx = CU->getZExtValue();
1620     assert(Idx < STy->getNumElements() && "Struct index out of range!");
1621     Elts[Idx] = EvaluateStoreInto(Elts[Idx], Val, Addr, OpNo+1);
1622     
1623     // Return the modified struct.
1624     return ConstantStruct::get(Elts);
1625   } else {
1626     ConstantInt *CI = cast<ConstantInt>(Addr->getOperand(OpNo));
1627     const ArrayType *ATy = cast<ArrayType>(Init->getType());
1628
1629     // Break up the array into elements.
1630     std::vector<Constant*> Elts;
1631     if (ConstantArray *CA = dyn_cast<ConstantArray>(Init)) {
1632       for (unsigned i = 0, e = CA->getNumOperands(); i != e; ++i)
1633         Elts.push_back(CA->getOperand(i));
1634     } else if (isa<ConstantAggregateZero>(Init)) {
1635       Constant *Elt = Constant::getNullValue(ATy->getElementType());
1636       Elts.assign(ATy->getNumElements(), Elt);
1637     } else if (isa<UndefValue>(Init)) {
1638       Constant *Elt = UndefValue::get(ATy->getElementType());
1639       Elts.assign(ATy->getNumElements(), Elt);
1640     } else {
1641       assert(0 && "This code is out of sync with "
1642              " ConstantFoldLoadThroughGEPConstantExpr");
1643     }
1644     
1645     assert(CI->getZExtValue() < ATy->getNumElements());
1646     Elts[CI->getZExtValue()] =
1647       EvaluateStoreInto(Elts[CI->getZExtValue()], Val, Addr, OpNo+1);
1648     return ConstantArray::get(ATy, Elts);
1649   }    
1650 }
1651
1652 /// CommitValueTo - We have decided that Addr (which satisfies the predicate
1653 /// isSimpleEnoughPointerToCommit) should get Val as its value.  Make it happen.
1654 static void CommitValueTo(Constant *Val, Constant *Addr) {
1655   if (GlobalVariable *GV = dyn_cast<GlobalVariable>(Addr)) {
1656     assert(GV->hasInitializer());
1657     GV->setInitializer(Val);
1658     return;
1659   }
1660   
1661   ConstantExpr *CE = cast<ConstantExpr>(Addr);
1662   GlobalVariable *GV = cast<GlobalVariable>(CE->getOperand(0));
1663   
1664   Constant *Init = GV->getInitializer();
1665   Init = EvaluateStoreInto(Init, Val, CE, 2);
1666   GV->setInitializer(Init);
1667 }
1668
1669 /// ComputeLoadResult - Return the value that would be computed by a load from
1670 /// P after the stores reflected by 'memory' have been performed.  If we can't
1671 /// decide, return null.
1672 static Constant *ComputeLoadResult(Constant *P,
1673                                 const std::map<Constant*, Constant*> &Memory) {
1674   // If this memory location has been recently stored, use the stored value: it
1675   // is the most up-to-date.
1676   std::map<Constant*, Constant*>::const_iterator I = Memory.find(P);
1677   if (I != Memory.end()) return I->second;
1678  
1679   // Access it.
1680   if (GlobalVariable *GV = dyn_cast<GlobalVariable>(P)) {
1681     if (GV->hasInitializer())
1682       return GV->getInitializer();
1683     return 0;
1684   }
1685   
1686   // Handle a constantexpr getelementptr.
1687   if (ConstantExpr *CE = dyn_cast<ConstantExpr>(P))
1688     if (CE->getOpcode() == Instruction::GetElementPtr &&
1689         isa<GlobalVariable>(CE->getOperand(0))) {
1690       GlobalVariable *GV = cast<GlobalVariable>(CE->getOperand(0));
1691       if (GV->hasInitializer())
1692         return ConstantFoldLoadThroughGEPConstantExpr(GV->getInitializer(), CE);
1693     }
1694
1695   return 0;  // don't know how to evaluate.
1696 }
1697
1698 /// EvaluateFunction - Evaluate a call to function F, returning true if
1699 /// successful, false if we can't evaluate it.  ActualArgs contains the formal
1700 /// arguments for the function.
1701 static bool EvaluateFunction(Function *F, Constant *&RetVal,
1702                              const std::vector<Constant*> &ActualArgs,
1703                              std::vector<Function*> &CallStack,
1704                              std::map<Constant*, Constant*> &MutatedMemory,
1705                              std::vector<GlobalVariable*> &AllocaTmps) {
1706   // Check to see if this function is already executing (recursion).  If so,
1707   // bail out.  TODO: we might want to accept limited recursion.
1708   if (std::find(CallStack.begin(), CallStack.end(), F) != CallStack.end())
1709     return false;
1710   
1711   CallStack.push_back(F);
1712   
1713   /// Values - As we compute SSA register values, we store their contents here.
1714   std::map<Value*, Constant*> Values;
1715   
1716   // Initialize arguments to the incoming values specified.
1717   unsigned ArgNo = 0;
1718   for (Function::arg_iterator AI = F->arg_begin(), E = F->arg_end(); AI != E;
1719        ++AI, ++ArgNo)
1720     Values[AI] = ActualArgs[ArgNo];
1721
1722   /// ExecutedBlocks - We only handle non-looping, non-recursive code.  As such,
1723   /// we can only evaluate any one basic block at most once.  This set keeps
1724   /// track of what we have executed so we can detect recursive cases etc.
1725   std::set<BasicBlock*> ExecutedBlocks;
1726   
1727   // CurInst - The current instruction we're evaluating.
1728   BasicBlock::iterator CurInst = F->begin()->begin();
1729   
1730   // This is the main evaluation loop.
1731   while (1) {
1732     Constant *InstResult = 0;
1733     
1734     if (StoreInst *SI = dyn_cast<StoreInst>(CurInst)) {
1735       if (SI->isVolatile()) return false;  // no volatile accesses.
1736       Constant *Ptr = getVal(Values, SI->getOperand(1));
1737       if (!isSimpleEnoughPointerToCommit(Ptr))
1738         // If this is too complex for us to commit, reject it.
1739         return false;
1740       Constant *Val = getVal(Values, SI->getOperand(0));
1741       MutatedMemory[Ptr] = Val;
1742     } else if (BinaryOperator *BO = dyn_cast<BinaryOperator>(CurInst)) {
1743       InstResult = ConstantExpr::get(BO->getOpcode(),
1744                                      getVal(Values, BO->getOperand(0)),
1745                                      getVal(Values, BO->getOperand(1)));
1746     } else if (CmpInst *CI = dyn_cast<CmpInst>(CurInst)) {
1747       InstResult = ConstantExpr::getCompare(CI->getPredicate(),
1748                                             getVal(Values, CI->getOperand(0)),
1749                                             getVal(Values, CI->getOperand(1)));
1750     } else if (CastInst *CI = dyn_cast<CastInst>(CurInst)) {
1751       InstResult = ConstantExpr::getCast(CI->getOpcode(),
1752                                          getVal(Values, CI->getOperand(0)),
1753                                          CI->getType());
1754     } else if (SelectInst *SI = dyn_cast<SelectInst>(CurInst)) {
1755       InstResult = ConstantExpr::getSelect(getVal(Values, SI->getOperand(0)),
1756                                            getVal(Values, SI->getOperand(1)),
1757                                            getVal(Values, SI->getOperand(2)));
1758     } else if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(CurInst)) {
1759       Constant *P = getVal(Values, GEP->getOperand(0));
1760       SmallVector<Constant*, 8> GEPOps;
1761       for (unsigned i = 1, e = GEP->getNumOperands(); i != e; ++i)
1762         GEPOps.push_back(getVal(Values, GEP->getOperand(i)));
1763       InstResult = ConstantExpr::getGetElementPtr(P, &GEPOps[0], GEPOps.size());
1764     } else if (LoadInst *LI = dyn_cast<LoadInst>(CurInst)) {
1765       if (LI->isVolatile()) return false;  // no volatile accesses.
1766       InstResult = ComputeLoadResult(getVal(Values, LI->getOperand(0)),
1767                                      MutatedMemory);
1768       if (InstResult == 0) return false; // Could not evaluate load.
1769     } else if (AllocaInst *AI = dyn_cast<AllocaInst>(CurInst)) {
1770       if (AI->isArrayAllocation()) return false;  // Cannot handle array allocs.
1771       const Type *Ty = AI->getType()->getElementType();
1772       AllocaTmps.push_back(new GlobalVariable(Ty, false,
1773                                               GlobalValue::InternalLinkage,
1774                                               UndefValue::get(Ty),
1775                                               AI->getName()));
1776       InstResult = AllocaTmps.back();     
1777     } else if (CallInst *CI = dyn_cast<CallInst>(CurInst)) {
1778       // Cannot handle inline asm.
1779       if (isa<InlineAsm>(CI->getOperand(0))) return false;
1780
1781       // Resolve function pointers.
1782       Function *Callee = dyn_cast<Function>(getVal(Values, CI->getOperand(0)));
1783       if (!Callee) return false;  // Cannot resolve.
1784
1785       std::vector<Constant*> Formals;
1786       for (unsigned i = 1, e = CI->getNumOperands(); i != e; ++i)
1787         Formals.push_back(getVal(Values, CI->getOperand(i)));
1788       
1789       if (Callee->isDeclaration()) {
1790         // If this is a function we can constant fold, do it.
1791         if (Constant *C = ConstantFoldCall(Callee, &Formals[0],
1792                                            Formals.size())) {
1793           InstResult = C;
1794         } else {
1795           return false;
1796         }
1797       } else {
1798         if (Callee->getFunctionType()->isVarArg())
1799           return false;
1800         
1801         Constant *RetVal;
1802         
1803         // Execute the call, if successful, use the return value.
1804         if (!EvaluateFunction(Callee, RetVal, Formals, CallStack,
1805                               MutatedMemory, AllocaTmps))
1806           return false;
1807         InstResult = RetVal;
1808       }
1809     } else if (isa<TerminatorInst>(CurInst)) {
1810       BasicBlock *NewBB = 0;
1811       if (BranchInst *BI = dyn_cast<BranchInst>(CurInst)) {
1812         if (BI->isUnconditional()) {
1813           NewBB = BI->getSuccessor(0);
1814         } else {
1815           ConstantInt *Cond =
1816             dyn_cast<ConstantInt>(getVal(Values, BI->getCondition()));
1817           if (!Cond) return false;  // Cannot determine.
1818
1819           NewBB = BI->getSuccessor(!Cond->getZExtValue());          
1820         }
1821       } else if (SwitchInst *SI = dyn_cast<SwitchInst>(CurInst)) {
1822         ConstantInt *Val =
1823           dyn_cast<ConstantInt>(getVal(Values, SI->getCondition()));
1824         if (!Val) return false;  // Cannot determine.
1825         NewBB = SI->getSuccessor(SI->findCaseValue(Val));
1826       } else if (ReturnInst *RI = dyn_cast<ReturnInst>(CurInst)) {
1827         if (RI->getNumOperands())
1828           RetVal = getVal(Values, RI->getOperand(0));
1829         
1830         CallStack.pop_back();  // return from fn.
1831         return true;  // We succeeded at evaluating this ctor!
1832       } else {
1833         // invoke, unwind, unreachable.
1834         return false;  // Cannot handle this terminator.
1835       }
1836       
1837       // Okay, we succeeded in evaluating this control flow.  See if we have
1838       // executed the new block before.  If so, we have a looping function,
1839       // which we cannot evaluate in reasonable time.
1840       if (!ExecutedBlocks.insert(NewBB).second)
1841         return false;  // looped!
1842       
1843       // Okay, we have never been in this block before.  Check to see if there
1844       // are any PHI nodes.  If so, evaluate them with information about where
1845       // we came from.
1846       BasicBlock *OldBB = CurInst->getParent();
1847       CurInst = NewBB->begin();
1848       PHINode *PN;
1849       for (; (PN = dyn_cast<PHINode>(CurInst)); ++CurInst)
1850         Values[PN] = getVal(Values, PN->getIncomingValueForBlock(OldBB));
1851
1852       // Do NOT increment CurInst.  We know that the terminator had no value.
1853       continue;
1854     } else {
1855       // Did not know how to evaluate this!
1856       return false;
1857     }
1858     
1859     if (!CurInst->use_empty())
1860       Values[CurInst] = InstResult;
1861     
1862     // Advance program counter.
1863     ++CurInst;
1864   }
1865 }
1866
1867 /// EvaluateStaticConstructor - Evaluate static constructors in the function, if
1868 /// we can.  Return true if we can, false otherwise.
1869 static bool EvaluateStaticConstructor(Function *F) {
1870   /// MutatedMemory - For each store we execute, we update this map.  Loads
1871   /// check this to get the most up-to-date value.  If evaluation is successful,
1872   /// this state is committed to the process.
1873   std::map<Constant*, Constant*> MutatedMemory;
1874
1875   /// AllocaTmps - To 'execute' an alloca, we create a temporary global variable
1876   /// to represent its body.  This vector is needed so we can delete the
1877   /// temporary globals when we are done.
1878   std::vector<GlobalVariable*> AllocaTmps;
1879   
1880   /// CallStack - This is used to detect recursion.  In pathological situations
1881   /// we could hit exponential behavior, but at least there is nothing
1882   /// unbounded.
1883   std::vector<Function*> CallStack;
1884
1885   // Call the function.
1886   Constant *RetValDummy;
1887   bool EvalSuccess = EvaluateFunction(F, RetValDummy, std::vector<Constant*>(),
1888                                        CallStack, MutatedMemory, AllocaTmps);
1889   if (EvalSuccess) {
1890     // We succeeded at evaluation: commit the result.
1891     DOUT << "FULLY EVALUATED GLOBAL CTOR FUNCTION '"
1892          << F->getName() << "' to " << MutatedMemory.size()
1893          << " stores.\n";
1894     for (std::map<Constant*, Constant*>::iterator I = MutatedMemory.begin(),
1895          E = MutatedMemory.end(); I != E; ++I)
1896       CommitValueTo(I->second, I->first);
1897   }
1898   
1899   // At this point, we are done interpreting.  If we created any 'alloca'
1900   // temporaries, release them now.
1901   while (!AllocaTmps.empty()) {
1902     GlobalVariable *Tmp = AllocaTmps.back();
1903     AllocaTmps.pop_back();
1904     
1905     // If there are still users of the alloca, the program is doing something
1906     // silly, e.g. storing the address of the alloca somewhere and using it
1907     // later.  Since this is undefined, we'll just make it be null.
1908     if (!Tmp->use_empty())
1909       Tmp->replaceAllUsesWith(Constant::getNullValue(Tmp->getType()));
1910     delete Tmp;
1911   }
1912   
1913   return EvalSuccess;
1914 }
1915
1916
1917
1918 /// OptimizeGlobalCtorsList - Simplify and evaluation global ctors if possible.
1919 /// Return true if anything changed.
1920 bool GlobalOpt::OptimizeGlobalCtorsList(GlobalVariable *&GCL) {
1921   std::vector<Function*> Ctors = ParseGlobalCtors(GCL);
1922   bool MadeChange = false;
1923   if (Ctors.empty()) return false;
1924   
1925   // Loop over global ctors, optimizing them when we can.
1926   for (unsigned i = 0; i != Ctors.size(); ++i) {
1927     Function *F = Ctors[i];
1928     // Found a null terminator in the middle of the list, prune off the rest of
1929     // the list.
1930     if (F == 0) {
1931       if (i != Ctors.size()-1) {
1932         Ctors.resize(i+1);
1933         MadeChange = true;
1934       }
1935       break;
1936     }
1937     
1938     // We cannot simplify external ctor functions.
1939     if (F->empty()) continue;
1940     
1941     // If we can evaluate the ctor at compile time, do.
1942     if (EvaluateStaticConstructor(F)) {
1943       Ctors.erase(Ctors.begin()+i);
1944       MadeChange = true;
1945       --i;
1946       ++NumCtorsEvaluated;
1947       continue;
1948     }
1949   }
1950   
1951   if (!MadeChange) return false;
1952   
1953   GCL = InstallGlobalCtors(GCL, Ctors);
1954   return true;
1955 }
1956
1957
1958 bool GlobalOpt::runOnModule(Module &M) {
1959   bool Changed = false;
1960   
1961   // Try to find the llvm.globalctors list.
1962   GlobalVariable *GlobalCtors = FindGlobalCtors(M);
1963
1964   bool LocalChange = true;
1965   while (LocalChange) {
1966     LocalChange = false;
1967     
1968     // Delete functions that are trivially dead, ccc -> fastcc
1969     LocalChange |= OptimizeFunctions(M);
1970     
1971     // Optimize global_ctors list.
1972     if (GlobalCtors)
1973       LocalChange |= OptimizeGlobalCtorsList(GlobalCtors);
1974     
1975     // Optimize non-address-taken globals.
1976     LocalChange |= OptimizeGlobalVars(M);
1977     Changed |= LocalChange;
1978   }
1979   
1980   // TODO: Move all global ctors functions to the end of the module for code
1981   // layout.
1982   
1983   return Changed;
1984 }