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