Update GEP constructors to use an iterator interface to fix
[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.begin(), Idxs.end(),
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       // If we get here we could have stores, selects, or phi nodes whose values
627       // are loaded.
628       assert((isa<StoreInst>(*GUI) || isa<PHINode>(*GUI) ||
629               isa<SelectInst>(*GUI)) &&
630              "Only expect load and stores!");
631     }
632
633   if (Changed) {
634     DOUT << "OPTIMIZED LOADS FROM STORED ONCE POINTER: " << *GV;
635     ++NumGlobUses;
636   }
637
638   // Delete all of the loads we can, keeping track of whether we nuked them all!
639   bool AllLoadsGone = true;
640   while (!Loads.empty()) {
641     LoadInst *L = Loads.back();
642     if (L->use_empty()) {
643       L->eraseFromParent();
644       Changed = true;
645     } else {
646       AllLoadsGone = false;
647     }
648     Loads.pop_back();
649   }
650
651   // If we nuked all of the loads, then none of the stores are needed either,
652   // nor is the global.
653   if (AllLoadsGone) {
654     DOUT << "  *** GLOBAL NOW DEAD!\n";
655     CleanupConstantGlobalUsers(GV, 0);
656     if (GV->use_empty()) {
657       GV->eraseFromParent();
658       ++NumDeleted;
659     }
660     Changed = true;
661   }
662   return Changed;
663 }
664
665 /// ConstantPropUsersOf - Walk the use list of V, constant folding all of the
666 /// instructions that are foldable.
667 static void ConstantPropUsersOf(Value *V) {
668   for (Value::use_iterator UI = V->use_begin(), E = V->use_end(); UI != E; )
669     if (Instruction *I = dyn_cast<Instruction>(*UI++))
670       if (Constant *NewC = ConstantFoldInstruction(I)) {
671         I->replaceAllUsesWith(NewC);
672
673         // Advance UI to the next non-I use to avoid invalidating it!
674         // Instructions could multiply use V.
675         while (UI != E && *UI == I)
676           ++UI;
677         I->eraseFromParent();
678       }
679 }
680
681 /// OptimizeGlobalAddressOfMalloc - This function takes the specified global
682 /// variable, and transforms the program as if it always contained the result of
683 /// the specified malloc.  Because it is always the result of the specified
684 /// malloc, there is no reason to actually DO the malloc.  Instead, turn the
685 /// malloc into a global, and any loads of GV as uses of the new global.
686 static GlobalVariable *OptimizeGlobalAddressOfMalloc(GlobalVariable *GV,
687                                                      MallocInst *MI) {
688   DOUT << "PROMOTING MALLOC GLOBAL: " << *GV << "  MALLOC = " << *MI;
689   ConstantInt *NElements = cast<ConstantInt>(MI->getArraySize());
690
691   if (NElements->getZExtValue() != 1) {
692     // If we have an array allocation, transform it to a single element
693     // allocation to make the code below simpler.
694     Type *NewTy = ArrayType::get(MI->getAllocatedType(),
695                                  NElements->getZExtValue());
696     MallocInst *NewMI =
697       new MallocInst(NewTy, Constant::getNullValue(Type::Int32Ty),
698                      MI->getAlignment(), MI->getName(), MI);
699     Value* Indices[2];
700     Indices[0] = Indices[1] = Constant::getNullValue(Type::Int32Ty);
701     Value *NewGEP = new GetElementPtrInst(NewMI, Indices, Indices + 2,
702                                           NewMI->getName()+".el0", MI);
703     MI->replaceAllUsesWith(NewGEP);
704     MI->eraseFromParent();
705     MI = NewMI;
706   }
707
708   // Create the new global variable.  The contents of the malloc'd memory is
709   // undefined, so initialize with an undef value.
710   Constant *Init = UndefValue::get(MI->getAllocatedType());
711   GlobalVariable *NewGV = new GlobalVariable(MI->getAllocatedType(), false,
712                                              GlobalValue::InternalLinkage, Init,
713                                              GV->getName()+".body",
714                                              (Module *)NULL,
715                                              GV->isThreadLocal());
716   GV->getParent()->getGlobalList().insert(GV, NewGV);
717
718   // Anything that used the malloc now uses the global directly.
719   MI->replaceAllUsesWith(NewGV);
720
721   Constant *RepValue = NewGV;
722   if (NewGV->getType() != GV->getType()->getElementType())
723     RepValue = ConstantExpr::getBitCast(RepValue, 
724                                         GV->getType()->getElementType());
725
726   // If there is a comparison against null, we will insert a global bool to
727   // keep track of whether the global was initialized yet or not.
728   GlobalVariable *InitBool =
729     new GlobalVariable(Type::Int1Ty, false, GlobalValue::InternalLinkage,
730                        ConstantInt::getFalse(), GV->getName()+".init",
731                        (Module *)NULL, GV->isThreadLocal());
732   bool InitBoolUsed = false;
733
734   // Loop over all uses of GV, processing them in turn.
735   std::vector<StoreInst*> Stores;
736   while (!GV->use_empty())
737     if (LoadInst *LI = dyn_cast<LoadInst>(GV->use_back())) {
738       while (!LI->use_empty()) {
739         Use &LoadUse = LI->use_begin().getUse();
740         if (!isa<ICmpInst>(LoadUse.getUser()))
741           LoadUse = RepValue;
742         else {
743           ICmpInst *CI = cast<ICmpInst>(LoadUse.getUser());
744           // Replace the cmp X, 0 with a use of the bool value.
745           Value *LV = new LoadInst(InitBool, InitBool->getName()+".val", CI);
746           InitBoolUsed = true;
747           switch (CI->getPredicate()) {
748           default: assert(0 && "Unknown ICmp Predicate!");
749           case ICmpInst::ICMP_ULT:
750           case ICmpInst::ICMP_SLT:
751             LV = ConstantInt::getFalse();   // X < null -> always false
752             break;
753           case ICmpInst::ICMP_ULE:
754           case ICmpInst::ICMP_SLE:
755           case ICmpInst::ICMP_EQ:
756             LV = BinaryOperator::createNot(LV, "notinit", CI);
757             break;
758           case ICmpInst::ICMP_NE:
759           case ICmpInst::ICMP_UGE:
760           case ICmpInst::ICMP_SGE:
761           case ICmpInst::ICMP_UGT:
762           case ICmpInst::ICMP_SGT:
763             break;  // no change.
764           }
765           CI->replaceAllUsesWith(LV);
766           CI->eraseFromParent();
767         }
768       }
769       LI->eraseFromParent();
770     } else {
771       StoreInst *SI = cast<StoreInst>(GV->use_back());
772       // The global is initialized when the store to it occurs.
773       new StoreInst(ConstantInt::getTrue(), InitBool, SI);
774       SI->eraseFromParent();
775     }
776
777   // If the initialization boolean was used, insert it, otherwise delete it.
778   if (!InitBoolUsed) {
779     while (!InitBool->use_empty())  // Delete initializations
780       cast<Instruction>(InitBool->use_back())->eraseFromParent();
781     delete InitBool;
782   } else
783     GV->getParent()->getGlobalList().insert(GV, InitBool);
784
785
786   // Now the GV is dead, nuke it and the malloc.
787   GV->eraseFromParent();
788   MI->eraseFromParent();
789
790   // To further other optimizations, loop over all users of NewGV and try to
791   // constant prop them.  This will promote GEP instructions with constant
792   // indices into GEP constant-exprs, which will allow global-opt to hack on it.
793   ConstantPropUsersOf(NewGV);
794   if (RepValue != NewGV)
795     ConstantPropUsersOf(RepValue);
796
797   return NewGV;
798 }
799
800 /// ValueIsOnlyUsedLocallyOrStoredToOneGlobal - Scan the use-list of V checking
801 /// to make sure that there are no complex uses of V.  We permit simple things
802 /// like dereferencing the pointer, but not storing through the address, unless
803 /// it is to the specified global.
804 static bool ValueIsOnlyUsedLocallyOrStoredToOneGlobal(Instruction *V,
805                                                       GlobalVariable *GV) {
806   for (Value::use_iterator UI = V->use_begin(), E = V->use_end(); UI != E;++UI)
807     if (isa<LoadInst>(*UI) || isa<CmpInst>(*UI)) {
808       // Fine, ignore.
809     } else if (StoreInst *SI = dyn_cast<StoreInst>(*UI)) {
810       if (SI->getOperand(0) == V && SI->getOperand(1) != GV)
811         return false;  // Storing the pointer itself... bad.
812       // Otherwise, storing through it, or storing into GV... fine.
813     } else if (isa<GetElementPtrInst>(*UI) || isa<SelectInst>(*UI)) {
814       if (!ValueIsOnlyUsedLocallyOrStoredToOneGlobal(cast<Instruction>(*UI),GV))
815         return false;
816     } else {
817       return false;
818     }
819   return true;
820 }
821
822 /// ReplaceUsesOfMallocWithGlobal - The Alloc pointer is stored into GV
823 /// somewhere.  Transform all uses of the allocation into loads from the
824 /// global and uses of the resultant pointer.  Further, delete the store into
825 /// GV.  This assumes that these value pass the 
826 /// 'ValueIsOnlyUsedLocallyOrStoredToOneGlobal' predicate.
827 static void ReplaceUsesOfMallocWithGlobal(Instruction *Alloc, 
828                                           GlobalVariable *GV) {
829   while (!Alloc->use_empty()) {
830     Instruction *U = Alloc->use_back();
831     if (StoreInst *SI = dyn_cast<StoreInst>(U)) {
832       // If this is the store of the allocation into the global, remove it.
833       if (SI->getOperand(1) == GV) {
834         SI->eraseFromParent();
835         continue;
836       }
837     }
838     
839     // Insert a load from the global, and use it instead of the malloc.
840     Value *NL = new LoadInst(GV, GV->getName()+".val", U);
841     U->replaceUsesOfWith(Alloc, NL);
842   }
843 }
844
845 /// GlobalLoadUsesSimpleEnoughForHeapSRA - If all users of values loaded from
846 /// GV are simple enough to perform HeapSRA, return true.
847 static bool GlobalLoadUsesSimpleEnoughForHeapSRA(GlobalVariable *GV) {
848   for (Value::use_iterator UI = GV->use_begin(), E = GV->use_end(); UI != E; 
849        ++UI)
850     if (LoadInst *LI = dyn_cast<LoadInst>(*UI)) {
851       // We permit two users of the load: setcc comparing against the null
852       // pointer, and a getelementptr of a specific form.
853       for (Value::use_iterator UI = LI->use_begin(), E = LI->use_end(); UI != E; 
854            ++UI) {
855         // Comparison against null is ok.
856         if (ICmpInst *ICI = dyn_cast<ICmpInst>(*UI)) {
857           if (!isa<ConstantPointerNull>(ICI->getOperand(1)))
858             return false;
859           continue;
860         }
861         
862         // getelementptr is also ok, but only a simple form.
863         GetElementPtrInst *GEPI = dyn_cast<GetElementPtrInst>(*UI);
864         if (!GEPI) return false;
865         
866         // Must index into the array and into the struct.
867         if (GEPI->getNumOperands() < 3)
868           return false;
869         
870         // Otherwise the GEP is ok.
871         continue;
872       }
873     }
874   return true;
875 }
876
877 /// RewriteUsesOfLoadForHeapSRoA - We are performing Heap SRoA on a global.  Ptr
878 /// is a value loaded from the global.  Eliminate all uses of Ptr, making them
879 /// use FieldGlobals instead.  All uses of loaded values satisfy
880 /// GlobalLoadUsesSimpleEnoughForHeapSRA.
881 static void RewriteUsesOfLoadForHeapSRoA(LoadInst *Ptr, 
882                              const std::vector<GlobalVariable*> &FieldGlobals) {
883   std::vector<Value *> InsertedLoadsForPtr;
884   //InsertedLoadsForPtr.resize(FieldGlobals.size());
885   while (!Ptr->use_empty()) {
886     Instruction *User = Ptr->use_back();
887     
888     // If this is a comparison against null, handle it.
889     if (ICmpInst *SCI = dyn_cast<ICmpInst>(User)) {
890       assert(isa<ConstantPointerNull>(SCI->getOperand(1)));
891       // If we have a setcc of the loaded pointer, we can use a setcc of any
892       // field.
893       Value *NPtr;
894       if (InsertedLoadsForPtr.empty()) {
895         NPtr = new LoadInst(FieldGlobals[0], Ptr->getName()+".f0", Ptr);
896         InsertedLoadsForPtr.push_back(Ptr);
897       } else {
898         NPtr = InsertedLoadsForPtr.back();
899       }
900       
901       Value *New = new ICmpInst(SCI->getPredicate(), NPtr,
902                                 Constant::getNullValue(NPtr->getType()),
903                                 SCI->getName(), SCI);
904       SCI->replaceAllUsesWith(New);
905       SCI->eraseFromParent();
906       continue;
907     }
908     
909     // Otherwise, this should be: 'getelementptr Ptr, Idx, uint FieldNo ...'
910     GetElementPtrInst *GEPI = cast<GetElementPtrInst>(User);
911     assert(GEPI->getNumOperands() >= 3 && isa<ConstantInt>(GEPI->getOperand(2))
912            && "Unexpected GEPI!");
913     
914     // Load the pointer for this field.
915     unsigned FieldNo = cast<ConstantInt>(GEPI->getOperand(2))->getZExtValue();
916     if (InsertedLoadsForPtr.size() <= FieldNo)
917       InsertedLoadsForPtr.resize(FieldNo+1);
918     if (InsertedLoadsForPtr[FieldNo] == 0)
919       InsertedLoadsForPtr[FieldNo] = new LoadInst(FieldGlobals[FieldNo],
920                                                   Ptr->getName()+".f" + 
921                                                   utostr(FieldNo), Ptr);
922     Value *NewPtr = InsertedLoadsForPtr[FieldNo];
923
924     // Create the new GEP idx vector.
925     SmallVector<Value*, 8> GEPIdx;
926     GEPIdx.push_back(GEPI->getOperand(1));
927     GEPIdx.append(GEPI->op_begin()+3, GEPI->op_end());
928
929     Value *NGEPI = new GetElementPtrInst(NewPtr, GEPIdx.begin(), GEPIdx.end(),
930                                          GEPI->getName(), GEPI);
931     GEPI->replaceAllUsesWith(NGEPI);
932     GEPI->eraseFromParent();
933   }
934 }
935
936 /// PerformHeapAllocSRoA - MI is an allocation of an array of structures.  Break
937 /// it up into multiple allocations of arrays of the fields.
938 static GlobalVariable *PerformHeapAllocSRoA(GlobalVariable *GV, MallocInst *MI){
939   DOUT << "SROA HEAP ALLOC: " << *GV << "  MALLOC = " << *MI;
940   const StructType *STy = cast<StructType>(MI->getAllocatedType());
941
942   // There is guaranteed to be at least one use of the malloc (storing
943   // it into GV).  If there are other uses, change them to be uses of
944   // the global to simplify later code.  This also deletes the store
945   // into GV.
946   ReplaceUsesOfMallocWithGlobal(MI, GV);
947   
948   // Okay, at this point, there are no users of the malloc.  Insert N
949   // new mallocs at the same place as MI, and N globals.
950   std::vector<GlobalVariable*> FieldGlobals;
951   std::vector<MallocInst*> FieldMallocs;
952   
953   for (unsigned FieldNo = 0, e = STy->getNumElements(); FieldNo != e;++FieldNo){
954     const Type *FieldTy = STy->getElementType(FieldNo);
955     const Type *PFieldTy = PointerType::get(FieldTy);
956     
957     GlobalVariable *NGV =
958       new GlobalVariable(PFieldTy, false, GlobalValue::InternalLinkage,
959                          Constant::getNullValue(PFieldTy),
960                          GV->getName() + ".f" + utostr(FieldNo), GV,
961                          GV->isThreadLocal());
962     FieldGlobals.push_back(NGV);
963     
964     MallocInst *NMI = new MallocInst(FieldTy, MI->getArraySize(),
965                                      MI->getName() + ".f" + utostr(FieldNo),MI);
966     FieldMallocs.push_back(NMI);
967     new StoreInst(NMI, NGV, MI);
968   }
969   
970   // The tricky aspect of this transformation is handling the case when malloc
971   // fails.  In the original code, malloc failing would set the result pointer
972   // of malloc to null.  In this case, some mallocs could succeed and others
973   // could fail.  As such, we emit code that looks like this:
974   //    F0 = malloc(field0)
975   //    F1 = malloc(field1)
976   //    F2 = malloc(field2)
977   //    if (F0 == 0 || F1 == 0 || F2 == 0) {
978   //      if (F0) { free(F0); F0 = 0; }
979   //      if (F1) { free(F1); F1 = 0; }
980   //      if (F2) { free(F2); F2 = 0; }
981   //    }
982   Value *RunningOr = 0;
983   for (unsigned i = 0, e = FieldMallocs.size(); i != e; ++i) {
984     Value *Cond = new ICmpInst(ICmpInst::ICMP_EQ, FieldMallocs[i],
985                              Constant::getNullValue(FieldMallocs[i]->getType()),
986                                   "isnull", MI);
987     if (!RunningOr)
988       RunningOr = Cond;   // First seteq
989     else
990       RunningOr = BinaryOperator::createOr(RunningOr, Cond, "tmp", MI);
991   }
992
993   // Split the basic block at the old malloc.
994   BasicBlock *OrigBB = MI->getParent();
995   BasicBlock *ContBB = OrigBB->splitBasicBlock(MI, "malloc_cont");
996   
997   // Create the block to check the first condition.  Put all these blocks at the
998   // end of the function as they are unlikely to be executed.
999   BasicBlock *NullPtrBlock = new BasicBlock("malloc_ret_null",
1000                                             OrigBB->getParent());
1001   
1002   // Remove the uncond branch from OrigBB to ContBB, turning it into a cond
1003   // branch on RunningOr.
1004   OrigBB->getTerminator()->eraseFromParent();
1005   new BranchInst(NullPtrBlock, ContBB, RunningOr, OrigBB);
1006   
1007   // Within the NullPtrBlock, we need to emit a comparison and branch for each
1008   // pointer, because some may be null while others are not.
1009   for (unsigned i = 0, e = FieldGlobals.size(); i != e; ++i) {
1010     Value *GVVal = new LoadInst(FieldGlobals[i], "tmp", NullPtrBlock);
1011     Value *Cmp = new ICmpInst(ICmpInst::ICMP_NE, GVVal, 
1012                               Constant::getNullValue(GVVal->getType()),
1013                               "tmp", NullPtrBlock);
1014     BasicBlock *FreeBlock = new BasicBlock("free_it", OrigBB->getParent());
1015     BasicBlock *NextBlock = new BasicBlock("next", OrigBB->getParent());
1016     new BranchInst(FreeBlock, NextBlock, Cmp, NullPtrBlock);
1017
1018     // Fill in FreeBlock.
1019     new FreeInst(GVVal, FreeBlock);
1020     new StoreInst(Constant::getNullValue(GVVal->getType()), FieldGlobals[i],
1021                   FreeBlock);
1022     new BranchInst(NextBlock, FreeBlock);
1023     
1024     NullPtrBlock = NextBlock;
1025   }
1026   
1027   new BranchInst(ContBB, NullPtrBlock);
1028   
1029   
1030   // MI is no longer needed, remove it.
1031   MI->eraseFromParent();
1032
1033   
1034   // Okay, the malloc site is completely handled.  All of the uses of GV are now
1035   // loads, and all uses of those loads are simple.  Rewrite them to use loads
1036   // of the per-field globals instead.
1037   while (!GV->use_empty()) {
1038     if (LoadInst *LI = dyn_cast<LoadInst>(GV->use_back())) {
1039       RewriteUsesOfLoadForHeapSRoA(LI, FieldGlobals);
1040       LI->eraseFromParent();
1041     } else {
1042       // Must be a store of null.
1043       StoreInst *SI = cast<StoreInst>(GV->use_back());
1044       assert(isa<Constant>(SI->getOperand(0)) &&
1045              cast<Constant>(SI->getOperand(0))->isNullValue() &&
1046              "Unexpected heap-sra user!");
1047       
1048       // Insert a store of null into each global.
1049       for (unsigned i = 0, e = FieldGlobals.size(); i != e; ++i) {
1050         Constant *Null = 
1051           Constant::getNullValue(FieldGlobals[i]->getType()->getElementType());
1052         new StoreInst(Null, FieldGlobals[i], SI);
1053       }
1054       // Erase the original store.
1055       SI->eraseFromParent();
1056     }
1057   }
1058
1059   // The old global is now dead, remove it.
1060   GV->eraseFromParent();
1061
1062   ++NumHeapSRA;
1063   return FieldGlobals[0];
1064 }
1065
1066
1067 // OptimizeOnceStoredGlobal - Try to optimize globals based on the knowledge
1068 // that only one value (besides its initializer) is ever stored to the global.
1069 static bool OptimizeOnceStoredGlobal(GlobalVariable *GV, Value *StoredOnceVal,
1070                                      Module::global_iterator &GVI,
1071                                      TargetData &TD) {
1072   if (CastInst *CI = dyn_cast<CastInst>(StoredOnceVal))
1073     StoredOnceVal = CI->getOperand(0);
1074   else if (GetElementPtrInst *GEPI =dyn_cast<GetElementPtrInst>(StoredOnceVal)){
1075     // "getelementptr Ptr, 0, 0, 0" is really just a cast.
1076     bool IsJustACast = true;
1077     for (unsigned i = 1, e = GEPI->getNumOperands(); i != e; ++i)
1078       if (!isa<Constant>(GEPI->getOperand(i)) ||
1079           !cast<Constant>(GEPI->getOperand(i))->isNullValue()) {
1080         IsJustACast = false;
1081         break;
1082       }
1083     if (IsJustACast)
1084       StoredOnceVal = GEPI->getOperand(0);
1085   }
1086
1087   // If we are dealing with a pointer global that is initialized to null and
1088   // only has one (non-null) value stored into it, then we can optimize any
1089   // users of the loaded value (often calls and loads) that would trap if the
1090   // value was null.
1091   if (isa<PointerType>(GV->getInitializer()->getType()) &&
1092       GV->getInitializer()->isNullValue()) {
1093     if (Constant *SOVC = dyn_cast<Constant>(StoredOnceVal)) {
1094       if (GV->getInitializer()->getType() != SOVC->getType())
1095         SOVC = ConstantExpr::getBitCast(SOVC, GV->getInitializer()->getType());
1096
1097       // Optimize away any trapping uses of the loaded value.
1098       if (OptimizeAwayTrappingUsesOfLoads(GV, SOVC))
1099         return true;
1100     } else if (MallocInst *MI = dyn_cast<MallocInst>(StoredOnceVal)) {
1101       // If this is a malloc of an abstract type, don't touch it.
1102       if (!MI->getAllocatedType()->isSized())
1103         return false;
1104       
1105       // We can't optimize this global unless all uses of it are *known* to be
1106       // of the malloc value, not of the null initializer value (consider a use
1107       // that compares the global's value against zero to see if the malloc has
1108       // been reached).  To do this, we check to see if all uses of the global
1109       // would trap if the global were null: this proves that they must all
1110       // happen after the malloc.
1111       if (!AllUsesOfLoadedValueWillTrapIfNull(GV))
1112         return false;
1113
1114       // We can't optimize this if the malloc itself is used in a complex way,
1115       // for example, being stored into multiple globals.  This allows the
1116       // malloc to be stored into the specified global, loaded setcc'd, and
1117       // GEP'd.  These are all things we could transform to using the global
1118       // for.
1119       if (!ValueIsOnlyUsedLocallyOrStoredToOneGlobal(MI, GV))
1120         return false;
1121
1122       
1123       // If we have a global that is only initialized with a fixed size malloc,
1124       // transform the program to use global memory instead of malloc'd memory.
1125       // This eliminates dynamic allocation, avoids an indirection accessing the
1126       // data, and exposes the resultant global to further GlobalOpt.
1127       if (ConstantInt *NElements = dyn_cast<ConstantInt>(MI->getArraySize())) {
1128         // Restrict this transformation to only working on small allocations
1129         // (2048 bytes currently), as we don't want to introduce a 16M global or
1130         // something.
1131         if (NElements->getZExtValue()*
1132                      TD.getTypeSize(MI->getAllocatedType()) < 2048) {
1133           GVI = OptimizeGlobalAddressOfMalloc(GV, MI);
1134           return true;
1135         }
1136       }
1137
1138       // If the allocation is an array of structures, consider transforming this
1139       // into multiple malloc'd arrays, one for each field.  This is basically
1140       // SRoA for malloc'd memory.
1141       if (const StructType *AllocTy = 
1142                   dyn_cast<StructType>(MI->getAllocatedType())) {
1143         // This the structure has an unreasonable number of fields, leave it
1144         // alone.
1145         if (AllocTy->getNumElements() <= 16 && AllocTy->getNumElements() > 0 &&
1146             GlobalLoadUsesSimpleEnoughForHeapSRA(GV)) {
1147           GVI = PerformHeapAllocSRoA(GV, MI);
1148           return true;
1149         }
1150       }
1151     }
1152   }
1153
1154   return false;
1155 }
1156
1157 /// ShrinkGlobalToBoolean - At this point, we have learned that the only two
1158 /// values ever stored into GV are its initializer and OtherVal.
1159 static void ShrinkGlobalToBoolean(GlobalVariable *GV, Constant *OtherVal) {
1160   // Create the new global, initializing it to false.
1161   GlobalVariable *NewGV = new GlobalVariable(Type::Int1Ty, false,
1162          GlobalValue::InternalLinkage, ConstantInt::getFalse(),
1163                                              GV->getName()+".b",
1164                                              (Module *)NULL,
1165                                              GV->isThreadLocal());
1166   GV->getParent()->getGlobalList().insert(GV, NewGV);
1167
1168   Constant *InitVal = GV->getInitializer();
1169   assert(InitVal->getType() != Type::Int1Ty && "No reason to shrink to bool!");
1170
1171   // If initialized to zero and storing one into the global, we can use a cast
1172   // instead of a select to synthesize the desired value.
1173   bool IsOneZero = false;
1174   if (ConstantInt *CI = dyn_cast<ConstantInt>(OtherVal))
1175     IsOneZero = InitVal->isNullValue() && CI->isOne();
1176
1177   while (!GV->use_empty()) {
1178     Instruction *UI = cast<Instruction>(GV->use_back());
1179     if (StoreInst *SI = dyn_cast<StoreInst>(UI)) {
1180       // Change the store into a boolean store.
1181       bool StoringOther = SI->getOperand(0) == OtherVal;
1182       // Only do this if we weren't storing a loaded value.
1183       Value *StoreVal;
1184       if (StoringOther || SI->getOperand(0) == InitVal)
1185         StoreVal = ConstantInt::get(Type::Int1Ty, StoringOther);
1186       else {
1187         // Otherwise, we are storing a previously loaded copy.  To do this,
1188         // change the copy from copying the original value to just copying the
1189         // bool.
1190         Instruction *StoredVal = cast<Instruction>(SI->getOperand(0));
1191
1192         // If we're already replaced the input, StoredVal will be a cast or
1193         // select instruction.  If not, it will be a load of the original
1194         // global.
1195         if (LoadInst *LI = dyn_cast<LoadInst>(StoredVal)) {
1196           assert(LI->getOperand(0) == GV && "Not a copy!");
1197           // Insert a new load, to preserve the saved value.
1198           StoreVal = new LoadInst(NewGV, LI->getName()+".b", LI);
1199         } else {
1200           assert((isa<CastInst>(StoredVal) || isa<SelectInst>(StoredVal)) &&
1201                  "This is not a form that we understand!");
1202           StoreVal = StoredVal->getOperand(0);
1203           assert(isa<LoadInst>(StoreVal) && "Not a load of NewGV!");
1204         }
1205       }
1206       new StoreInst(StoreVal, NewGV, SI);
1207     } else if (!UI->use_empty()) {
1208       // Change the load into a load of bool then a select.
1209       LoadInst *LI = cast<LoadInst>(UI);
1210       LoadInst *NLI = new LoadInst(NewGV, LI->getName()+".b", LI);
1211       Value *NSI;
1212       if (IsOneZero)
1213         NSI = new ZExtInst(NLI, LI->getType(), "", LI);
1214       else
1215         NSI = new SelectInst(NLI, OtherVal, InitVal, "", LI);
1216       NSI->takeName(LI);
1217       LI->replaceAllUsesWith(NSI);
1218     }
1219     UI->eraseFromParent();
1220   }
1221
1222   GV->eraseFromParent();
1223 }
1224
1225
1226 /// ProcessInternalGlobal - Analyze the specified global variable and optimize
1227 /// it if possible.  If we make a change, return true.
1228 bool GlobalOpt::ProcessInternalGlobal(GlobalVariable *GV,
1229                                       Module::global_iterator &GVI) {
1230   std::set<PHINode*> PHIUsers;
1231   GlobalStatus GS;
1232   GV->removeDeadConstantUsers();
1233
1234   if (GV->use_empty()) {
1235     DOUT << "GLOBAL DEAD: " << *GV;
1236     GV->eraseFromParent();
1237     ++NumDeleted;
1238     return true;
1239   }
1240
1241   if (!AnalyzeGlobal(GV, GS, PHIUsers)) {
1242 #if 0
1243     cerr << "Global: " << *GV;
1244     cerr << "  isLoaded = " << GS.isLoaded << "\n";
1245     cerr << "  StoredType = ";
1246     switch (GS.StoredType) {
1247     case GlobalStatus::NotStored: cerr << "NEVER STORED\n"; break;
1248     case GlobalStatus::isInitializerStored: cerr << "INIT STORED\n"; break;
1249     case GlobalStatus::isStoredOnce: cerr << "STORED ONCE\n"; break;
1250     case GlobalStatus::isStored: cerr << "stored\n"; break;
1251     }
1252     if (GS.StoredType == GlobalStatus::isStoredOnce && GS.StoredOnceValue)
1253       cerr << "  StoredOnceValue = " << *GS.StoredOnceValue << "\n";
1254     if (GS.AccessingFunction && !GS.HasMultipleAccessingFunctions)
1255       cerr << "  AccessingFunction = " << GS.AccessingFunction->getName()
1256                 << "\n";
1257     cerr << "  HasMultipleAccessingFunctions =  "
1258               << GS.HasMultipleAccessingFunctions << "\n";
1259     cerr << "  HasNonInstructionUser = " << GS.HasNonInstructionUser<<"\n";
1260     cerr << "  isNotSuitableForSRA = " << GS.isNotSuitableForSRA << "\n";
1261     cerr << "\n";
1262 #endif
1263     
1264     // If this is a first class global and has only one accessing function
1265     // and this function is main (which we know is not recursive we can make
1266     // this global a local variable) we replace the global with a local alloca
1267     // in this function.
1268     //
1269     // NOTE: It doesn't make sense to promote non first class types since we
1270     // are just replacing static memory to stack memory.
1271     if (!GS.HasMultipleAccessingFunctions &&
1272         GS.AccessingFunction && !GS.HasNonInstructionUser &&
1273         GV->getType()->getElementType()->isFirstClassType() &&
1274         GS.AccessingFunction->getName() == "main" &&
1275         GS.AccessingFunction->hasExternalLinkage()) {
1276       DOUT << "LOCALIZING GLOBAL: " << *GV;
1277       Instruction* FirstI = GS.AccessingFunction->getEntryBlock().begin();
1278       const Type* ElemTy = GV->getType()->getElementType();
1279       // FIXME: Pass Global's alignment when globals have alignment
1280       AllocaInst* Alloca = new AllocaInst(ElemTy, NULL, GV->getName(), FirstI);
1281       if (!isa<UndefValue>(GV->getInitializer()))
1282         new StoreInst(GV->getInitializer(), Alloca, FirstI);
1283
1284       GV->replaceAllUsesWith(Alloca);
1285       GV->eraseFromParent();
1286       ++NumLocalized;
1287       return true;
1288     }
1289     
1290     // If the global is never loaded (but may be stored to), it is dead.
1291     // Delete it now.
1292     if (!GS.isLoaded) {
1293       DOUT << "GLOBAL NEVER LOADED: " << *GV;
1294
1295       // Delete any stores we can find to the global.  We may not be able to
1296       // make it completely dead though.
1297       bool Changed = CleanupConstantGlobalUsers(GV, GV->getInitializer());
1298
1299       // If the global is dead now, delete it.
1300       if (GV->use_empty()) {
1301         GV->eraseFromParent();
1302         ++NumDeleted;
1303         Changed = true;
1304       }
1305       return Changed;
1306
1307     } else if (GS.StoredType <= GlobalStatus::isInitializerStored) {
1308       DOUT << "MARKING CONSTANT: " << *GV;
1309       GV->setConstant(true);
1310
1311       // Clean up any obviously simplifiable users now.
1312       CleanupConstantGlobalUsers(GV, GV->getInitializer());
1313
1314       // If the global is dead now, just nuke it.
1315       if (GV->use_empty()) {
1316         DOUT << "   *** Marking constant allowed us to simplify "
1317              << "all users and delete global!\n";
1318         GV->eraseFromParent();
1319         ++NumDeleted;
1320       }
1321
1322       ++NumMarked;
1323       return true;
1324     } else if (!GS.isNotSuitableForSRA &&
1325                !GV->getInitializer()->getType()->isFirstClassType()) {
1326       if (GlobalVariable *FirstNewGV = SRAGlobal(GV)) {
1327         GVI = FirstNewGV;  // Don't skip the newly produced globals!
1328         return true;
1329       }
1330     } else if (GS.StoredType == GlobalStatus::isStoredOnce) {
1331       // If the initial value for the global was an undef value, and if only
1332       // one other value was stored into it, we can just change the
1333       // initializer to be an undef value, then delete all stores to the
1334       // global.  This allows us to mark it constant.
1335       if (Constant *SOVConstant = dyn_cast<Constant>(GS.StoredOnceValue))
1336         if (isa<UndefValue>(GV->getInitializer())) {
1337           // Change the initial value here.
1338           GV->setInitializer(SOVConstant);
1339
1340           // Clean up any obviously simplifiable users now.
1341           CleanupConstantGlobalUsers(GV, GV->getInitializer());
1342
1343           if (GV->use_empty()) {
1344             DOUT << "   *** Substituting initializer allowed us to "
1345                  << "simplify all users and delete global!\n";
1346             GV->eraseFromParent();
1347             ++NumDeleted;
1348           } else {
1349             GVI = GV;
1350           }
1351           ++NumSubstitute;
1352           return true;
1353         }
1354
1355       // Try to optimize globals based on the knowledge that only one value
1356       // (besides its initializer) is ever stored to the global.
1357       if (OptimizeOnceStoredGlobal(GV, GS.StoredOnceValue, GVI,
1358                                    getAnalysis<TargetData>()))
1359         return true;
1360
1361       // Otherwise, if the global was not a boolean, we can shrink it to be a
1362       // boolean.
1363       if (Constant *SOVConstant = dyn_cast<Constant>(GS.StoredOnceValue))
1364         if (GV->getType()->getElementType() != Type::Int1Ty &&
1365             !GV->getType()->getElementType()->isFloatingPoint() &&
1366             !isa<VectorType>(GV->getType()->getElementType()) &&
1367             !GS.HasPHIUser && !GS.isNotSuitableForSRA) {
1368           DOUT << "   *** SHRINKING TO BOOL: " << *GV;
1369           ShrinkGlobalToBoolean(GV, SOVConstant);
1370           ++NumShrunkToBool;
1371           return true;
1372         }
1373     }
1374   }
1375   return false;
1376 }
1377
1378 /// OnlyCalledDirectly - Return true if the specified function is only called
1379 /// directly.  In other words, its address is never taken.
1380 static bool OnlyCalledDirectly(Function *F) {
1381   for (Value::use_iterator UI = F->use_begin(), E = F->use_end(); UI != E;++UI){
1382     Instruction *User = dyn_cast<Instruction>(*UI);
1383     if (!User) return false;
1384     if (!isa<CallInst>(User) && !isa<InvokeInst>(User)) return false;
1385
1386     // See if the function address is passed as an argument.
1387     for (unsigned i = 1, e = User->getNumOperands(); i != e; ++i)
1388       if (User->getOperand(i) == F) return false;
1389   }
1390   return true;
1391 }
1392
1393 /// ChangeCalleesToFastCall - Walk all of the direct calls of the specified
1394 /// function, changing them to FastCC.
1395 static void ChangeCalleesToFastCall(Function *F) {
1396   for (Value::use_iterator UI = F->use_begin(), E = F->use_end(); UI != E;++UI){
1397     Instruction *User = cast<Instruction>(*UI);
1398     if (CallInst *CI = dyn_cast<CallInst>(User))
1399       CI->setCallingConv(CallingConv::Fast);
1400     else
1401       cast<InvokeInst>(User)->setCallingConv(CallingConv::Fast);
1402   }
1403 }
1404
1405 bool GlobalOpt::OptimizeFunctions(Module &M) {
1406   bool Changed = false;
1407   // Optimize functions.
1408   for (Module::iterator FI = M.begin(), E = M.end(); FI != E; ) {
1409     Function *F = FI++;
1410     F->removeDeadConstantUsers();
1411     if (F->use_empty() && (F->hasInternalLinkage() ||
1412                            F->hasLinkOnceLinkage())) {
1413       M.getFunctionList().erase(F);
1414       Changed = true;
1415       ++NumFnDeleted;
1416     } else if (F->hasInternalLinkage() &&
1417                F->getCallingConv() == CallingConv::C &&  !F->isVarArg() &&
1418                OnlyCalledDirectly(F)) {
1419       // If this function has C calling conventions, is not a varargs
1420       // function, and is only called directly, promote it to use the Fast
1421       // calling convention.
1422       F->setCallingConv(CallingConv::Fast);
1423       ChangeCalleesToFastCall(F);
1424       ++NumFastCallFns;
1425       Changed = true;
1426     }
1427   }
1428   return Changed;
1429 }
1430
1431 bool GlobalOpt::OptimizeGlobalVars(Module &M) {
1432   bool Changed = false;
1433   for (Module::global_iterator GVI = M.global_begin(), E = M.global_end();
1434        GVI != E; ) {
1435     GlobalVariable *GV = GVI++;
1436     if (!GV->isConstant() && GV->hasInternalLinkage() &&
1437         GV->hasInitializer())
1438       Changed |= ProcessInternalGlobal(GV, GVI);
1439   }
1440   return Changed;
1441 }
1442
1443 /// FindGlobalCtors - Find the llvm.globalctors list, verifying that all
1444 /// initializers have an init priority of 65535.
1445 GlobalVariable *GlobalOpt::FindGlobalCtors(Module &M) {
1446   for (Module::global_iterator I = M.global_begin(), E = M.global_end();
1447        I != E; ++I)
1448     if (I->getName() == "llvm.global_ctors") {
1449       // Found it, verify it's an array of { int, void()* }.
1450       const ArrayType *ATy =dyn_cast<ArrayType>(I->getType()->getElementType());
1451       if (!ATy) return 0;
1452       const StructType *STy = dyn_cast<StructType>(ATy->getElementType());
1453       if (!STy || STy->getNumElements() != 2 ||
1454           STy->getElementType(0) != Type::Int32Ty) return 0;
1455       const PointerType *PFTy = dyn_cast<PointerType>(STy->getElementType(1));
1456       if (!PFTy) return 0;
1457       const FunctionType *FTy = dyn_cast<FunctionType>(PFTy->getElementType());
1458       if (!FTy || FTy->getReturnType() != Type::VoidTy || FTy->isVarArg() ||
1459           FTy->getNumParams() != 0)
1460         return 0;
1461       
1462       // Verify that the initializer is simple enough for us to handle.
1463       if (!I->hasInitializer()) return 0;
1464       ConstantArray *CA = dyn_cast<ConstantArray>(I->getInitializer());
1465       if (!CA) return 0;
1466       for (unsigned i = 0, e = CA->getNumOperands(); i != e; ++i)
1467         if (ConstantStruct *CS = dyn_cast<ConstantStruct>(CA->getOperand(i))) {
1468           if (isa<ConstantPointerNull>(CS->getOperand(1)))
1469             continue;
1470
1471           // Must have a function or null ptr.
1472           if (!isa<Function>(CS->getOperand(1)))
1473             return 0;
1474           
1475           // Init priority must be standard.
1476           ConstantInt *CI = dyn_cast<ConstantInt>(CS->getOperand(0));
1477           if (!CI || CI->getZExtValue() != 65535)
1478             return 0;
1479         } else {
1480           return 0;
1481         }
1482       
1483       return I;
1484     }
1485   return 0;
1486 }
1487
1488 /// ParseGlobalCtors - Given a llvm.global_ctors list that we can understand,
1489 /// return a list of the functions and null terminator as a vector.
1490 static std::vector<Function*> ParseGlobalCtors(GlobalVariable *GV) {
1491   ConstantArray *CA = cast<ConstantArray>(GV->getInitializer());
1492   std::vector<Function*> Result;
1493   Result.reserve(CA->getNumOperands());
1494   for (unsigned i = 0, e = CA->getNumOperands(); i != e; ++i) {
1495     ConstantStruct *CS = cast<ConstantStruct>(CA->getOperand(i));
1496     Result.push_back(dyn_cast<Function>(CS->getOperand(1)));
1497   }
1498   return Result;
1499 }
1500
1501 /// InstallGlobalCtors - Given a specified llvm.global_ctors list, install the
1502 /// specified array, returning the new global to use.
1503 static GlobalVariable *InstallGlobalCtors(GlobalVariable *GCL, 
1504                                           const std::vector<Function*> &Ctors) {
1505   // If we made a change, reassemble the initializer list.
1506   std::vector<Constant*> CSVals;
1507   CSVals.push_back(ConstantInt::get(Type::Int32Ty, 65535));
1508   CSVals.push_back(0);
1509   
1510   // Create the new init list.
1511   std::vector<Constant*> CAList;
1512   for (unsigned i = 0, e = Ctors.size(); i != e; ++i) {
1513     if (Ctors[i]) {
1514       CSVals[1] = Ctors[i];
1515     } else {
1516       const Type *FTy = FunctionType::get(Type::VoidTy,
1517                                           std::vector<const Type*>(), false);
1518       const PointerType *PFTy = PointerType::get(FTy);
1519       CSVals[1] = Constant::getNullValue(PFTy);
1520       CSVals[0] = ConstantInt::get(Type::Int32Ty, 2147483647);
1521     }
1522     CAList.push_back(ConstantStruct::get(CSVals));
1523   }
1524   
1525   // Create the array initializer.
1526   const Type *StructTy =
1527     cast<ArrayType>(GCL->getType()->getElementType())->getElementType();
1528   Constant *CA = ConstantArray::get(ArrayType::get(StructTy, CAList.size()),
1529                                     CAList);
1530   
1531   // If we didn't change the number of elements, don't create a new GV.
1532   if (CA->getType() == GCL->getInitializer()->getType()) {
1533     GCL->setInitializer(CA);
1534     return GCL;
1535   }
1536   
1537   // Create the new global and insert it next to the existing list.
1538   GlobalVariable *NGV = new GlobalVariable(CA->getType(), GCL->isConstant(),
1539                                            GCL->getLinkage(), CA, "",
1540                                            (Module *)NULL,
1541                                            GCL->isThreadLocal());
1542   GCL->getParent()->getGlobalList().insert(GCL, NGV);
1543   NGV->takeName(GCL);
1544   
1545   // Nuke the old list, replacing any uses with the new one.
1546   if (!GCL->use_empty()) {
1547     Constant *V = NGV;
1548     if (V->getType() != GCL->getType())
1549       V = ConstantExpr::getBitCast(V, GCL->getType());
1550     GCL->replaceAllUsesWith(V);
1551   }
1552   GCL->eraseFromParent();
1553   
1554   if (Ctors.size())
1555     return NGV;
1556   else
1557     return 0;
1558 }
1559
1560
1561 static Constant *getVal(std::map<Value*, Constant*> &ComputedValues,
1562                         Value *V) {
1563   if (Constant *CV = dyn_cast<Constant>(V)) return CV;
1564   Constant *R = ComputedValues[V];
1565   assert(R && "Reference to an uncomputed value!");
1566   return R;
1567 }
1568
1569 /// isSimpleEnoughPointerToCommit - Return true if this constant is simple
1570 /// enough for us to understand.  In particular, if it is a cast of something,
1571 /// we punt.  We basically just support direct accesses to globals and GEP's of
1572 /// globals.  This should be kept up to date with CommitValueTo.
1573 static bool isSimpleEnoughPointerToCommit(Constant *C) {
1574   if (GlobalVariable *GV = dyn_cast<GlobalVariable>(C)) {
1575     if (!GV->hasExternalLinkage() && !GV->hasInternalLinkage())
1576       return false;  // do not allow weak/linkonce/dllimport/dllexport linkage.
1577     return !GV->isDeclaration();  // reject external globals.
1578   }
1579   if (ConstantExpr *CE = dyn_cast<ConstantExpr>(C))
1580     // Handle a constantexpr gep.
1581     if (CE->getOpcode() == Instruction::GetElementPtr &&
1582         isa<GlobalVariable>(CE->getOperand(0))) {
1583       GlobalVariable *GV = cast<GlobalVariable>(CE->getOperand(0));
1584       if (!GV->hasExternalLinkage() && !GV->hasInternalLinkage())
1585         return false;  // do not allow weak/linkonce/dllimport/dllexport linkage.
1586       return GV->hasInitializer() &&
1587              ConstantFoldLoadThroughGEPConstantExpr(GV->getInitializer(), CE);
1588     }
1589   return false;
1590 }
1591
1592 /// EvaluateStoreInto - Evaluate a piece of a constantexpr store into a global
1593 /// initializer.  This returns 'Init' modified to reflect 'Val' stored into it.
1594 /// At this point, the GEP operands of Addr [0, OpNo) have been stepped into.
1595 static Constant *EvaluateStoreInto(Constant *Init, Constant *Val,
1596                                    ConstantExpr *Addr, unsigned OpNo) {
1597   // Base case of the recursion.
1598   if (OpNo == Addr->getNumOperands()) {
1599     assert(Val->getType() == Init->getType() && "Type mismatch!");
1600     return Val;
1601   }
1602   
1603   if (const StructType *STy = dyn_cast<StructType>(Init->getType())) {
1604     std::vector<Constant*> Elts;
1605
1606     // Break up the constant into its elements.
1607     if (ConstantStruct *CS = dyn_cast<ConstantStruct>(Init)) {
1608       for (unsigned i = 0, e = CS->getNumOperands(); i != e; ++i)
1609         Elts.push_back(CS->getOperand(i));
1610     } else if (isa<ConstantAggregateZero>(Init)) {
1611       for (unsigned i = 0, e = STy->getNumElements(); i != e; ++i)
1612         Elts.push_back(Constant::getNullValue(STy->getElementType(i)));
1613     } else if (isa<UndefValue>(Init)) {
1614       for (unsigned i = 0, e = STy->getNumElements(); i != e; ++i)
1615         Elts.push_back(UndefValue::get(STy->getElementType(i)));
1616     } else {
1617       assert(0 && "This code is out of sync with "
1618              " ConstantFoldLoadThroughGEPConstantExpr");
1619     }
1620     
1621     // Replace the element that we are supposed to.
1622     ConstantInt *CU = cast<ConstantInt>(Addr->getOperand(OpNo));
1623     unsigned Idx = CU->getZExtValue();
1624     assert(Idx < STy->getNumElements() && "Struct index out of range!");
1625     Elts[Idx] = EvaluateStoreInto(Elts[Idx], Val, Addr, OpNo+1);
1626     
1627     // Return the modified struct.
1628     return ConstantStruct::get(&Elts[0], Elts.size(), STy->isPacked());
1629   } else {
1630     ConstantInt *CI = cast<ConstantInt>(Addr->getOperand(OpNo));
1631     const ArrayType *ATy = cast<ArrayType>(Init->getType());
1632
1633     // Break up the array into elements.
1634     std::vector<Constant*> Elts;
1635     if (ConstantArray *CA = dyn_cast<ConstantArray>(Init)) {
1636       for (unsigned i = 0, e = CA->getNumOperands(); i != e; ++i)
1637         Elts.push_back(CA->getOperand(i));
1638     } else if (isa<ConstantAggregateZero>(Init)) {
1639       Constant *Elt = Constant::getNullValue(ATy->getElementType());
1640       Elts.assign(ATy->getNumElements(), Elt);
1641     } else if (isa<UndefValue>(Init)) {
1642       Constant *Elt = UndefValue::get(ATy->getElementType());
1643       Elts.assign(ATy->getNumElements(), Elt);
1644     } else {
1645       assert(0 && "This code is out of sync with "
1646              " ConstantFoldLoadThroughGEPConstantExpr");
1647     }
1648     
1649     assert(CI->getZExtValue() < ATy->getNumElements());
1650     Elts[CI->getZExtValue()] =
1651       EvaluateStoreInto(Elts[CI->getZExtValue()], Val, Addr, OpNo+1);
1652     return ConstantArray::get(ATy, Elts);
1653   }    
1654 }
1655
1656 /// CommitValueTo - We have decided that Addr (which satisfies the predicate
1657 /// isSimpleEnoughPointerToCommit) should get Val as its value.  Make it happen.
1658 static void CommitValueTo(Constant *Val, Constant *Addr) {
1659   if (GlobalVariable *GV = dyn_cast<GlobalVariable>(Addr)) {
1660     assert(GV->hasInitializer());
1661     GV->setInitializer(Val);
1662     return;
1663   }
1664   
1665   ConstantExpr *CE = cast<ConstantExpr>(Addr);
1666   GlobalVariable *GV = cast<GlobalVariable>(CE->getOperand(0));
1667   
1668   Constant *Init = GV->getInitializer();
1669   Init = EvaluateStoreInto(Init, Val, CE, 2);
1670   GV->setInitializer(Init);
1671 }
1672
1673 /// ComputeLoadResult - Return the value that would be computed by a load from
1674 /// P after the stores reflected by 'memory' have been performed.  If we can't
1675 /// decide, return null.
1676 static Constant *ComputeLoadResult(Constant *P,
1677                                 const std::map<Constant*, Constant*> &Memory) {
1678   // If this memory location has been recently stored, use the stored value: it
1679   // is the most up-to-date.
1680   std::map<Constant*, Constant*>::const_iterator I = Memory.find(P);
1681   if (I != Memory.end()) return I->second;
1682  
1683   // Access it.
1684   if (GlobalVariable *GV = dyn_cast<GlobalVariable>(P)) {
1685     if (GV->hasInitializer())
1686       return GV->getInitializer();
1687     return 0;
1688   }
1689   
1690   // Handle a constantexpr getelementptr.
1691   if (ConstantExpr *CE = dyn_cast<ConstantExpr>(P))
1692     if (CE->getOpcode() == Instruction::GetElementPtr &&
1693         isa<GlobalVariable>(CE->getOperand(0))) {
1694       GlobalVariable *GV = cast<GlobalVariable>(CE->getOperand(0));
1695       if (GV->hasInitializer())
1696         return ConstantFoldLoadThroughGEPConstantExpr(GV->getInitializer(), CE);
1697     }
1698
1699   return 0;  // don't know how to evaluate.
1700 }
1701
1702 /// EvaluateFunction - Evaluate a call to function F, returning true if
1703 /// successful, false if we can't evaluate it.  ActualArgs contains the formal
1704 /// arguments for the function.
1705 static bool EvaluateFunction(Function *F, Constant *&RetVal,
1706                              const std::vector<Constant*> &ActualArgs,
1707                              std::vector<Function*> &CallStack,
1708                              std::map<Constant*, Constant*> &MutatedMemory,
1709                              std::vector<GlobalVariable*> &AllocaTmps) {
1710   // Check to see if this function is already executing (recursion).  If so,
1711   // bail out.  TODO: we might want to accept limited recursion.
1712   if (std::find(CallStack.begin(), CallStack.end(), F) != CallStack.end())
1713     return false;
1714   
1715   CallStack.push_back(F);
1716   
1717   /// Values - As we compute SSA register values, we store their contents here.
1718   std::map<Value*, Constant*> Values;
1719   
1720   // Initialize arguments to the incoming values specified.
1721   unsigned ArgNo = 0;
1722   for (Function::arg_iterator AI = F->arg_begin(), E = F->arg_end(); AI != E;
1723        ++AI, ++ArgNo)
1724     Values[AI] = ActualArgs[ArgNo];
1725
1726   /// ExecutedBlocks - We only handle non-looping, non-recursive code.  As such,
1727   /// we can only evaluate any one basic block at most once.  This set keeps
1728   /// track of what we have executed so we can detect recursive cases etc.
1729   std::set<BasicBlock*> ExecutedBlocks;
1730   
1731   // CurInst - The current instruction we're evaluating.
1732   BasicBlock::iterator CurInst = F->begin()->begin();
1733   
1734   // This is the main evaluation loop.
1735   while (1) {
1736     Constant *InstResult = 0;
1737     
1738     if (StoreInst *SI = dyn_cast<StoreInst>(CurInst)) {
1739       if (SI->isVolatile()) return false;  // no volatile accesses.
1740       Constant *Ptr = getVal(Values, SI->getOperand(1));
1741       if (!isSimpleEnoughPointerToCommit(Ptr))
1742         // If this is too complex for us to commit, reject it.
1743         return false;
1744       Constant *Val = getVal(Values, SI->getOperand(0));
1745       MutatedMemory[Ptr] = Val;
1746     } else if (BinaryOperator *BO = dyn_cast<BinaryOperator>(CurInst)) {
1747       InstResult = ConstantExpr::get(BO->getOpcode(),
1748                                      getVal(Values, BO->getOperand(0)),
1749                                      getVal(Values, BO->getOperand(1)));
1750     } else if (CmpInst *CI = dyn_cast<CmpInst>(CurInst)) {
1751       InstResult = ConstantExpr::getCompare(CI->getPredicate(),
1752                                             getVal(Values, CI->getOperand(0)),
1753                                             getVal(Values, CI->getOperand(1)));
1754     } else if (CastInst *CI = dyn_cast<CastInst>(CurInst)) {
1755       InstResult = ConstantExpr::getCast(CI->getOpcode(),
1756                                          getVal(Values, CI->getOperand(0)),
1757                                          CI->getType());
1758     } else if (SelectInst *SI = dyn_cast<SelectInst>(CurInst)) {
1759       InstResult = ConstantExpr::getSelect(getVal(Values, SI->getOperand(0)),
1760                                            getVal(Values, SI->getOperand(1)),
1761                                            getVal(Values, SI->getOperand(2)));
1762     } else if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(CurInst)) {
1763       Constant *P = getVal(Values, GEP->getOperand(0));
1764       SmallVector<Constant*, 8> GEPOps;
1765       for (unsigned i = 1, e = GEP->getNumOperands(); i != e; ++i)
1766         GEPOps.push_back(getVal(Values, GEP->getOperand(i)));
1767       InstResult = ConstantExpr::getGetElementPtr(P, &GEPOps[0], GEPOps.size());
1768     } else if (LoadInst *LI = dyn_cast<LoadInst>(CurInst)) {
1769       if (LI->isVolatile()) return false;  // no volatile accesses.
1770       InstResult = ComputeLoadResult(getVal(Values, LI->getOperand(0)),
1771                                      MutatedMemory);
1772       if (InstResult == 0) return false; // Could not evaluate load.
1773     } else if (AllocaInst *AI = dyn_cast<AllocaInst>(CurInst)) {
1774       if (AI->isArrayAllocation()) return false;  // Cannot handle array allocs.
1775       const Type *Ty = AI->getType()->getElementType();
1776       AllocaTmps.push_back(new GlobalVariable(Ty, false,
1777                                               GlobalValue::InternalLinkage,
1778                                               UndefValue::get(Ty),
1779                                               AI->getName()));
1780       InstResult = AllocaTmps.back();     
1781     } else if (CallInst *CI = dyn_cast<CallInst>(CurInst)) {
1782       // Cannot handle inline asm.
1783       if (isa<InlineAsm>(CI->getOperand(0))) return false;
1784
1785       // Resolve function pointers.
1786       Function *Callee = dyn_cast<Function>(getVal(Values, CI->getOperand(0)));
1787       if (!Callee) return false;  // Cannot resolve.
1788
1789       std::vector<Constant*> Formals;
1790       for (unsigned i = 1, e = CI->getNumOperands(); i != e; ++i)
1791         Formals.push_back(getVal(Values, CI->getOperand(i)));
1792       
1793       if (Callee->isDeclaration()) {
1794         // If this is a function we can constant fold, do it.
1795         if (Constant *C = ConstantFoldCall(Callee, &Formals[0],
1796                                            Formals.size())) {
1797           InstResult = C;
1798         } else {
1799           return false;
1800         }
1801       } else {
1802         if (Callee->getFunctionType()->isVarArg())
1803           return false;
1804         
1805         Constant *RetVal;
1806         
1807         // Execute the call, if successful, use the return value.
1808         if (!EvaluateFunction(Callee, RetVal, Formals, CallStack,
1809                               MutatedMemory, AllocaTmps))
1810           return false;
1811         InstResult = RetVal;
1812       }
1813     } else if (isa<TerminatorInst>(CurInst)) {
1814       BasicBlock *NewBB = 0;
1815       if (BranchInst *BI = dyn_cast<BranchInst>(CurInst)) {
1816         if (BI->isUnconditional()) {
1817           NewBB = BI->getSuccessor(0);
1818         } else {
1819           ConstantInt *Cond =
1820             dyn_cast<ConstantInt>(getVal(Values, BI->getCondition()));
1821           if (!Cond) return false;  // Cannot determine.
1822
1823           NewBB = BI->getSuccessor(!Cond->getZExtValue());          
1824         }
1825       } else if (SwitchInst *SI = dyn_cast<SwitchInst>(CurInst)) {
1826         ConstantInt *Val =
1827           dyn_cast<ConstantInt>(getVal(Values, SI->getCondition()));
1828         if (!Val) return false;  // Cannot determine.
1829         NewBB = SI->getSuccessor(SI->findCaseValue(Val));
1830       } else if (ReturnInst *RI = dyn_cast<ReturnInst>(CurInst)) {
1831         if (RI->getNumOperands())
1832           RetVal = getVal(Values, RI->getOperand(0));
1833         
1834         CallStack.pop_back();  // return from fn.
1835         return true;  // We succeeded at evaluating this ctor!
1836       } else {
1837         // invoke, unwind, unreachable.
1838         return false;  // Cannot handle this terminator.
1839       }
1840       
1841       // Okay, we succeeded in evaluating this control flow.  See if we have
1842       // executed the new block before.  If so, we have a looping function,
1843       // which we cannot evaluate in reasonable time.
1844       if (!ExecutedBlocks.insert(NewBB).second)
1845         return false;  // looped!
1846       
1847       // Okay, we have never been in this block before.  Check to see if there
1848       // are any PHI nodes.  If so, evaluate them with information about where
1849       // we came from.
1850       BasicBlock *OldBB = CurInst->getParent();
1851       CurInst = NewBB->begin();
1852       PHINode *PN;
1853       for (; (PN = dyn_cast<PHINode>(CurInst)); ++CurInst)
1854         Values[PN] = getVal(Values, PN->getIncomingValueForBlock(OldBB));
1855
1856       // Do NOT increment CurInst.  We know that the terminator had no value.
1857       continue;
1858     } else {
1859       // Did not know how to evaluate this!
1860       return false;
1861     }
1862     
1863     if (!CurInst->use_empty())
1864       Values[CurInst] = InstResult;
1865     
1866     // Advance program counter.
1867     ++CurInst;
1868   }
1869 }
1870
1871 /// EvaluateStaticConstructor - Evaluate static constructors in the function, if
1872 /// we can.  Return true if we can, false otherwise.
1873 static bool EvaluateStaticConstructor(Function *F) {
1874   /// MutatedMemory - For each store we execute, we update this map.  Loads
1875   /// check this to get the most up-to-date value.  If evaluation is successful,
1876   /// this state is committed to the process.
1877   std::map<Constant*, Constant*> MutatedMemory;
1878
1879   /// AllocaTmps - To 'execute' an alloca, we create a temporary global variable
1880   /// to represent its body.  This vector is needed so we can delete the
1881   /// temporary globals when we are done.
1882   std::vector<GlobalVariable*> AllocaTmps;
1883   
1884   /// CallStack - This is used to detect recursion.  In pathological situations
1885   /// we could hit exponential behavior, but at least there is nothing
1886   /// unbounded.
1887   std::vector<Function*> CallStack;
1888
1889   // Call the function.
1890   Constant *RetValDummy;
1891   bool EvalSuccess = EvaluateFunction(F, RetValDummy, std::vector<Constant*>(),
1892                                        CallStack, MutatedMemory, AllocaTmps);
1893   if (EvalSuccess) {
1894     // We succeeded at evaluation: commit the result.
1895     DOUT << "FULLY EVALUATED GLOBAL CTOR FUNCTION '"
1896          << F->getName() << "' to " << MutatedMemory.size()
1897          << " stores.\n";
1898     for (std::map<Constant*, Constant*>::iterator I = MutatedMemory.begin(),
1899          E = MutatedMemory.end(); I != E; ++I)
1900       CommitValueTo(I->second, I->first);
1901   }
1902   
1903   // At this point, we are done interpreting.  If we created any 'alloca'
1904   // temporaries, release them now.
1905   while (!AllocaTmps.empty()) {
1906     GlobalVariable *Tmp = AllocaTmps.back();
1907     AllocaTmps.pop_back();
1908     
1909     // If there are still users of the alloca, the program is doing something
1910     // silly, e.g. storing the address of the alloca somewhere and using it
1911     // later.  Since this is undefined, we'll just make it be null.
1912     if (!Tmp->use_empty())
1913       Tmp->replaceAllUsesWith(Constant::getNullValue(Tmp->getType()));
1914     delete Tmp;
1915   }
1916   
1917   return EvalSuccess;
1918 }
1919
1920
1921
1922 /// OptimizeGlobalCtorsList - Simplify and evaluation global ctors if possible.
1923 /// Return true if anything changed.
1924 bool GlobalOpt::OptimizeGlobalCtorsList(GlobalVariable *&GCL) {
1925   std::vector<Function*> Ctors = ParseGlobalCtors(GCL);
1926   bool MadeChange = false;
1927   if (Ctors.empty()) return false;
1928   
1929   // Loop over global ctors, optimizing them when we can.
1930   for (unsigned i = 0; i != Ctors.size(); ++i) {
1931     Function *F = Ctors[i];
1932     // Found a null terminator in the middle of the list, prune off the rest of
1933     // the list.
1934     if (F == 0) {
1935       if (i != Ctors.size()-1) {
1936         Ctors.resize(i+1);
1937         MadeChange = true;
1938       }
1939       break;
1940     }
1941     
1942     // We cannot simplify external ctor functions.
1943     if (F->empty()) continue;
1944     
1945     // If we can evaluate the ctor at compile time, do.
1946     if (EvaluateStaticConstructor(F)) {
1947       Ctors.erase(Ctors.begin()+i);
1948       MadeChange = true;
1949       --i;
1950       ++NumCtorsEvaluated;
1951       continue;
1952     }
1953   }
1954   
1955   if (!MadeChange) return false;
1956   
1957   GCL = InstallGlobalCtors(GCL, Ctors);
1958   return true;
1959 }
1960
1961
1962 bool GlobalOpt::runOnModule(Module &M) {
1963   bool Changed = false;
1964   
1965   // Try to find the llvm.globalctors list.
1966   GlobalVariable *GlobalCtors = FindGlobalCtors(M);
1967
1968   bool LocalChange = true;
1969   while (LocalChange) {
1970     LocalChange = false;
1971     
1972     // Delete functions that are trivially dead, ccc -> fastcc
1973     LocalChange |= OptimizeFunctions(M);
1974     
1975     // Optimize global_ctors list.
1976     if (GlobalCtors)
1977       LocalChange |= OptimizeGlobalCtorsList(GlobalCtors);
1978     
1979     // Optimize non-address-taken globals.
1980     LocalChange |= OptimizeGlobalVars(M);
1981     Changed |= LocalChange;
1982   }
1983   
1984   // TODO: Move all global ctors functions to the end of the module for code
1985   // layout.
1986   
1987   return Changed;
1988 }