Chris Lattner | 25db580 | 2004-10-07 04:16:33 +0000 | [diff] [blame] | 1 | //===- GlobalOpt.cpp - Optimize Global Variables --------------------------===// |
| 2 | // |
| 3 | // The LLVM Compiler Infrastructure |
| 4 | // |
| 5 | // This file was developed by the LLVM research group and is distributed under |
| 6 | // the University of Illinois Open Source License. See LICENSE.TXT for details. |
| 7 | // |
| 8 | //===----------------------------------------------------------------------===// |
| 9 | // |
| 10 | // This pass transforms simple global variables that never have their address |
| 11 | // taken. If obviously true, it marks read/write globals as constant, deletes |
| 12 | // variables only stored to, etc. |
| 13 | // |
| 14 | //===----------------------------------------------------------------------===// |
| 15 | |
| 16 | #define DEBUG_TYPE "globalopt" |
| 17 | #include "llvm/Transforms/IPO.h" |
| 18 | #include "llvm/Constants.h" |
| 19 | #include "llvm/DerivedTypes.h" |
| 20 | #include "llvm/Instructions.h" |
| 21 | #include "llvm/Module.h" |
| 22 | #include "llvm/Pass.h" |
| 23 | #include "llvm/Support/Debug.h" |
| 24 | #include "llvm/ADT/Statistic.h" |
Chris Lattner | abab071 | 2004-10-08 17:32:09 +0000 | [diff] [blame] | 25 | #include "llvm/ADT/StringExtras.h" |
Chris Lattner | 25db580 | 2004-10-07 04:16:33 +0000 | [diff] [blame] | 26 | #include <set> |
| 27 | #include <algorithm> |
| 28 | using namespace llvm; |
| 29 | |
| 30 | namespace { |
Chris Lattner | abab071 | 2004-10-08 17:32:09 +0000 | [diff] [blame] | 31 | Statistic<> NumMarked ("globalopt", "Number of globals marked constant"); |
| 32 | Statistic<> NumSRA ("globalopt", "Number of aggregate globals broken " |
| 33 | "into scalars"); |
| 34 | Statistic<> NumDeleted ("globalopt", "Number of globals deleted"); |
Chris Lattner | 25db580 | 2004-10-07 04:16:33 +0000 | [diff] [blame] | 35 | Statistic<> NumFnDeleted("globalopt", "Number of functions deleted"); |
| 36 | |
| 37 | struct GlobalOpt : public ModulePass { |
| 38 | bool runOnModule(Module &M); |
| 39 | }; |
| 40 | |
| 41 | RegisterOpt<GlobalOpt> X("globalopt", "Global Variable Optimizer"); |
| 42 | } |
| 43 | |
| 44 | ModulePass *llvm::createGlobalOptimizerPass() { return new GlobalOpt(); } |
| 45 | |
| 46 | /// GlobalStatus - As we analyze each global, keep track of some information |
| 47 | /// about it. If we find out that the address of the global is taken, none of |
Chris Lattner | 617f1a3 | 2004-10-07 21:30:30 +0000 | [diff] [blame] | 48 | /// this info will be accurate. |
Chris Lattner | 25db580 | 2004-10-07 04:16:33 +0000 | [diff] [blame] | 49 | struct GlobalStatus { |
Chris Lattner | 617f1a3 | 2004-10-07 21:30:30 +0000 | [diff] [blame] | 50 | /// isLoaded - True if the global is ever loaded. If the global isn't ever |
| 51 | /// loaded it can be deleted. |
Chris Lattner | 25db580 | 2004-10-07 04:16:33 +0000 | [diff] [blame] | 52 | bool isLoaded; |
Chris Lattner | 617f1a3 | 2004-10-07 21:30:30 +0000 | [diff] [blame] | 53 | |
| 54 | /// StoredType - Keep track of what stores to the global look like. |
| 55 | /// |
Chris Lattner | 25db580 | 2004-10-07 04:16:33 +0000 | [diff] [blame] | 56 | enum StoredType { |
Chris Lattner | 617f1a3 | 2004-10-07 21:30:30 +0000 | [diff] [blame] | 57 | /// NotStored - There is no store to this global. It can thus be marked |
| 58 | /// constant. |
| 59 | NotStored, |
| 60 | |
| 61 | /// isInitializerStored - This global is stored to, but the only thing |
| 62 | /// stored is the constant it was initialized with. This is only tracked |
| 63 | /// for scalar globals. |
| 64 | isInitializerStored, |
| 65 | |
| 66 | /// isStoredOnce - This global is stored to, but only its initializer and |
| 67 | /// one other value is ever stored to it. If this global isStoredOnce, we |
| 68 | /// track the value stored to it in StoredOnceValue below. This is only |
| 69 | /// tracked for scalar globals. |
| 70 | isStoredOnce, |
| 71 | |
| 72 | /// isStored - This global is stored to by multiple values or something else |
| 73 | /// that we cannot track. |
| 74 | isStored |
Chris Lattner | 25db580 | 2004-10-07 04:16:33 +0000 | [diff] [blame] | 75 | } StoredType; |
Chris Lattner | 617f1a3 | 2004-10-07 21:30:30 +0000 | [diff] [blame] | 76 | |
| 77 | /// StoredOnceValue - If only one value (besides the initializer constant) is |
| 78 | /// ever stored to this global, keep track of what value it is. |
| 79 | Value *StoredOnceValue; |
| 80 | |
| 81 | /// isNotSuitableForSRA - Keep track of whether any SRA preventing users of |
| 82 | /// the global exist. Such users include GEP instruction with variable |
| 83 | /// indexes, and non-gep/load/store users like constant expr casts. |
Chris Lattner | 25db580 | 2004-10-07 04:16:33 +0000 | [diff] [blame] | 84 | bool isNotSuitableForSRA; |
| 85 | |
Chris Lattner | 617f1a3 | 2004-10-07 21:30:30 +0000 | [diff] [blame] | 86 | GlobalStatus() : isLoaded(false), StoredType(NotStored), StoredOnceValue(0), |
Chris Lattner | 25db580 | 2004-10-07 04:16:33 +0000 | [diff] [blame] | 87 | isNotSuitableForSRA(false) {} |
| 88 | }; |
| 89 | |
Chris Lattner | 1c4bddc | 2004-10-08 20:59:28 +0000 | [diff] [blame] | 90 | |
| 91 | |
| 92 | /// ConstantIsDead - Return true if the specified constant is (transitively) |
| 93 | /// dead. The constant may be used by other constants (e.g. constant arrays and |
| 94 | /// constant exprs) as long as they are dead, but it cannot be used by anything |
| 95 | /// else. |
| 96 | static bool ConstantIsDead(Constant *C) { |
| 97 | if (isa<GlobalValue>(C)) return false; |
| 98 | |
| 99 | for (Value::use_iterator UI = C->use_begin(), E = C->use_end(); UI != E; ++UI) |
| 100 | if (Constant *CU = dyn_cast<Constant>(*UI)) { |
| 101 | if (!ConstantIsDead(CU)) return false; |
| 102 | } else |
| 103 | return false; |
| 104 | return true; |
| 105 | } |
| 106 | |
| 107 | |
Chris Lattner | 25db580 | 2004-10-07 04:16:33 +0000 | [diff] [blame] | 108 | /// AnalyzeGlobal - Look at all uses of the global and fill in the GlobalStatus |
| 109 | /// structure. If the global has its address taken, return true to indicate we |
| 110 | /// can't do anything with it. |
| 111 | /// |
| 112 | static bool AnalyzeGlobal(Value *V, GlobalStatus &GS, |
| 113 | std::set<PHINode*> &PHIUsers) { |
| 114 | for (Value::use_iterator UI = V->use_begin(), E = V->use_end(); UI != E; ++UI) |
| 115 | if (ConstantExpr *CE = dyn_cast<ConstantExpr>(*UI)) { |
| 116 | if (AnalyzeGlobal(CE, GS, PHIUsers)) return true; |
| 117 | if (CE->getOpcode() != Instruction::GetElementPtr) |
| 118 | GS.isNotSuitableForSRA = true; |
Chris Lattner | abab071 | 2004-10-08 17:32:09 +0000 | [diff] [blame] | 119 | else if (!GS.isNotSuitableForSRA) { |
| 120 | // Check to see if this ConstantExpr GEP is SRA'able. In particular, we |
| 121 | // don't like < 3 operand CE's, and we don't like non-constant integer |
| 122 | // indices. |
| 123 | if (CE->getNumOperands() < 3 || !CE->getOperand(1)->isNullValue()) |
| 124 | GS.isNotSuitableForSRA = true; |
| 125 | else { |
| 126 | for (unsigned i = 1, e = CE->getNumOperands(); i != e; ++i) |
| 127 | if (!isa<ConstantInt>(CE->getOperand(i))) { |
| 128 | GS.isNotSuitableForSRA = true; |
| 129 | break; |
| 130 | } |
| 131 | } |
| 132 | } |
| 133 | |
Chris Lattner | 25db580 | 2004-10-07 04:16:33 +0000 | [diff] [blame] | 134 | } else if (Instruction *I = dyn_cast<Instruction>(*UI)) { |
| 135 | if (isa<LoadInst>(I)) { |
| 136 | GS.isLoaded = true; |
| 137 | } else if (StoreInst *SI = dyn_cast<StoreInst>(I)) { |
Chris Lattner | 02b6c91 | 2004-10-07 06:01:25 +0000 | [diff] [blame] | 138 | // Don't allow a store OF the address, only stores TO the address. |
| 139 | if (SI->getOperand(0) == V) return true; |
| 140 | |
Chris Lattner | 617f1a3 | 2004-10-07 21:30:30 +0000 | [diff] [blame] | 141 | // If this is a direct store to the global (i.e., the global is a scalar |
| 142 | // value, not an aggregate), keep more specific information about |
| 143 | // stores. |
| 144 | if (GS.StoredType != GlobalStatus::isStored) |
| 145 | if (GlobalVariable *GV = dyn_cast<GlobalVariable>(SI->getOperand(1))){ |
| 146 | if (SI->getOperand(0) == GV->getInitializer()) { |
| 147 | if (GS.StoredType < GlobalStatus::isInitializerStored) |
| 148 | GS.StoredType = GlobalStatus::isInitializerStored; |
| 149 | } else if (GS.StoredType < GlobalStatus::isStoredOnce) { |
| 150 | GS.StoredType = GlobalStatus::isStoredOnce; |
| 151 | GS.StoredOnceValue = SI->getOperand(0); |
| 152 | } else if (GS.StoredType == GlobalStatus::isStoredOnce && |
| 153 | GS.StoredOnceValue == SI->getOperand(0)) { |
| 154 | // noop. |
| 155 | } else { |
| 156 | GS.StoredType = GlobalStatus::isStored; |
| 157 | } |
| 158 | } else { |
Chris Lattner | 25db580 | 2004-10-07 04:16:33 +0000 | [diff] [blame] | 159 | GS.StoredType = GlobalStatus::isStored; |
Chris Lattner | 617f1a3 | 2004-10-07 21:30:30 +0000 | [diff] [blame] | 160 | } |
Chris Lattner | 25db580 | 2004-10-07 04:16:33 +0000 | [diff] [blame] | 161 | } else if (I->getOpcode() == Instruction::GetElementPtr) { |
| 162 | if (AnalyzeGlobal(I, GS, PHIUsers)) return true; |
Chris Lattner | abab071 | 2004-10-08 17:32:09 +0000 | [diff] [blame] | 163 | // Theoretically we could SRA globals with GEP insts if all indexes are |
| 164 | // constants. In practice, these GEPs would already be constant exprs |
| 165 | // if that was the case though. |
| 166 | GS.isNotSuitableForSRA = true; |
Chris Lattner | 25db580 | 2004-10-07 04:16:33 +0000 | [diff] [blame] | 167 | } else if (I->getOpcode() == Instruction::Select) { |
| 168 | if (AnalyzeGlobal(I, GS, PHIUsers)) return true; |
| 169 | GS.isNotSuitableForSRA = true; |
| 170 | } else if (PHINode *PN = dyn_cast<PHINode>(I)) { |
| 171 | // PHI nodes we can check just like select or GEP instructions, but we |
| 172 | // have to be careful about infinite recursion. |
| 173 | if (PHIUsers.insert(PN).second) // Not already visited. |
| 174 | if (AnalyzeGlobal(I, GS, PHIUsers)) return true; |
| 175 | GS.isNotSuitableForSRA = true; |
| 176 | } else if (isa<SetCondInst>(I)) { |
| 177 | GS.isNotSuitableForSRA = true; |
| 178 | } else { |
| 179 | return true; // Any other non-load instruction might take address! |
| 180 | } |
Chris Lattner | 1c4bddc | 2004-10-08 20:59:28 +0000 | [diff] [blame] | 181 | } else if (Constant *C = dyn_cast<Constant>(*UI)) { |
| 182 | // We might have a dead and dangling constant hanging off of here. |
| 183 | if (!ConstantIsDead(C)) |
| 184 | return true; |
Chris Lattner | 25db580 | 2004-10-07 04:16:33 +0000 | [diff] [blame] | 185 | } else { |
| 186 | // Otherwise must be a global or some other user. |
| 187 | return true; |
| 188 | } |
| 189 | |
| 190 | return false; |
| 191 | } |
| 192 | |
Chris Lattner | abab071 | 2004-10-08 17:32:09 +0000 | [diff] [blame] | 193 | static Constant *getAggregateConstantElement(Constant *Agg, Constant *Idx) { |
| 194 | ConstantInt *CI = dyn_cast<ConstantInt>(Idx); |
| 195 | if (!CI) return 0; |
| 196 | uint64_t IdxV = CI->getRawValue(); |
Chris Lattner | 25db580 | 2004-10-07 04:16:33 +0000 | [diff] [blame] | 197 | |
Chris Lattner | abab071 | 2004-10-08 17:32:09 +0000 | [diff] [blame] | 198 | if (ConstantStruct *CS = dyn_cast<ConstantStruct>(Agg)) { |
| 199 | if (IdxV < CS->getNumOperands()) return CS->getOperand(IdxV); |
| 200 | } else if (ConstantArray *CA = dyn_cast<ConstantArray>(Agg)) { |
| 201 | if (IdxV < CA->getNumOperands()) return CA->getOperand(IdxV); |
| 202 | } else if (ConstantPacked *CP = dyn_cast<ConstantPacked>(Agg)) { |
| 203 | if (IdxV < CP->getNumOperands()) return CP->getOperand(IdxV); |
| 204 | } else if (ConstantAggregateZero *CAZ = |
| 205 | dyn_cast<ConstantAggregateZero>(Agg)) { |
| 206 | if (const StructType *STy = dyn_cast<StructType>(Agg->getType())) { |
| 207 | if (IdxV < STy->getNumElements()) |
| 208 | return Constant::getNullValue(STy->getElementType(IdxV)); |
| 209 | } else if (const SequentialType *STy = |
| 210 | dyn_cast<SequentialType>(Agg->getType())) { |
| 211 | return Constant::getNullValue(STy->getElementType()); |
| 212 | } |
| 213 | } |
| 214 | return 0; |
| 215 | } |
Chris Lattner | 25db580 | 2004-10-07 04:16:33 +0000 | [diff] [blame] | 216 | |
| 217 | static Constant *TraverseGEPInitializer(User *GEP, Constant *Init) { |
| 218 | if (GEP->getNumOperands() == 1 || |
| 219 | !isa<Constant>(GEP->getOperand(1)) || |
| 220 | !cast<Constant>(GEP->getOperand(1))->isNullValue()) |
| 221 | return 0; |
| 222 | |
| 223 | for (unsigned i = 2, e = GEP->getNumOperands(); i != e; ++i) { |
| 224 | ConstantInt *Idx = dyn_cast<ConstantInt>(GEP->getOperand(i)); |
| 225 | if (!Idx) return 0; |
Chris Lattner | abab071 | 2004-10-08 17:32:09 +0000 | [diff] [blame] | 226 | Init = getAggregateConstantElement(Init, Idx); |
| 227 | if (Init == 0) return 0; |
Chris Lattner | 25db580 | 2004-10-07 04:16:33 +0000 | [diff] [blame] | 228 | } |
| 229 | return Init; |
| 230 | } |
| 231 | |
| 232 | /// CleanupConstantGlobalUsers - We just marked GV constant. Loop over all |
| 233 | /// users of the global, cleaning up the obvious ones. This is largely just a |
Chris Lattner | cb9f152 | 2004-10-10 16:43:46 +0000 | [diff] [blame] | 234 | /// quick scan over the use list to clean up the easy and obvious cruft. This |
| 235 | /// returns true if it made a change. |
| 236 | static bool CleanupConstantGlobalUsers(Value *V, Constant *Init) { |
| 237 | bool Changed = false; |
Chris Lattner | 25db580 | 2004-10-07 04:16:33 +0000 | [diff] [blame] | 238 | for (Value::use_iterator UI = V->use_begin(), E = V->use_end(); UI != E;) { |
| 239 | User *U = *UI++; |
| 240 | |
| 241 | if (LoadInst *LI = dyn_cast<LoadInst>(U)) { |
| 242 | // Replace the load with the initializer. |
| 243 | LI->replaceAllUsesWith(Init); |
| 244 | LI->getParent()->getInstList().erase(LI); |
Chris Lattner | cb9f152 | 2004-10-10 16:43:46 +0000 | [diff] [blame] | 245 | Changed = true; |
Chris Lattner | 25db580 | 2004-10-07 04:16:33 +0000 | [diff] [blame] | 246 | } else if (StoreInst *SI = dyn_cast<StoreInst>(U)) { |
| 247 | // Store must be unreachable or storing Init into the global. |
| 248 | SI->getParent()->getInstList().erase(SI); |
Chris Lattner | cb9f152 | 2004-10-10 16:43:46 +0000 | [diff] [blame] | 249 | Changed = true; |
Chris Lattner | 25db580 | 2004-10-07 04:16:33 +0000 | [diff] [blame] | 250 | } else if (ConstantExpr *CE = dyn_cast<ConstantExpr>(U)) { |
| 251 | if (CE->getOpcode() == Instruction::GetElementPtr) { |
| 252 | if (Constant *SubInit = TraverseGEPInitializer(CE, Init)) |
Chris Lattner | cb9f152 | 2004-10-10 16:43:46 +0000 | [diff] [blame] | 253 | Changed |= CleanupConstantGlobalUsers(CE, SubInit); |
| 254 | if (CE->use_empty()) { |
| 255 | CE->destroyConstant(); |
| 256 | Changed = true; |
| 257 | } |
Chris Lattner | 25db580 | 2004-10-07 04:16:33 +0000 | [diff] [blame] | 258 | } |
| 259 | } else if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(U)) { |
| 260 | if (Constant *SubInit = TraverseGEPInitializer(GEP, Init)) |
Chris Lattner | cb9f152 | 2004-10-10 16:43:46 +0000 | [diff] [blame] | 261 | Changed |= CleanupConstantGlobalUsers(GEP, SubInit); |
Chris Lattner | a0e769c | 2004-10-10 16:47:33 +0000 | [diff] [blame] | 262 | else { |
| 263 | // If this GEP has variable indexes, we should still be able to delete |
| 264 | // any stores through it. |
| 265 | for (Value::use_iterator GUI = GEP->use_begin(), E = GEP->use_end(); |
| 266 | GUI != E;) |
| 267 | if (StoreInst *SI = dyn_cast<StoreInst>(*GUI++)) { |
| 268 | SI->getParent()->getInstList().erase(SI); |
| 269 | Changed = true; |
| 270 | } |
| 271 | } |
| 272 | |
Chris Lattner | cb9f152 | 2004-10-10 16:43:46 +0000 | [diff] [blame] | 273 | if (GEP->use_empty()) { |
Chris Lattner | 25db580 | 2004-10-07 04:16:33 +0000 | [diff] [blame] | 274 | GEP->getParent()->getInstList().erase(GEP); |
Chris Lattner | cb9f152 | 2004-10-10 16:43:46 +0000 | [diff] [blame] | 275 | Changed = true; |
| 276 | } |
Chris Lattner | 1c4bddc | 2004-10-08 20:59:28 +0000 | [diff] [blame] | 277 | } else if (Constant *C = dyn_cast<Constant>(U)) { |
| 278 | // If we have a chain of dead constantexprs or other things dangling from |
| 279 | // us, and if they are all dead, nuke them without remorse. |
| 280 | if (ConstantIsDead(C)) { |
| 281 | C->destroyConstant(); |
| 282 | // This could have incalidated UI, start over from scratch.x |
| 283 | CleanupConstantGlobalUsers(V, Init); |
Chris Lattner | cb9f152 | 2004-10-10 16:43:46 +0000 | [diff] [blame] | 284 | return true; |
Chris Lattner | 1c4bddc | 2004-10-08 20:59:28 +0000 | [diff] [blame] | 285 | } |
Chris Lattner | 25db580 | 2004-10-07 04:16:33 +0000 | [diff] [blame] | 286 | } |
| 287 | } |
Chris Lattner | cb9f152 | 2004-10-10 16:43:46 +0000 | [diff] [blame] | 288 | return Changed; |
Chris Lattner | 25db580 | 2004-10-07 04:16:33 +0000 | [diff] [blame] | 289 | } |
| 290 | |
Chris Lattner | abab071 | 2004-10-08 17:32:09 +0000 | [diff] [blame] | 291 | /// SRAGlobal - Perform scalar replacement of aggregates on the specified global |
| 292 | /// variable. This opens the door for other optimizations by exposing the |
| 293 | /// behavior of the program in a more fine-grained way. We have determined that |
| 294 | /// this transformation is safe already. We return the first global variable we |
| 295 | /// insert so that the caller can reprocess it. |
| 296 | static GlobalVariable *SRAGlobal(GlobalVariable *GV) { |
| 297 | assert(GV->hasInternalLinkage() && !GV->isConstant()); |
| 298 | Constant *Init = GV->getInitializer(); |
| 299 | const Type *Ty = Init->getType(); |
| 300 | |
| 301 | std::vector<GlobalVariable*> NewGlobals; |
| 302 | Module::GlobalListType &Globals = GV->getParent()->getGlobalList(); |
| 303 | |
| 304 | if (const StructType *STy = dyn_cast<StructType>(Ty)) { |
| 305 | NewGlobals.reserve(STy->getNumElements()); |
| 306 | for (unsigned i = 0, e = STy->getNumElements(); i != e; ++i) { |
| 307 | Constant *In = getAggregateConstantElement(Init, |
| 308 | ConstantUInt::get(Type::UIntTy, i)); |
| 309 | assert(In && "Couldn't get element of initializer?"); |
| 310 | GlobalVariable *NGV = new GlobalVariable(STy->getElementType(i), false, |
| 311 | GlobalVariable::InternalLinkage, |
| 312 | In, GV->getName()+"."+utostr(i)); |
| 313 | Globals.insert(GV, NGV); |
| 314 | NewGlobals.push_back(NGV); |
| 315 | } |
| 316 | } else if (const SequentialType *STy = dyn_cast<SequentialType>(Ty)) { |
| 317 | unsigned NumElements = 0; |
| 318 | if (const ArrayType *ATy = dyn_cast<ArrayType>(STy)) |
| 319 | NumElements = ATy->getNumElements(); |
| 320 | else if (const PackedType *PTy = dyn_cast<PackedType>(STy)) |
| 321 | NumElements = PTy->getNumElements(); |
| 322 | else |
| 323 | assert(0 && "Unknown aggregate sequential type!"); |
| 324 | |
| 325 | if (NumElements > 16) return 0; // It's not worth it. |
| 326 | NewGlobals.reserve(NumElements); |
| 327 | for (unsigned i = 0, e = NumElements; i != e; ++i) { |
| 328 | Constant *In = getAggregateConstantElement(Init, |
| 329 | ConstantUInt::get(Type::UIntTy, i)); |
| 330 | assert(In && "Couldn't get element of initializer?"); |
| 331 | |
| 332 | GlobalVariable *NGV = new GlobalVariable(STy->getElementType(), false, |
| 333 | GlobalVariable::InternalLinkage, |
| 334 | In, GV->getName()+"."+utostr(i)); |
| 335 | Globals.insert(GV, NGV); |
| 336 | NewGlobals.push_back(NGV); |
| 337 | } |
| 338 | } |
| 339 | |
| 340 | if (NewGlobals.empty()) |
| 341 | return 0; |
| 342 | |
| 343 | Constant *NullInt = Constant::getNullValue(Type::IntTy); |
| 344 | |
| 345 | // Loop over all of the uses of the global, replacing the constantexpr geps, |
| 346 | // with smaller constantexpr geps or direct references. |
| 347 | while (!GV->use_empty()) { |
| 348 | ConstantExpr *CE = cast<ConstantExpr>(GV->use_back()); |
| 349 | assert(CE->getOpcode() == Instruction::GetElementPtr && |
| 350 | "NonGEP CE's are not SRAable!"); |
| 351 | // Ignore the 1th operand, which has to be zero or else the program is quite |
| 352 | // broken (undefined). Get the 2nd operand, which is the structure or array |
| 353 | // index. |
| 354 | unsigned Val = cast<ConstantInt>(CE->getOperand(2))->getRawValue(); |
| 355 | if (Val >= NewGlobals.size()) Val = 0; // Out of bound array access. |
| 356 | |
| 357 | Constant *NewPtr = NewGlobals[Val]; |
| 358 | |
| 359 | // Form a shorter GEP if needed. |
| 360 | if (CE->getNumOperands() > 3) { |
| 361 | std::vector<Constant*> Idxs; |
| 362 | Idxs.push_back(NullInt); |
| 363 | for (unsigned i = 3, e = CE->getNumOperands(); i != e; ++i) |
| 364 | Idxs.push_back(CE->getOperand(i)); |
| 365 | NewPtr = ConstantExpr::getGetElementPtr(NewPtr, Idxs); |
| 366 | } |
| 367 | CE->replaceAllUsesWith(NewPtr); |
| 368 | CE->destroyConstant(); |
| 369 | } |
| 370 | |
Chris Lattner | 73ad73e | 2004-10-08 20:25:55 +0000 | [diff] [blame] | 371 | // Delete the old global, now that it is dead. |
| 372 | Globals.erase(GV); |
Chris Lattner | abab071 | 2004-10-08 17:32:09 +0000 | [diff] [blame] | 373 | ++NumSRA; |
| 374 | return NewGlobals[0]; |
| 375 | } |
| 376 | |
Chris Lattner | 09a5272 | 2004-10-09 21:48:45 +0000 | [diff] [blame] | 377 | /// AllUsesOfValueWillTrapIfNull - Return true if all users of the specified |
| 378 | /// value will trap if the value is dynamically null. |
| 379 | static bool AllUsesOfValueWillTrapIfNull(Value *V) { |
| 380 | for (Value::use_iterator UI = V->use_begin(), E = V->use_end(); UI != E; ++UI) |
| 381 | if (isa<LoadInst>(*UI)) { |
| 382 | // Will trap. |
| 383 | } else if (StoreInst *SI = dyn_cast<StoreInst>(*UI)) { |
| 384 | if (SI->getOperand(0) == V) { |
| 385 | //std::cerr << "NONTRAPPING USE: " << **UI; |
| 386 | return false; // Storing the value. |
| 387 | } |
| 388 | } else if (CallInst *CI = dyn_cast<CallInst>(*UI)) { |
| 389 | if (CI->getOperand(0) != V) { |
| 390 | //std::cerr << "NONTRAPPING USE: " << **UI; |
| 391 | return false; // Not calling the ptr |
| 392 | } |
| 393 | } else if (InvokeInst *II = dyn_cast<InvokeInst>(*UI)) { |
| 394 | if (II->getOperand(0) != V) { |
| 395 | //std::cerr << "NONTRAPPING USE: " << **UI; |
| 396 | return false; // Not calling the ptr |
| 397 | } |
| 398 | } else if (CastInst *CI = dyn_cast<CastInst>(*UI)) { |
| 399 | if (!AllUsesOfValueWillTrapIfNull(CI)) return false; |
| 400 | } else if (GetElementPtrInst *GEPI = dyn_cast<GetElementPtrInst>(*UI)) { |
| 401 | if (!AllUsesOfValueWillTrapIfNull(GEPI)) return false; |
| 402 | } else { |
| 403 | //std::cerr << "NONTRAPPING USE: " << **UI; |
| 404 | return false; |
| 405 | } |
| 406 | return true; |
| 407 | } |
| 408 | |
| 409 | /// AllUsesOfLoadedValueWillTrapIfNull - Return true if all uses of any loads |
| 410 | /// from GV will trap if the loaded value is null. |
| 411 | static bool AllUsesOfLoadedValueWillTrapIfNull(GlobalVariable *GV) { |
| 412 | for (Value::use_iterator UI = GV->use_begin(), E = GV->use_end(); UI!=E; ++UI) |
| 413 | if (LoadInst *LI = dyn_cast<LoadInst>(*UI)) { |
| 414 | if (!AllUsesOfValueWillTrapIfNull(LI)) |
| 415 | return false; |
| 416 | } else if (isa<StoreInst>(*UI)) { |
| 417 | // Ignore stores to the global. |
| 418 | } else { |
| 419 | // We don't know or understand this user, bail out. |
| 420 | //std::cerr << "UNKNOWN USER OF GLOBAL!: " << **UI; |
| 421 | return false; |
| 422 | } |
| 423 | |
| 424 | return true; |
| 425 | } |
| 426 | |
| 427 | // OptimizeOnceStoredGlobal - Try to optimize globals based on the knowledge |
| 428 | // that only one value (besides its initializer) is ever stored to the global. |
| 429 | static bool OptimizeOnceStoredGlobal(GlobalVariable *GV, Value *StoredOnceVal) { |
| 430 | if (CastInst *CI = dyn_cast<CastInst>(StoredOnceVal)) |
| 431 | StoredOnceVal = CI->getOperand(0); |
| 432 | else if (GetElementPtrInst *GEPI =dyn_cast<GetElementPtrInst>(StoredOnceVal)){ |
| 433 | bool IsJustACast = true; |
| 434 | for (unsigned i = 1, e = GEPI->getNumOperands(); i != e; ++i) |
| 435 | if (!isa<Constant>(GEPI->getOperand(i)) || |
| 436 | !cast<Constant>(GEPI->getOperand(i))->isNullValue()) { |
| 437 | IsJustACast = false; |
| 438 | break; |
| 439 | } |
| 440 | if (IsJustACast) |
| 441 | StoredOnceVal = GEPI->getOperand(0); |
| 442 | } |
| 443 | |
| 444 | // If we are dealing with a pointer global that is initialized to null, only |
| 445 | // has one (non-null) value stored into, and if we know that all users of the |
| 446 | // loaded value trap if null, then the load users must never get the |
| 447 | // initializer. Instead, replace all of the loads with the stored value. |
| 448 | if (isa<PointerType>(GV->getInitializer()->getType()) && |
| 449 | GV->getInitializer()->isNullValue()) { |
Chris Lattner | 604ed7a | 2004-10-10 17:07:12 +0000 | [diff] [blame] | 450 | if (Constant *SOVC = dyn_cast<Constant>(StoredOnceVal)) |
| 451 | if (AllUsesOfLoadedValueWillTrapIfNull(GV)) { |
| 452 | DEBUG(std::cerr << "REPLACING STORED GLOBAL POINTER: " << *GV); |
Chris Lattner | 09a5272 | 2004-10-09 21:48:45 +0000 | [diff] [blame] | 453 | |
Chris Lattner | 604ed7a | 2004-10-10 17:07:12 +0000 | [diff] [blame] | 454 | if (GV->getInitializer()->getType() != SOVC->getType()) |
| 455 | SOVC = ConstantExpr::getCast(SOVC, GV->getInitializer()->getType()); |
Chris Lattner | 09a5272 | 2004-10-09 21:48:45 +0000 | [diff] [blame] | 456 | |
Chris Lattner | 604ed7a | 2004-10-10 17:07:12 +0000 | [diff] [blame] | 457 | //std::cerr << " Stored Value: " << *SOVC << "\n"; |
Chris Lattner | 09a5272 | 2004-10-09 21:48:45 +0000 | [diff] [blame] | 458 | |
Chris Lattner | 604ed7a | 2004-10-10 17:07:12 +0000 | [diff] [blame] | 459 | // Replace all uses of loads with uses of uses of the stored value. |
| 460 | while (!GV->use_empty()) |
| 461 | if (LoadInst *LI = dyn_cast<LoadInst>(GV->use_back())) { |
| 462 | LI->replaceAllUsesWith(SOVC); |
| 463 | LI->getParent()->getInstList().erase(LI); // Nuke the load. |
| 464 | } else if (StoreInst *SI = dyn_cast<StoreInst>(GV->use_back())) { |
| 465 | SI->getParent()->getInstList().erase(SI); // Nuke the store |
| 466 | } else { |
| 467 | assert(0 && "Unknown user of stored once global!"); |
| 468 | } |
| 469 | |
| 470 | // Nuke the now-dead global. |
| 471 | GV->getParent()->getGlobalList().erase(GV); |
| 472 | return true; |
| 473 | } |
Chris Lattner | 09a5272 | 2004-10-09 21:48:45 +0000 | [diff] [blame] | 474 | //if (isa<MallocInst>(StoredOnceValue)) |
| 475 | } |
| 476 | return false; |
| 477 | } |
Chris Lattner | 1c4bddc | 2004-10-08 20:59:28 +0000 | [diff] [blame] | 478 | |
| 479 | /// ProcessInternalGlobal - Analyze the specified global variable and optimize |
| 480 | /// it if possible. If we make a change, return true. |
| 481 | static bool ProcessInternalGlobal(GlobalVariable *GV, Module::giterator &GVI) { |
| 482 | std::set<PHINode*> PHIUsers; |
| 483 | GlobalStatus GS; |
| 484 | PHIUsers.clear(); |
| 485 | GV->removeDeadConstantUsers(); |
| 486 | |
| 487 | if (GV->use_empty()) { |
| 488 | DEBUG(std::cerr << "GLOBAL DEAD: " << *GV); |
Chris Lattner | 1b8d295 | 2004-10-08 22:05:31 +0000 | [diff] [blame] | 489 | GV->getParent()->getGlobalList().erase(GV); |
Chris Lattner | 1c4bddc | 2004-10-08 20:59:28 +0000 | [diff] [blame] | 490 | ++NumDeleted; |
| 491 | return true; |
| 492 | } |
| 493 | |
| 494 | if (!AnalyzeGlobal(GV, GS, PHIUsers)) { |
| 495 | // If the global is never loaded (but may be stored to), it is dead. |
| 496 | // Delete it now. |
| 497 | if (!GS.isLoaded) { |
| 498 | DEBUG(std::cerr << "GLOBAL NEVER LOADED: " << *GV); |
Chris Lattner | f369b38 | 2004-10-09 03:32:52 +0000 | [diff] [blame] | 499 | |
Chris Lattner | 1c4bddc | 2004-10-08 20:59:28 +0000 | [diff] [blame] | 500 | // Delete any stores we can find to the global. We may not be able to |
| 501 | // make it completely dead though. |
Chris Lattner | cb9f152 | 2004-10-10 16:43:46 +0000 | [diff] [blame] | 502 | bool Changed = CleanupConstantGlobalUsers(GV, GV->getInitializer()); |
Chris Lattner | f369b38 | 2004-10-09 03:32:52 +0000 | [diff] [blame] | 503 | |
Chris Lattner | 1c4bddc | 2004-10-08 20:59:28 +0000 | [diff] [blame] | 504 | // If the global is dead now, delete it. |
| 505 | if (GV->use_empty()) { |
| 506 | GV->getParent()->getGlobalList().erase(GV); |
| 507 | ++NumDeleted; |
Chris Lattner | f369b38 | 2004-10-09 03:32:52 +0000 | [diff] [blame] | 508 | Changed = true; |
Chris Lattner | 1c4bddc | 2004-10-08 20:59:28 +0000 | [diff] [blame] | 509 | } |
Chris Lattner | f369b38 | 2004-10-09 03:32:52 +0000 | [diff] [blame] | 510 | return Changed; |
Chris Lattner | 1c4bddc | 2004-10-08 20:59:28 +0000 | [diff] [blame] | 511 | |
| 512 | } else if (GS.StoredType <= GlobalStatus::isInitializerStored) { |
| 513 | DEBUG(std::cerr << "MARKING CONSTANT: " << *GV); |
| 514 | GV->setConstant(true); |
| 515 | |
| 516 | // Clean up any obviously simplifiable users now. |
| 517 | CleanupConstantGlobalUsers(GV, GV->getInitializer()); |
| 518 | |
| 519 | // If the global is dead now, just nuke it. |
| 520 | if (GV->use_empty()) { |
| 521 | DEBUG(std::cerr << " *** Marking constant allowed us to simplify " |
| 522 | "all users and delete global!\n"); |
| 523 | GV->getParent()->getGlobalList().erase(GV); |
| 524 | ++NumDeleted; |
| 525 | } |
| 526 | |
| 527 | ++NumMarked; |
| 528 | return true; |
| 529 | } else if (!GS.isNotSuitableForSRA && |
| 530 | !GV->getInitializer()->getType()->isFirstClassType()) { |
| 531 | DEBUG(std::cerr << "PERFORMING GLOBAL SRA ON: " << *GV); |
| 532 | if (GlobalVariable *FirstNewGV = SRAGlobal(GV)) { |
| 533 | GVI = FirstNewGV; // Don't skip the newly produced globals! |
| 534 | return true; |
| 535 | } |
Chris Lattner | 09a5272 | 2004-10-09 21:48:45 +0000 | [diff] [blame] | 536 | } else if (GS.StoredType == GlobalStatus::isStoredOnce) { |
| 537 | // Try to optimize globals based on the knowledge that only one value |
| 538 | // (besides its initializer) is ever stored to the global. |
| 539 | if (OptimizeOnceStoredGlobal(GV, GS.StoredOnceValue)) |
| 540 | return true; |
Chris Lattner | 1c4bddc | 2004-10-08 20:59:28 +0000 | [diff] [blame] | 541 | } |
| 542 | } |
| 543 | return false; |
| 544 | } |
| 545 | |
| 546 | |
Chris Lattner | 25db580 | 2004-10-07 04:16:33 +0000 | [diff] [blame] | 547 | bool GlobalOpt::runOnModule(Module &M) { |
| 548 | bool Changed = false; |
| 549 | |
| 550 | // As a prepass, delete functions that are trivially dead. |
| 551 | bool LocalChange = true; |
| 552 | while (LocalChange) { |
| 553 | LocalChange = false; |
| 554 | for (Module::iterator FI = M.begin(), E = M.end(); FI != E; ) { |
| 555 | Function *F = FI++; |
| 556 | F->removeDeadConstantUsers(); |
| 557 | if (F->use_empty() && (F->hasInternalLinkage() || F->hasWeakLinkage())) { |
| 558 | M.getFunctionList().erase(F); |
| 559 | LocalChange = true; |
| 560 | ++NumFnDeleted; |
| 561 | } |
| 562 | } |
| 563 | Changed |= LocalChange; |
| 564 | } |
| 565 | |
Chris Lattner | 1c4bddc | 2004-10-08 20:59:28 +0000 | [diff] [blame] | 566 | LocalChange = true; |
| 567 | while (LocalChange) { |
| 568 | LocalChange = false; |
| 569 | for (Module::giterator GVI = M.gbegin(), E = M.gend(); GVI != E;) { |
| 570 | GlobalVariable *GV = GVI++; |
| 571 | if (!GV->isConstant() && GV->hasInternalLinkage() && |
| 572 | GV->hasInitializer()) |
| 573 | LocalChange |= ProcessInternalGlobal(GV, GVI); |
Chris Lattner | 25db580 | 2004-10-07 04:16:33 +0000 | [diff] [blame] | 574 | } |
Chris Lattner | 1c4bddc | 2004-10-08 20:59:28 +0000 | [diff] [blame] | 575 | Changed |= LocalChange; |
Chris Lattner | 25db580 | 2004-10-07 04:16:33 +0000 | [diff] [blame] | 576 | } |
| 577 | return Changed; |
| 578 | } |